blob: d30240d5fbd1585c251300a19263a3f606f0d9cd [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
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.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005"""Enables directory-specific presubmit checks to run at upload and/or commit.
6"""
7
Saagar Sanghavi99816902020-08-11 22:41:25 +00008__version__ = '2.0.0'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00009
10# TODO(joi) Add caching where appropriate/needed. The API is designed to allow
11# caching (between all different invocations of presubmit scripts for a given
12# change). We should add it as our presubmit scripts start feeling slow.
13
Edward Lemura5799e32020-01-17 19:26:51 +000014import argparse
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +090015import ast # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000016import contextlib
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000017import cpplint
dcheng091b7db2016-06-16 01:27:51 -070018import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000019import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000020import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000021import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000022import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000023import logging
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000024import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000025import os # Somewhat exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000026import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000027import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040028import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000029import sys # Parts exposed through API.
30import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040031import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000032import time
Edward Lemurde9e3ca2019-10-24 21:13:31 +000033import traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +000034import unittest # Exposed through the API.
Gavin Maka94d8fe2023-09-05 18:05:01 +000035import urllib.parse as urlparse
36import urllib.request as urllib_request
37import urllib.error as urllib_error
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
Josip Sokcevic7958e302023-03-01 23:02:21 +000044import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000045import gerrit_util
Edward Lesmes9ce03f82021-01-12 20:13:31 +000046import owners_client
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020047import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import presubmit_canned_checks
Saagar Sanghavi9949ab72020-07-20 20:56:40 +000049import rdb_wrapper
Josip Sokcevic7958e302023-03-01 23:02:21 +000050import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000051import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000052
Mike Frysinger124bb8e2023-09-06 05:48:55 +000053# TODO: Should fix these warnings.
54# pylint: disable=line-too-long
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000055
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000056# Ask for feedback only once in program lifetime.
57_ASKED_FOR_FEEDBACK = False
58
Bruce Dawsondca14bc2022-09-15 20:59:38 +000059# Set if super-verbose mode is requested, for tracking where presubmit messages
60# are coming from.
61_SHOW_CALLSTACKS = False
62
63
Edward Lemurecc27072020-01-06 16:42:34 +000064def time_time():
Mike Frysinger124bb8e2023-09-06 05:48:55 +000065 # Use this so that it can be mocked in tests without interfering with python
66 # system machinery.
67 return time.time()
Edward Lemurecc27072020-01-06 16:42:34 +000068
69
maruel@chromium.org899e1c12011-04-07 17:03:18 +000070class PresubmitFailure(Exception):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000071 pass
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000072
73
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000074class CommandData(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000075 def __init__(self, name, cmd, kwargs, message, python3=True):
76 # The python3 argument is ignored but has to be retained because of the
77 # many callers in other repos that pass it in.
78 del python3
79 self.name = name
80 self.cmd = cmd
81 self.stdin = kwargs.get('stdin', None)
82 self.kwargs = kwargs.copy()
83 self.kwargs['stdout'] = subprocess.PIPE
84 self.kwargs['stderr'] = subprocess.STDOUT
85 self.kwargs['stdin'] = subprocess.PIPE
86 self.message = message
87 self.info = None
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000088
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000089
Edward Lesmes8e282792018-04-03 18:50:29 -040090# Adapted from
91# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
92#
93# An object that catches SIGINT sent to the Python process and notices
94# if processes passed to wait() die by SIGINT (we need to look for
95# both of those cases, because pressing Ctrl+C can result in either
96# the main process or one of the subprocesses getting the signal).
97#
98# Before a SIGINT is seen, wait(p) will simply call p.wait() and
99# return the result. Once a SIGINT has been seen (in the main process
100# or a subprocess, including the one the current call is waiting for),
Edward Lemur9a5bb612019-09-26 02:01:52 +0000101# wait(p) will call p.terminate().
Edward Lesmes8e282792018-04-03 18:50:29 -0400102class SigintHandler(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000103 sigint_returncodes = {
104 -signal.SIGINT, # Unix
105 -1073741510, # Windows
106 }
Edward Lesmes8e282792018-04-03 18:50:29 -0400107
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000108 def __init__(self):
109 self.__lock = threading.Lock()
110 self.__processes = set()
111 self.__got_sigint = False
112 self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
Edward Lesmes8e282792018-04-03 18:50:29 -0400113
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000114 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
Edward Lesmes8e282792018-04-03 18:50:29 -0400121
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000122 def interrupt(self, signal_num, frame):
123 with self.__lock:
124 self.__on_sigint()
125 self.__previous_signal(signal_num, frame)
Edward Lesmes8e282792018-04-03 18:50:29 -0400126
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000127 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()
142 return stdout, stderr
143
Edward Lesmes8e282792018-04-03 18:50:29 -0400144
145sigint_handler = SigintHandler()
146
147
Edward Lemurecc27072020-01-06 16:42:34 +0000148class Timer(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000149 def __init__(self, timeout, fn):
150 self.completed = False
151 self._fn = fn
152 self._timer = threading.Timer(timeout,
153 self._onTimer) if timeout else None
Edward Lemurecc27072020-01-06 16:42:34 +0000154
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000155 def __enter__(self):
156 if self._timer:
157 self._timer.start()
158 return self
Edward Lemurecc27072020-01-06 16:42:34 +0000159
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000160 def __exit__(self, _type, _value, _traceback):
161 if self._timer:
162 self._timer.cancel()
Edward Lemurecc27072020-01-06 16:42:34 +0000163
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000164 def _onTimer(self):
165 self._fn()
166 self.completed = True
Edward Lemurecc27072020-01-06 16:42:34 +0000167
168
Edward Lesmes8e282792018-04-03 18:50:29 -0400169class ThreadPool(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000170 def __init__(self, pool_size=None, timeout=None):
171 self.timeout = timeout
172 self._pool_size = pool_size or multiprocessing.cpu_count()
173 if sys.platform == 'win32':
174 # TODO(crbug.com/1190269) - we can't use more than 56 child
175 # processes on Windows or Python3 may hang.
176 self._pool_size = min(self._pool_size, 56)
177 self._messages = []
178 self._messages_lock = threading.Lock()
179 self._tests = []
180 self._tests_lock = threading.Lock()
181 self._nonparallel_tests = []
Edward Lesmes8e282792018-04-03 18:50:29 -0400182
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000183 def _GetCommand(self, test):
184 vpython = 'vpython3'
185 if sys.platform == 'win32':
186 vpython += '.bat'
Edward Lesmes8e282792018-04-03 18:50:29 -0400187
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000188 cmd = test.cmd
189 if cmd[0] == 'python':
190 cmd = list(cmd)
191 cmd[0] = vpython
192 elif cmd[0].endswith('.py'):
193 cmd = [vpython] + cmd
Edward Lesmes8e282792018-04-03 18:50:29 -0400194
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000195 # On Windows, scripts on the current directory take precedence over
196 # PATH, so that when testing depot_tools on Windows, calling
197 # `vpython.bat` will execute the copy of vpython of the depot_tools
198 # under test instead of the one in the bot. As a workaround, we run the
199 # tests from the parent directory instead.
200 if (cmd[0] == vpython and 'cwd' in test.kwargs
201 and os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
202 test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
203 cmd[1] = os.path.join('depot_tools', cmd[1])
Edward Lemur336e51f2019-11-14 21:42:04 +0000204
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000205 return cmd
Edward Lemurecc27072020-01-06 16:42:34 +0000206
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000207 def _RunWithTimeout(self, cmd, stdin, kwargs):
208 p = subprocess.Popen(cmd, **kwargs)
209 with Timer(self.timeout, p.terminate) as timer:
210 stdout, _ = sigint_handler.wait(p, stdin)
211 stdout = stdout.decode('utf-8', 'ignore')
212 if timer.completed:
213 stdout = 'Process timed out after %ss\n%s' % (self.timeout,
214 stdout)
215 return p.returncode, stdout
Edward Lemurecc27072020-01-06 16:42:34 +0000216
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000217 def CallCommand(self, test, show_callstack=None):
218 """Runs an external program.
Edward Lemurecc27072020-01-06 16:42:34 +0000219
Edward Lemura5799e32020-01-17 19:26:51 +0000220 This function converts invocation of .py files and invocations of 'python'
Edward Lemurecc27072020-01-06 16:42:34 +0000221 to vpython invocations.
222 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000223 cmd = self._GetCommand(test)
224 try:
225 start = time_time()
226 returncode, stdout = self._RunWithTimeout(cmd, test.stdin,
227 test.kwargs)
228 duration = time_time() - start
229 except Exception:
230 duration = time_time() - start
231 return test.message(
232 '%s\n%s exec failure (%4.2fs)\n%s' %
233 (test.name, ' '.join(cmd), duration, traceback.format_exc()),
234 show_callstack=show_callstack)
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000235
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000236 if returncode != 0:
237 return test.message('%s\n%s (%4.2fs) failed\n%s' %
238 (test.name, ' '.join(cmd), duration, stdout),
239 show_callstack=show_callstack)
Edward Lemurecc27072020-01-06 16:42:34 +0000240
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000241 if test.info:
242 return test.info('%s\n%s (%4.2fs)' %
243 (test.name, ' '.join(cmd), duration),
244 show_callstack=show_callstack)
Edward Lesmes8e282792018-04-03 18:50:29 -0400245
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000246 def AddTests(self, tests, parallel=True):
247 if parallel:
248 self._tests.extend(tests)
249 else:
250 self._nonparallel_tests.extend(tests)
Edward Lesmes8e282792018-04-03 18:50:29 -0400251
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000252 def RunAsync(self):
253 self._messages = []
Edward Lesmes8e282792018-04-03 18:50:29 -0400254
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000255 def _WorkerFn():
256 while True:
257 test = None
258 with self._tests_lock:
259 if not self._tests:
260 break
261 test = self._tests.pop()
262 result = self.CallCommand(test, show_callstack=False)
263 if result:
264 with self._messages_lock:
265 self._messages.append(result)
Edward Lesmes8e282792018-04-03 18:50:29 -0400266
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000267 def _StartDaemon():
268 t = threading.Thread(target=_WorkerFn)
269 t.daemon = True
270 t.start()
271 return t
Edward Lesmes8e282792018-04-03 18:50:29 -0400272
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000273 while self._nonparallel_tests:
274 test = self._nonparallel_tests.pop()
275 result = self.CallCommand(test)
276 if result:
277 self._messages.append(result)
Edward Lesmes8e282792018-04-03 18:50:29 -0400278
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000279 if self._tests:
280 threads = [_StartDaemon() for _ in range(self._pool_size)]
281 for worker in threads:
282 worker.join()
Edward Lesmes8e282792018-04-03 18:50:29 -0400283
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000284 return self._messages
Edward Lesmes8e282792018-04-03 18:50:29 -0400285
286
Josip Sokcevica9a7eec2023-03-10 03:54:52 +0000287def normpath(path):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000288 '''Version of os.path.normpath that also changes backward slashes to
Josip Sokcevica9a7eec2023-03-10 03:54:52 +0000289 forward slashes when not running on Windows.
290 '''
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000291 # This is safe to always do because the Windows version of os.path.normpath
292 # will replace forward slashes with backward slashes.
293 path = path.replace(os.sep, '/')
294 return os.path.normpath(path)
Josip Sokcevica9a7eec2023-03-10 03:54:52 +0000295
296
Josip Sokcevic7958e302023-03-01 23:02:21 +0000297def _RightHandSideLinesImpl(affected_files):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000298 """Implements RightHandSideLines for InputApi and GclChange."""
299 for af in affected_files:
300 lines = af.ChangedContents()
301 for line in lines:
302 yield (af, line[0], line[1])
Josip Sokcevic7958e302023-03-01 23:02:21 +0000303
304
Edward Lemur6eb1d322020-02-27 22:20:15 +0000305def prompt_should_continue(prompt_string):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000306 sys.stdout.write(prompt_string)
307 sys.stdout.flush()
308 response = sys.stdin.readline().strip().lower()
309 return response in ('y', 'yes')
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000310
Josip Sokcevic967cf672023-05-10 17:09:58 +0000311
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000312# Top level object so multiprocessing can pickle
313# Public access through OutputApi object.
314class _PresubmitResult(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000315 """Base class for result objects."""
316 fatal = False
317 should_prompt = False
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000318
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000319 def __init__(self, message, items=None, long_text='', show_callstack=None):
320 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000321 message: A short one-line message to indicate errors.
322 items: A list of short strings to indicate where errors occurred.
323 long_text: multi-line text output, e.g. from another tool
324 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000325 self._message = _PresubmitResult._ensure_str(message)
326 self._items = items or []
327 self._long_text = _PresubmitResult._ensure_str(long_text.rstrip())
328 if show_callstack is None:
329 show_callstack = _SHOW_CALLSTACKS
330 if show_callstack:
331 self._long_text += 'Presubmit result call stack is:\n'
332 self._long_text += ''.join(traceback.format_stack(None, 8))
Tom McKee61c72652021-07-20 11:56:32 +0000333
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000334 @staticmethod
335 def _ensure_str(val):
336 """
Gavin Maka94d8fe2023-09-05 18:05:01 +0000337 val: A "stringish" value. Can be any of str or bytes.
Tom McKee61c72652021-07-20 11:56:32 +0000338 returns: A str after applying encoding/decoding as needed.
339 Assumes/uses UTF-8 for relevant inputs/outputs.
Tom McKee61c72652021-07-20 11:56:32 +0000340 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000341 if isinstance(val, str):
342 return val
343 if isinstance(val, bytes):
344 return val.decode()
345 raise ValueError("Unknown string type %s" % type(val))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000346
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000347 def handle(self):
348 sys.stdout.write(self._message)
349 sys.stdout.write('\n')
350 for item in self._items:
351 sys.stdout.write(' ')
352 # Write separately in case it's unicode.
353 sys.stdout.write(str(item))
354 sys.stdout.write('\n')
355 if self._long_text:
356 sys.stdout.write('\n***************\n')
357 # Write separately in case it's unicode.
358 sys.stdout.write(self._long_text)
359 sys.stdout.write('\n***************\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000360
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000361 def json_format(self):
362 return {
363 'message': self._message,
364 'items': [str(item) for item in self._items],
365 'long_text': self._long_text,
366 'fatal': self.fatal
367 }
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000368
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000369
370# Top level object so multiprocessing can pickle
371# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000372class _PresubmitError(_PresubmitResult):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000373 """A hard presubmit error."""
374 fatal = True
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000375
376
377# Top level object so multiprocessing can pickle
378# Public access through OutputApi object.
379class _PresubmitPromptWarning(_PresubmitResult):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000380 """An warning that prompts the user if they want to continue."""
381 should_prompt = True
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000382
383
384# Top level object so multiprocessing can pickle
385# Public access through OutputApi object.
386class _PresubmitNotifyResult(_PresubmitResult):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000387 """Just print something to the screen -- but it's not even a warning."""
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000388
389
390# Top level object so multiprocessing can pickle
391# Public access through OutputApi object.
392class _MailTextResult(_PresubmitResult):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000393 """A warning that should be included in the review request email."""
394 def __init__(self, *args, **kwargs):
395 super(_MailTextResult, self).__init__()
396 raise NotImplementedError()
397
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000398
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000399class GerritAccessor(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000400 """Limited Gerrit functionality for canned presubmit checks to work.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000401
402 To avoid excessive Gerrit calls, caches the results.
403 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000404 def __init__(self, url=None, project=None, branch=None):
405 self.host = urlparse.urlparse(url).netloc if url else None
406 self.project = project
407 self.branch = branch
408 self.cache = {}
409 self.code_owners_enabled = None
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000410
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000411 def _FetchChangeDetail(self, issue):
412 # Separate function to be easily mocked in tests.
413 try:
414 return gerrit_util.GetChangeDetail(
415 self.host, str(issue),
416 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
417 except gerrit_util.GerritError as e:
418 if e.http_status == 404:
419 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
420 'no credentials to fetch issue details' % issue)
421 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000422
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000423 def GetChangeInfo(self, issue):
424 """Returns labels and all revisions (patchsets) for this issue.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000425
426 The result is a dictionary according to Gerrit REST Api.
427 https://gerrit-review.googlesource.com/Documentation/rest-api.html
428
429 However, API isn't very clear what's inside, so see tests for example.
430 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000431 assert issue
432 cache_key = int(issue)
433 if cache_key not in self.cache:
434 self.cache[cache_key] = self._FetchChangeDetail(issue)
435 return self.cache[cache_key]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000436
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000437 def GetChangeDescription(self, issue, patchset=None):
438 """If patchset is none, fetches current patchset."""
439 info = self.GetChangeInfo(issue)
440 # info is a reference to cache. We'll modify it here adding description
441 # to it to the right patchset, if it is not yet there.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000442
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000443 # Find revision info for the patchset we want.
444 if patchset is not None:
445 for rev, rev_info in info['revisions'].items():
446 if str(rev_info['_number']) == str(patchset):
447 break
448 else:
449 raise Exception('patchset %s doesn\'t exist in issue %s' %
450 (patchset, issue))
451 else:
452 rev = info['current_revision']
453 rev_info = info['revisions'][rev]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000454
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000455 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000456
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000457 def GetDestRef(self, issue):
458 ref = self.GetChangeInfo(issue)['branch']
459 if not ref.startswith('refs/'):
460 # NOTE: it is possible to create 'refs/x' branch,
461 # aka 'refs/heads/refs/x'. However, this is ill-advised.
462 ref = 'refs/heads/%s' % ref
463 return ref
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800464
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000465 def _GetApproversForLabel(self, issue, label):
466 change_info = self.GetChangeInfo(issue)
467 label_info = change_info.get('labels', {}).get(label, {})
468 values = label_info.get('values', {}).keys()
469 if not values:
470 return []
471 max_value = max(int(v) for v in values)
472 return [
473 v for v in label_info.get('all', [])
474 if v.get('value', 0) == max_value
475 ]
Edward Lesmes02d4b822020-11-11 00:37:35 +0000476
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000477 def IsBotCommitApproved(self, issue):
478 return bool(self._GetApproversForLabel(issue, 'Bot-Commit'))
Edward Lesmesc4566172021-03-19 16:55:13 +0000479
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000480 def IsOwnersOverrideApproved(self, issue):
481 return bool(self._GetApproversForLabel(issue, 'Owners-Override'))
Edward Lesmescf49cb82020-11-11 01:08:36 +0000482
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000483 def GetChangeOwner(self, issue):
484 return self.GetChangeInfo(issue)['owner']['email']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000485
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000486 def GetChangeReviewers(self, issue, approving_only=True):
487 changeinfo = self.GetChangeInfo(issue)
488 if approving_only:
489 reviewers = self._GetApproversForLabel(issue, 'Code-Review')
490 else:
491 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
492 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000493
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000494 def UpdateDescription(self, description, issue):
495 gerrit_util.SetCommitMessage(self.host,
496 issue,
497 description,
498 notify='NONE')
Edward Lemure4d329c2020-02-03 20:41:18 +0000499
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000500 def IsCodeOwnersEnabledOnRepo(self):
501 if self.code_owners_enabled is None:
502 self.code_owners_enabled = gerrit_util.IsCodeOwnersEnabledOnRepo(
503 self.host, self.project)
504 return self.code_owners_enabled
Edward Lesmes8170c292021-03-19 20:04:43 +0000505
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000506
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000507class OutputApi(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000508 """An instance of OutputApi gets passed to presubmit scripts so that they
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000509 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000510 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000511 PresubmitResult = _PresubmitResult
512 PresubmitError = _PresubmitError
513 PresubmitPromptWarning = _PresubmitPromptWarning
514 PresubmitNotifyResult = _PresubmitNotifyResult
515 MailTextResult = _MailTextResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000516
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000517 def __init__(self, is_committing):
518 self.is_committing = is_committing
519 self.more_cc = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800520
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000521 def AppendCC(self, cc):
522 """Appends a user to cc for this change."""
523 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000524
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000525 def PresubmitPromptOrNotify(self, *args, **kwargs):
526 """Warn the user when uploading, but only notify if committing."""
527 if self.is_committing:
528 return self.PresubmitNotifyResult(*args, **kwargs)
529 return self.PresubmitPromptWarning(*args, **kwargs)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000530
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000531
532class InputApi(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000533 """An instance of this object is passed to presubmit scripts so they can
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000534 know stuff about the change they're looking at.
535 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000536 # Method could be a function
537 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000538
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000539 # File extensions that are considered source files from a style guide
540 # perspective. Don't modify this list from a presubmit script!
541 #
542 # Files without an extension aren't included in the list. If you want to
543 # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the allow list.
544 # Note that ALL CAPS files are skipped in DEFAULT_FILES_TO_SKIP below.
545 DEFAULT_FILES_TO_CHECK = (
546 # C++ and friends
547 r'.+\.c$',
548 r'.+\.cc$',
549 r'.+\.cpp$',
550 r'.+\.h$',
551 r'.+\.m$',
552 r'.+\.mm$',
553 r'.+\.inl$',
554 r'.+\.asm$',
555 r'.+\.hxx$',
556 r'.+\.hpp$',
557 r'.+\.s$',
558 r'.+\.S$',
559 # Scripts
560 r'.+\.js$',
561 r'.+\.ts$',
562 r'.+\.py$',
563 r'.+\.sh$',
564 r'.+\.rb$',
565 r'.+\.pl$',
566 r'.+\.pm$',
567 # Other
568 r'.+\.java$',
569 r'.+\.mk$',
570 r'.+\.am$',
571 r'.+\.css$',
572 r'.+\.mojom$',
573 r'.+\.fidl$',
574 r'.+\.rs$',
575 )
maruel@chromium.org3410d912009-06-09 20:56:16 +0000576
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000577 # Path regexp that should be excluded from being considered containing
578 # source files. Don't modify this list from a presubmit script!
579 DEFAULT_FILES_TO_SKIP = (
580 r'testing_support[\\\/]google_appengine[\\\/].*',
581 r'.*\bexperimental[\\\/].*',
582 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
583 # (crbug.com/539768 and crbug.com/836555).
584 r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
585 # Output directories (just in case)
586 r'.*\bDebug[\\\/].*',
587 r'.*\bRelease[\\\/].*',
588 r'.*\bxcodebuild[\\\/].*',
589 r'.*\bout[\\\/].*',
590 # All caps files like README and LICENCE.
591 r'.*\b[A-Z0-9_]{2,}$',
592 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
593 r'(|.*[\\\/])\.git[\\\/].*',
594 r'(|.*[\\\/])\.svn[\\\/].*',
595 # There is no point in processing a patch file.
596 r'.+\.diff$',
597 r'.+\.patch$',
598 )
maruel@chromium.org3410d912009-06-09 20:56:16 +0000599
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000600 def __init__(self,
601 change,
602 presubmit_path,
603 is_committing,
604 verbose,
605 gerrit_obj,
606 dry_run=None,
607 thread_pool=None,
608 parallel=False,
609 no_diffs=False):
610 """Builds an InputApi object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000611
612 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000613 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000614 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000615 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000616 gerrit_obj: provides basic Gerrit codereview functionality.
617 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400618 parallel: if true, all tests reported via input_api.RunTests for all
619 PRESUBMIT files will be run in parallel.
Bruce Dawson09c0c072022-05-26 20:28:58 +0000620 no_diffs: if true, implies that --files or --all was specified so some
621 checks can be skipped, and some errors will be messages.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000623 # Version number of the presubmit_support script.
624 self.version = [int(x) for x in __version__.split('.')]
625 self.change = change
626 self.is_committing = is_committing
627 self.gerrit = gerrit_obj
628 self.dry_run = dry_run
629 self.no_diffs = no_diffs
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000631 self.parallel = parallel
632 self.thread_pool = thread_pool or ThreadPool()
Edward Lesmes8e282792018-04-03 18:50:29 -0400633
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000634 # We expose various modules and functions as attributes of the input_api
635 # so that presubmit scripts don't have to import them.
636 self.ast = ast
637 self.basename = os.path.basename
638 self.cpplint = cpplint
639 self.fnmatch = fnmatch
640 self.gclient_paths = gclient_paths
641 self.glob = glob.glob
642 self.json = json
643 self.logging = logging.getLogger('PRESUBMIT')
644 self.os_listdir = os.listdir
645 self.os_path = os.path
646 self.os_stat = os.stat
647 self.os_walk = os.walk
648 self.re = re
649 self.subprocess = subprocess
650 self.sys = sys
651 self.tempfile = tempfile
652 self.time = time
653 self.unittest = unittest
654 self.urllib_request = urllib_request
655 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000656
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000657 self.is_windows = sys.platform == 'win32'
Robert Iannucci50258932018-03-19 10:30:59 -0700658
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000659 # Set python_executable to 'vpython3' in order to allow scripts in other
660 # repos (e.g. src.git) to automatically pick up that repo's .vpython
661 # file, instead of inheriting the one in depot_tools.
662 self.python_executable = 'vpython3'
663 # Offer a python 3 executable for use during the migration off of python
664 # 2.
665 self.python3_executable = 'vpython3'
666 self.environ = os.environ
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000667
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000668 # InputApi.platform is the platform you're currently running on.
669 self.platform = sys.platform
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000670
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000671 self.cpu_count = multiprocessing.cpu_count()
672 if self.is_windows:
673 # TODO(crbug.com/1190269) - we can't use more than 56 child
674 # processes on Windows or Python3 may hang.
675 self.cpu_count = min(self.cpu_count, 56)
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000676
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000677 # The local path of the currently-being-processed presubmit script.
678 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000679
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000680 # We carry the canned checks so presubmit scripts can easily use them.
681 self.canned_checks = presubmit_canned_checks
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000682
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000683 # Temporary files we must manually remove at the end of a run.
684 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200685
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000686 self.owners_client = None
687 if self.gerrit and not 'PRESUBMIT_SKIP_NETWORK' in self.environ:
688 try:
689 self.owners_client = owners_client.GetCodeOwnersClient(
690 host=self.gerrit.host,
691 project=self.gerrit.project,
692 branch=self.gerrit.branch)
693 except Exception as e:
694 print('Failed to set owners_client - %s' % str(e))
695 self.owners_finder = owners_finder.OwnersFinder
696 self.verbose = verbose
697 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000698
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000699 # Replace <hash_map> and <hash_set> as headers that need to be included
700 # with 'base/containers/hash_tables.h' instead.
701 # Access to a protected member _XX of a client class
702 # pylint: disable=protected-access
703 self.cpplint._re_pattern_templates = [
704 (a, b,
705 'base/containers/hash_tables.h') if header in ('<hash_map>',
706 '<hash_set>') else
707 (a, b, header) for (a, b, header) in cpplint._re_pattern_templates
708 ]
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000709
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000710 def SetTimeout(self, timeout):
711 self.thread_pool.timeout = timeout
Edward Lemurecc27072020-01-06 16:42:34 +0000712
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000713 def PresubmitLocalPath(self):
714 """Returns the local path of the presubmit script currently being run.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000715
716 This is useful if you don't want to hard-code absolute paths in the
717 presubmit script. For example, It can be used to find another file
718 relative to the PRESUBMIT.py script, so the whole tree can be branched and
719 the presubmit script still works, without editing its content.
720 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000721 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000722
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000723 def AffectedFiles(self, include_deletes=True, file_filter=None):
724 """Same as input_api.change.AffectedFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000725 (and optionally directories) in the same directory as the current presubmit
Bruce Dawson7a0b07a2020-04-23 17:14:40 +0000726 script, or subdirectories thereof. Note that files are listed using the OS
727 path separator, so backslashes are used as separators on Windows.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000728 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000729 dir_with_slash = normpath(self.PresubmitLocalPath())
730 # normpath strips trailing path separators, so the trailing separator
731 # has to be added after the normpath call.
732 if len(dir_with_slash) > 0:
733 dir_with_slash += os.path.sep
sail@chromium.org5538e022011-05-12 17:53:16 +0000734
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000735 return list(
736 filter(
737 lambda x: normpath(x.AbsoluteLocalPath()).startswith(
738 dir_with_slash),
739 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000740
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000741 def LocalPaths(self):
742 """Returns local paths of input_api.AffectedFiles()."""
743 paths = [af.LocalPath() for af in self.AffectedFiles()]
744 logging.debug('LocalPaths: %s', paths)
745 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000746
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000747 def AbsoluteLocalPaths(self):
748 """Returns absolute local paths of input_api.AffectedFiles()."""
749 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000750
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000751 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
752 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000753 in the same directory as the current presubmit script, or subdirectories
754 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000755 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000756 if include_deletes is not None:
757 warn('AffectedTestableFiles(include_deletes=%s)'
758 ' is deprecated and ignored' % str(include_deletes),
759 category=DeprecationWarning,
760 stacklevel=2)
761 # pylint: disable=consider-using-generator
762 return [
763 x for x in self.AffectedFiles(include_deletes=False, **kwargs)
764 if x.IsTestableFile()
765 ]
agable0b65e732016-11-22 09:25:46 -0800766
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000767 def AffectedTextFiles(self, include_deletes=None):
768 """An alias to AffectedTestableFiles for backwards compatibility."""
769 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000770
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000771 def FilterSourceFile(self,
772 affected_file,
773 files_to_check=None,
774 files_to_skip=None,
775 allow_list=None,
776 block_list=None):
777 """Filters out files that aren't considered 'source file'.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000778
local_bot64021412020-07-08 21:05:39 +0000779 If files_to_check or files_to_skip is None, InputApi.DEFAULT_FILES_TO_CHECK
780 and InputApi.DEFAULT_FILES_TO_SKIP is used respectively.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000781
Bruce Dawson635383f2022-09-13 16:23:18 +0000782 affected_file.LocalPath() needs to re.match an entry in the files_to_check
783 list and not re.match any entries in the files_to_skip list.
784 '/' path separators should be used in the regular expressions and will work
785 on Windows as well as other platforms.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000786
787 Note: Copy-paste this function to suit your needs or use a lambda function.
788 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000789 if files_to_check is None:
790 files_to_check = self.DEFAULT_FILES_TO_CHECK
791 if files_to_skip is None:
792 files_to_skip = self.DEFAULT_FILES_TO_SKIP
local_bot30f774e2020-06-25 18:23:34 +0000793
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000794 def Find(affected_file, items):
795 local_path = affected_file.LocalPath()
796 for item in items:
797 if self.re.match(item, local_path):
798 return True
799 # Handle the cases where the files regex only handles /, but the
800 # local path uses \.
801 if self.is_windows and self.re.match(
802 item, local_path.replace('\\', '/')):
803 return True
804 return False
maruel@chromium.org3410d912009-06-09 20:56:16 +0000805
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000806 return (Find(affected_file, files_to_check)
807 and not Find(affected_file, files_to_skip))
808
809 def AffectedSourceFiles(self, source_file):
810 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000811
812 If source_file is None, InputApi.FilterSourceFile() is used.
813 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000814 if not source_file:
815 source_file = self.FilterSourceFile
816 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000817
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000818 def RightHandSideLines(self, source_file_filter=None):
819 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000820
821 Only lists lines from new or modified text files in the change that are
822 contained by the directory of the currently executing presubmit script.
823
824 This is useful for doing line-by-line regex checks, like checking for
825 trailing whitespace.
826
827 Yields:
828 a 3 tuple:
Josip Sokcevic7958e302023-03-01 23:02:21 +0000829 the AffectedFile instance of the current file;
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000830 integer line number (1-based); and
831 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000832
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000833 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000834 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000835 files = self.AffectedSourceFiles(source_file_filter)
836 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000837
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000838 def ReadFile(self, file_item, mode='r'):
839 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000840
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000841 Deny reading anything outside the repository.
842 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000843 if isinstance(file_item, AffectedFile):
844 file_item = file_item.AbsoluteLocalPath()
845 if not file_item.startswith(self.change.RepositoryRoot()):
846 raise IOError('Access outside the repository root is denied.')
847 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000848
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000849 def CreateTemporaryFile(self, **kwargs):
850 """Returns a named temporary file that must be removed with a call to
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100851 RemoveTemporaryFiles().
852
853 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
854 except for |delete|, which is always set to False.
855
856 Presubmit checks that need to create a temporary file and pass it for
857 reading should use this function instead of NamedTemporaryFile(), as
858 Windows fails to open a file that is already open for writing.
859
860 with input_api.CreateTemporaryFile() as f:
861 f.write('xyz')
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100862 input_api.subprocess.check_output(['script-that', '--reads-from',
863 f.name])
864
865
866 Note that callers of CreateTemporaryFile() should not worry about removing
867 any temporary file; this is done transparently by the presubmit handling
868 code.
869 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000870 if 'delete' in kwargs:
871 # Prevent users from passing |delete|; we take care of file deletion
872 # ourselves and this prevents unintuitive error messages when we
873 # pass delete=False and 'delete' is also in kwargs.
874 raise TypeError(
875 'CreateTemporaryFile() does not take a "delete" '
876 'argument, file deletion is handled automatically by '
877 'the same presubmit_support code that creates InputApi '
878 'objects.')
879 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
880 self._named_temporary_files.append(temp_file.name)
881 return temp_file
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100882
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000883 @property
884 def tbr(self):
885 """Returns if a change is TBR'ed."""
886 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000887
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000888 def RunTests(self, tests_mix, parallel=True):
889 tests = []
890 msgs = []
891 for t in tests_mix:
892 if isinstance(t, OutputApi.PresubmitResult) and t:
893 msgs.append(t)
894 else:
895 assert issubclass(t.message, _PresubmitResult)
896 tests.append(t)
897 if self.verbose:
898 t.info = _PresubmitNotifyResult
899 if not t.kwargs.get('cwd'):
900 t.kwargs['cwd'] = self.PresubmitLocalPath()
901 self.thread_pool.AddTests(tests, parallel)
902 # When self.parallel is True (i.e. --parallel is passed as an option)
903 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
904 # will run all tests once all PRESUBMIT files are processed.
905 # Otherwise, it will run them and return the results.
906 if not self.parallel:
907 msgs.extend(self.thread_pool.RunAsync())
908 return msgs
scottmg86099d72016-09-01 09:16:51 -0700909
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000910
Josip Sokcevic7958e302023-03-01 23:02:21 +0000911class _DiffCache(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000912 """Caches diffs retrieved from a particular SCM."""
913 def __init__(self, upstream=None):
914 """Stores the upstream revision against which all diffs will be computed."""
915 self._upstream = upstream
Josip Sokcevic7958e302023-03-01 23:02:21 +0000916
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000917 def GetDiff(self, path, local_root):
918 """Get the diff for a particular path."""
919 raise NotImplementedError()
Josip Sokcevic7958e302023-03-01 23:02:21 +0000920
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000921 def GetOldContents(self, path, local_root):
922 """Get the old version for a particular path."""
923 raise NotImplementedError()
Josip Sokcevic7958e302023-03-01 23:02:21 +0000924
925
926class _GitDiffCache(_DiffCache):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000927 """DiffCache implementation for git; gets all file diffs at once."""
928 def __init__(self, upstream):
929 super(_GitDiffCache, self).__init__(upstream=upstream)
930 self._diffs_by_file = None
Josip Sokcevic7958e302023-03-01 23:02:21 +0000931
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000932 def GetDiff(self, path, local_root):
933 # Compare against None to distinguish between None and an initialized
934 # but empty dictionary.
935 if self._diffs_by_file == None:
936 # Compute a single diff for all files and parse the output; should
937 # with git this is much faster than computing one diff for each
938 # file.
939 diffs = {}
Josip Sokcevic7958e302023-03-01 23:02:21 +0000940
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000941 # Don't specify any filenames below, because there are command line
942 # length limits on some platforms and GenerateDiff would fail.
943 unified_diff = scm.GIT.GenerateDiff(local_root,
944 files=[],
945 full_move=True,
946 branch=self._upstream)
Josip Sokcevic7958e302023-03-01 23:02:21 +0000947
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000948 # This regex matches the path twice, separated by a space. Note that
949 # filename itself may contain spaces.
950 file_marker = re.compile(
951 '^diff --git (?P<filename>.*) (?P=filename)$')
952 current_diff = []
953 keep_line_endings = True
954 for x in unified_diff.splitlines(keep_line_endings):
955 match = file_marker.match(x)
956 if match:
957 # Marks the start of a new per-file section.
958 diffs[match.group('filename')] = current_diff = [x]
959 elif x.startswith('diff --git'):
960 raise PresubmitFailure('Unexpected diff line: %s' % x)
961 else:
962 current_diff.append(x)
Josip Sokcevic7958e302023-03-01 23:02:21 +0000963
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000964 self._diffs_by_file = dict(
965 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
Josip Sokcevic7958e302023-03-01 23:02:21 +0000966
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000967 if path not in self._diffs_by_file:
968 # SCM didn't have any diff on this file. It could be that the file
969 # was not modified at all (e.g. user used --all flag in git cl
970 # presubmit). Intead of failing, return empty string. See:
971 # https://crbug.com/808346.
972 return ''
Josip Sokcevic7958e302023-03-01 23:02:21 +0000973
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000974 return self._diffs_by_file[path]
Josip Sokcevic7958e302023-03-01 23:02:21 +0000975
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000976 def GetOldContents(self, path, local_root):
977 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
Josip Sokcevic7958e302023-03-01 23:02:21 +0000978
979
980class AffectedFile(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000981 """Representation of a file in a change."""
Josip Sokcevic7958e302023-03-01 23:02:21 +0000982
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000983 DIFF_CACHE = _DiffCache
Josip Sokcevic7958e302023-03-01 23:02:21 +0000984
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000985 # Method could be a function
986 # pylint: disable=no-self-use
987 def __init__(self, path, action, repository_root, diff_cache):
988 self._path = path
989 self._action = action
990 self._local_root = repository_root
991 self._is_directory = None
992 self._cached_changed_contents = None
993 self._cached_new_contents = None
994 self._diff_cache = diff_cache
995 logging.debug('%s(%s)', self.__class__.__name__, self._path)
Josip Sokcevic7958e302023-03-01 23:02:21 +0000996
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000997 def LocalPath(self):
998 """Returns the path of this file on the local disk relative to client root.
Josip Sokcevic7958e302023-03-01 23:02:21 +0000999
1000 This should be used for error messages but not for accessing files,
1001 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
1002 often != client root).
1003 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001004 return normpath(self._path)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001005
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001006 def AbsoluteLocalPath(self):
1007 """Returns the absolute path of this file on the local disk.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001008 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001009 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001010
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001011 def Action(self):
1012 """Returns the action on this opened file, e.g. A, M, D, etc."""
1013 return self._action
Josip Sokcevic7958e302023-03-01 23:02:21 +00001014
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001015 def IsTestableFile(self):
1016 """Returns True if the file is a text file and not a binary file.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001017
1018 Deleted files are not text file."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001019 raise NotImplementedError() # Implement when needed
Josip Sokcevic7958e302023-03-01 23:02:21 +00001020
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001021 def IsTextFile(self):
1022 """An alias to IsTestableFile for backwards compatibility."""
1023 return self.IsTestableFile()
Josip Sokcevic7958e302023-03-01 23:02:21 +00001024
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001025 def OldContents(self):
1026 """Returns an iterator over the lines in the old version of file.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001027
1028 The old version is the file before any modifications in the user's
1029 workspace, i.e. the 'left hand side'.
1030
1031 Contents will be empty if the file is a directory or does not exist.
1032 Note: The carriage returns (LF or CR) are stripped off.
1033 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001034 return self._diff_cache.GetOldContents(self.LocalPath(),
1035 self._local_root).splitlines()
Josip Sokcevic7958e302023-03-01 23:02:21 +00001036
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001037 def NewContents(self):
1038 """Returns an iterator over the lines in the new version of file.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001039
1040 The new version is the file in the user's workspace, i.e. the 'right hand
1041 side'.
1042
1043 Contents will be empty if the file is a directory or does not exist.
1044 Note: The carriage returns (LF or CR) are stripped off.
1045 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001046 if self._cached_new_contents is None:
1047 self._cached_new_contents = []
1048 try:
1049 self._cached_new_contents = gclient_utils.FileRead(
1050 self.AbsoluteLocalPath(), 'rU').splitlines()
1051 except IOError:
1052 pass # File not found? That's fine; maybe it was deleted.
1053 except UnicodeDecodeError as e:
1054 # log the filename since we're probably trying to read a binary
1055 # file, and shouldn't be.
1056 print('Error reading %s: %s' % (self.AbsoluteLocalPath(), e))
1057 raise
Josip Sokcevic7958e302023-03-01 23:02:21 +00001058
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001059 return self._cached_new_contents[:]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001060
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001061 def ChangedContents(self, keeplinebreaks=False):
1062 """Returns a list of tuples (line number, line text) of all new lines.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001063
1064 This relies on the scm diff output describing each changed code section
1065 with a line of the form
1066
1067 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
1068 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001069 # Don't return cached results when line breaks are requested.
1070 if not keeplinebreaks and self._cached_changed_contents is not None:
1071 return self._cached_changed_contents[:]
1072 result = []
1073 line_num = 0
Josip Sokcevic7958e302023-03-01 23:02:21 +00001074
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001075 # The keeplinebreaks parameter to splitlines must be True or else the
1076 # CheckForWindowsLineEndings presubmit will be a NOP.
1077 for line in self.GenerateScmDiff().splitlines(keeplinebreaks):
1078 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
1079 if m:
1080 line_num = int(m.groups(1)[0])
1081 continue
1082 if line.startswith('+') and not line.startswith('++'):
1083 result.append((line_num, line[1:]))
1084 if not line.startswith('-'):
1085 line_num += 1
1086 # Don't cache results with line breaks.
1087 if keeplinebreaks:
1088 return result
1089 self._cached_changed_contents = result
1090 return self._cached_changed_contents[:]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001091
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001092 def __str__(self):
1093 return self.LocalPath()
Josip Sokcevic7958e302023-03-01 23:02:21 +00001094
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001095 def GenerateScmDiff(self):
1096 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001097
1098
1099class GitAffectedFile(AffectedFile):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001100 """Representation of a file in a change out of a git checkout."""
1101 # Method 'NNN' is abstract in class 'NNN' but is not overridden
1102 # pylint: disable=abstract-method
Josip Sokcevic7958e302023-03-01 23:02:21 +00001103
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001104 DIFF_CACHE = _GitDiffCache
Josip Sokcevic7958e302023-03-01 23:02:21 +00001105
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001106 def __init__(self, *args, **kwargs):
1107 AffectedFile.__init__(self, *args, **kwargs)
1108 self._server_path = None
1109 self._is_testable_file = None
Josip Sokcevic7958e302023-03-01 23:02:21 +00001110
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001111 def IsTestableFile(self):
1112 if self._is_testable_file is None:
1113 if self.Action() == 'D':
1114 # A deleted file is not testable.
1115 self._is_testable_file = False
1116 else:
1117 self._is_testable_file = os.path.isfile(
1118 self.AbsoluteLocalPath())
1119 return self._is_testable_file
Josip Sokcevic7958e302023-03-01 23:02:21 +00001120
1121
1122class Change(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001123 """Describe a change.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001124
1125 Used directly by the presubmit scripts to query the current change being
1126 tested.
1127
1128 Instance members:
1129 tags: Dictionary of KEY=VALUE pairs found in the change description.
1130 self.KEY: equivalent to tags['KEY']
1131 """
1132
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001133 _AFFECTED_FILES = AffectedFile
Josip Sokcevic7958e302023-03-01 23:02:21 +00001134
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001135 # Matches key/value (or 'tag') lines in changelist descriptions.
1136 TAG_LINE_RE = re.compile(
1137 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
1138 scm = ''
Josip Sokcevic7958e302023-03-01 23:02:21 +00001139
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001140 def __init__(self,
1141 name,
1142 description,
1143 local_root,
1144 files,
1145 issue,
1146 patchset,
1147 author,
1148 upstream=None):
1149 if files is None:
1150 files = []
1151 self._name = name
1152 # Convert root into an absolute path.
1153 self._local_root = os.path.abspath(local_root)
1154 self._upstream = upstream
1155 self.issue = issue
1156 self.patchset = patchset
1157 self.author_email = author
Josip Sokcevic7958e302023-03-01 23:02:21 +00001158
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001159 self._full_description = ''
1160 self.tags = {}
1161 self._description_without_tags = ''
1162 self.SetDescriptionText(description)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001163
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001164 assert all((isinstance(f, (list, tuple)) and len(f) == 2)
1165 for f in files), files
Josip Sokcevic7958e302023-03-01 23:02:21 +00001166
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001167 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
1168 self._affected_files = [
1169 self._AFFECTED_FILES(path, action.strip(), self._local_root,
1170 diff_cache) for action, path in files
1171 ]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001172
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001173 def UpstreamBranch(self):
1174 """Returns the upstream branch for the change."""
1175 return self._upstream
Josip Sokcevic7958e302023-03-01 23:02:21 +00001176
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001177 def Name(self):
1178 """Returns the change name."""
1179 return self._name
Josip Sokcevic7958e302023-03-01 23:02:21 +00001180
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001181 def DescriptionText(self):
1182 """Returns the user-entered changelist description, minus tags.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001183
1184 Any line in the user-provided description starting with e.g. 'FOO='
1185 (whitespace permitted before and around) is considered a tag line. Such
1186 lines are stripped out of the description this function returns.
1187 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001188 return self._description_without_tags
Josip Sokcevic7958e302023-03-01 23:02:21 +00001189
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001190 def FullDescriptionText(self):
1191 """Returns the complete changelist description including tags."""
1192 return self._full_description
Josip Sokcevic7958e302023-03-01 23:02:21 +00001193
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001194 def SetDescriptionText(self, description):
1195 """Sets the full description text (including tags) to |description|.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001196
1197 Also updates the list of tags."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001198 self._full_description = description
Josip Sokcevic7958e302023-03-01 23:02:21 +00001199
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001200 # From the description text, build up a dictionary of key/value pairs
1201 # plus the description minus all key/value or 'tag' lines.
1202 description_without_tags = []
1203 self.tags = {}
1204 for line in self._full_description.splitlines():
1205 m = self.TAG_LINE_RE.match(line)
1206 if m:
1207 self.tags[m.group('key')] = m.group('value')
1208 else:
1209 description_without_tags.append(line)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001210
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001211 # Change back to text and remove whitespace at end.
1212 self._description_without_tags = (
1213 '\n'.join(description_without_tags).rstrip())
Josip Sokcevic7958e302023-03-01 23:02:21 +00001214
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001215 def AddDescriptionFooter(self, key, value):
1216 """Adds the given footer to the change description.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001217
1218 Args:
1219 key: A string with the key for the git footer. It must conform to
1220 the git footers format (i.e. 'List-Of-Tokens') and will be case
1221 normalized so that each token is title-cased.
1222 value: A string with the value for the git footer.
1223 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001224 description = git_footers.add_footer(self.FullDescriptionText(),
1225 git_footers.normalize_name(key),
1226 value)
1227 self.SetDescriptionText(description)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001228
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001229 def RepositoryRoot(self):
1230 """Returns the repository (checkout) root directory for this change,
Josip Sokcevic7958e302023-03-01 23:02:21 +00001231 as an absolute path.
1232 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001233 return self._local_root
Josip Sokcevic7958e302023-03-01 23:02:21 +00001234
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001235 def __getattr__(self, attr):
1236 """Return tags directly as attributes on the object."""
1237 if not re.match(r'^[A-Z_]*$', attr):
1238 raise AttributeError(self, attr)
1239 return self.tags.get(attr)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001240
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001241 def GitFootersFromDescription(self):
1242 """Return the git footers present in the description.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001243
1244 Returns:
1245 footers: A dict of {footer: [values]} containing a multimap of the footers
1246 in the change description.
1247 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001248 return git_footers.parse_footers(self.FullDescriptionText())
Josip Sokcevic7958e302023-03-01 23:02:21 +00001249
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001250 def BugsFromDescription(self):
1251 """Returns all bugs referenced in the commit description."""
1252 bug_tags = ['BUG', 'FIXED']
Josip Sokcevic7958e302023-03-01 23:02:21 +00001253
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001254 tags = []
1255 for tag in bug_tags:
1256 values = self.tags.get(tag)
1257 if values:
1258 tags += [value.strip() for value in values.split(',')]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001259
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001260 footers = []
1261 parsed = self.GitFootersFromDescription()
1262 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
1263 for unsplit_footer in unsplit_footers:
1264 footers += [b.strip() for b in unsplit_footer.split(',')]
1265 return sorted(set(tags + footers))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001266
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001267 def ReviewersFromDescription(self):
1268 """Returns all reviewers listed in the commit description."""
1269 # We don't support a 'R:' git-footer for reviewers; that is in metadata.
1270 tags = [
1271 r.strip() for r in self.tags.get('R', '').split(',') if r.strip()
1272 ]
1273 return sorted(set(tags))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001274
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001275 def TBRsFromDescription(self):
1276 """Returns all TBR reviewers listed in the commit description."""
1277 tags = [
1278 r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()
1279 ]
1280 # TODO(crbug.com/839208): Remove support for 'Tbr:' when TBRs are
1281 # programmatically determined by self-CR+1s.
1282 footers = self.GitFootersFromDescription().get('Tbr', [])
1283 return sorted(set(tags + footers))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001284
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001285 # TODO(crbug.com/753425): Delete these once we're sure they're unused.
1286 @property
1287 def BUG(self):
1288 return ','.join(self.BugsFromDescription())
Josip Sokcevic7958e302023-03-01 23:02:21 +00001289
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001290 @property
1291 def R(self):
1292 return ','.join(self.ReviewersFromDescription())
Josip Sokcevic7958e302023-03-01 23:02:21 +00001293
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001294 @property
1295 def TBR(self):
1296 return ','.join(self.TBRsFromDescription())
1297
1298 def AllFiles(self, root=None):
1299 """List all files under source control in the repo."""
1300 raise NotImplementedError()
1301
1302 def AffectedFiles(self, include_deletes=True, file_filter=None):
1303 """Returns a list of AffectedFile instances for all files in the change.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001304
1305 Args:
1306 include_deletes: If false, deleted files will be filtered out.
1307 file_filter: An additional filter to apply.
1308
1309 Returns:
1310 [AffectedFile(path, action), AffectedFile(path, action)]
1311 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001312 affected = list(filter(file_filter, self._affected_files))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001313
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001314 if include_deletes:
1315 return affected
1316 return list(filter(lambda x: x.Action() != 'D', affected))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001317
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001318 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
1319 """Return a list of the existing text files in a change."""
1320 if include_deletes is not None:
1321 warn('AffectedTeestableFiles(include_deletes=%s)'
1322 ' is deprecated and ignored' % str(include_deletes),
1323 category=DeprecationWarning,
1324 stacklevel=2)
1325 return list(
1326 filter(lambda x: x.IsTestableFile(),
1327 self.AffectedFiles(include_deletes=False, **kwargs)))
Josip Sokcevic7958e302023-03-01 23:02:21 +00001328
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001329 def AffectedTextFiles(self, include_deletes=None):
1330 """An alias to AffectedTestableFiles for backwards compatibility."""
1331 return self.AffectedTestableFiles(include_deletes=include_deletes)
Josip Sokcevic7958e302023-03-01 23:02:21 +00001332
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001333 def LocalPaths(self):
1334 """Convenience function."""
1335 return [af.LocalPath() for af in self.AffectedFiles()]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001336
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001337 def AbsoluteLocalPaths(self):
1338 """Convenience function."""
1339 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
Josip Sokcevic7958e302023-03-01 23:02:21 +00001340
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001341 def RightHandSideLines(self):
1342 """An iterator over all text lines in 'new' version of changed files.
Josip Sokcevic7958e302023-03-01 23:02:21 +00001343
1344 Lists lines from new or modified text files in the change.
1345
1346 This is useful for doing line-by-line regex checks, like checking for
1347 trailing whitespace.
1348
1349 Yields:
1350 a 3 tuple:
1351 the AffectedFile instance of the current file;
1352 integer line number (1-based); and
1353 the contents of the line as a string.
1354 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001355 return _RightHandSideLinesImpl(
1356 x for x in self.AffectedFiles(include_deletes=False)
1357 if x.IsTestableFile())
Josip Sokcevic7958e302023-03-01 23:02:21 +00001358
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001359 def OriginalOwnersFiles(self):
1360 """A map from path names of affected OWNERS files to their old content."""
1361 def owners_file_filter(f):
1362 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1363
1364 files = self.AffectedFiles(file_filter=owners_file_filter)
1365 return {f.LocalPath(): f.OldContents() for f in files}
Josip Sokcevic7958e302023-03-01 23:02:21 +00001366
1367
1368class GitChange(Change):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001369 _AFFECTED_FILES = GitAffectedFile
1370 scm = 'git'
Josip Sokcevic7958e302023-03-01 23:02:21 +00001371
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001372 def AllFiles(self, root=None):
1373 """List all files under source control in the repo."""
1374 root = root or self.RepositoryRoot()
1375 return subprocess.check_output(
1376 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1377 cwd=root).decode('utf-8', 'ignore').splitlines()
Josip Sokcevic7958e302023-03-01 23:02:21 +00001378
1379
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001380def ListRelevantPresubmitFiles(files, root):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001381 """Finds all presubmit files that apply to a given set of source files.
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001382
1383 If inherit-review-settings-ok is present right under root, looks for
1384 PRESUBMIT.py in directories enclosing root.
1385
1386 Args:
1387 files: An iterable container containing file paths.
1388 root: Path where to stop searching.
1389
1390 Return:
1391 List of absolute paths of the existing PRESUBMIT.py scripts.
1392 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001393 files = [normpath(os.path.join(root, f)) for f in files]
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001394
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001395 # List all the individual directories containing files.
1396 directories = {os.path.dirname(f) for f in files}
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001397
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001398 # Ignore root if inherit-review-settings-ok is present.
1399 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1400 root = None
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001401
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001402 # Collect all unique directories that may contain PRESUBMIT.py.
1403 candidates = set()
1404 for directory in directories:
1405 while True:
1406 if directory in candidates:
1407 break
1408 candidates.add(directory)
1409 if directory == root:
1410 break
1411 parent_dir = os.path.dirname(directory)
1412 if parent_dir == directory:
1413 # We hit the system root directory.
1414 break
1415 directory = parent_dir
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001416
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001417 # Look for PRESUBMIT.py in all candidate directories.
1418 results = []
1419 for directory in sorted(list(candidates)):
1420 try:
1421 for f in os.listdir(directory):
1422 p = os.path.join(directory, f)
1423 if os.path.isfile(p) and re.match(
1424 r'PRESUBMIT.*\.py$',
1425 f) and not f.startswith('PRESUBMIT_test'):
1426 results.append(p)
1427 except OSError:
1428 pass
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001429
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001430 logging.debug('Presubmit files: %s', ','.join(results))
1431 return results
Josip Sokcevica9a7eec2023-03-10 03:54:52 +00001432
1433
rmistry@google.com5626a922015-02-26 14:03:30 +00001434class GetPostUploadExecuter(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001435 def __init__(self, change, gerrit_obj):
1436 """
Josip Sokcevice293d3d2022-02-16 22:52:15 +00001437 Args:
Pavol Marko624e7ee2023-01-09 09:56:29 +00001438 change: The Change object.
1439 gerrit_obj: provides basic Gerrit codereview functionality.
Josip Sokcevice293d3d2022-02-16 22:52:15 +00001440 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001441 self.change = change
1442 self.gerrit = gerrit_obj
Josip Sokcevice293d3d2022-02-16 22:52:15 +00001443
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001444 def ExecPresubmitScript(self, script_text, presubmit_path):
1445 """Executes PostUploadHook() from a single presubmit script.
Josip Sokcevic632bbc02022-05-19 05:32:50 +00001446 Caller is responsible for validating whether the hook should be executed
1447 and should only call this function if it should be.
rmistry@google.com5626a922015-02-26 14:03:30 +00001448
1449 Args:
1450 script_text: The text of the presubmit script.
1451 presubmit_path: Project script to run.
rmistry@google.com5626a922015-02-26 14:03:30 +00001452
1453 Return:
1454 A list of results objects.
1455 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001456 # Change to the presubmit file's directory to support local imports.
1457 presubmit_dir = os.path.dirname(presubmit_path)
1458 main_path = os.getcwd()
1459 try:
1460 os.chdir(presubmit_dir)
1461 return self._execute_with_local_working_directory(
1462 script_text, presubmit_dir, presubmit_path)
1463 finally:
1464 # Return the process to the original working directory.
1465 os.chdir(main_path)
Pavol Marko624e7ee2023-01-09 09:56:29 +00001466
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001467 def _execute_with_local_working_directory(self, script_text, presubmit_dir,
1468 presubmit_path):
1469 context = {}
1470 try:
1471 exec(
1472 compile(script_text, presubmit_path, 'exec', dont_inherit=True),
1473 context)
1474 except Exception as e:
1475 raise PresubmitFailure('"%s" had an exception.\n%s' %
1476 (presubmit_path, e))
rmistry@google.com5626a922015-02-26 14:03:30 +00001477
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001478 function_name = 'PostUploadHook'
1479 if function_name not in context:
1480 return {}
1481 post_upload_hook = context[function_name]
1482 if not len(inspect.getfullargspec(post_upload_hook)[0]) == 3:
1483 raise PresubmitFailure(
1484 'Expected function "PostUploadHook" to take three arguments.')
1485 return post_upload_hook(self.gerrit, self.change, OutputApi(False))
rmistry@google.com5626a922015-02-26 14:03:30 +00001486
1487
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001488def _MergeMasters(masters1, masters2):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001489 """Merges two master maps. Merges also the tests of each builder."""
1490 result = {}
1491 for (master, builders) in itertools.chain(masters1.items(),
1492 masters2.items()):
1493 new_builders = result.setdefault(master, {})
1494 for (builder, tests) in builders.items():
1495 new_builders.setdefault(builder, set([])).update(tests)
1496 return result
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001497
1498
Robert Iannucci3d6d2d22023-05-11 17:25:05 +00001499def DoPostUploadExecuter(change, gerrit_obj, verbose):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001500 """Execute the post upload hook.
rmistry@google.com5626a922015-02-26 14:03:30 +00001501
1502 Args:
1503 change: The Change object.
Edward Lemur016a0872020-02-04 22:13:28 +00001504 gerrit_obj: The GerritAccessor object.
rmistry@google.com5626a922015-02-26 14:03:30 +00001505 verbose: Prints debug info.
rmistry@google.com5626a922015-02-26 14:03:30 +00001506 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001507 python_version = 'Python %s' % sys.version_info.major
1508 sys.stdout.write('Running %s post upload checks ...\n' % python_version)
1509 presubmit_files = ListRelevantPresubmitFiles(change.LocalPaths(),
1510 change.RepositoryRoot())
1511 if not presubmit_files and verbose:
1512 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
1513 results = []
1514 executer = GetPostUploadExecuter(change, gerrit_obj)
1515 # The root presubmit file should be executed after the ones in
1516 # subdirectories. i.e. the specific post upload hooks should run before the
1517 # general ones. Thus, reverse the order provided by
1518 # ListRelevantPresubmitFiles.
1519 presubmit_files.reverse()
rmistry@google.com5626a922015-02-26 14:03:30 +00001520
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001521 for filename in presubmit_files:
1522 filename = os.path.abspath(filename)
1523 # Accept CRLF presubmit script.
1524 presubmit_script = gclient_utils.FileRead(filename).replace(
1525 '\r\n', '\n')
1526 if verbose:
1527 sys.stdout.write('Running %s\n' % filename)
1528 results.extend(executer.ExecPresubmitScript(presubmit_script, filename))
rmistry@google.com5626a922015-02-26 14:03:30 +00001529
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001530 if not results:
1531 return 0
Edward Lemur6eb1d322020-02-27 22:20:15 +00001532
Edward Lemur6eb1d322020-02-27 22:20:15 +00001533 sys.stdout.write('\n')
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001534 sys.stdout.write('** Post Upload Hook Messages **\n')
Edward Lemur6eb1d322020-02-27 22:20:15 +00001535
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001536 exit_code = 0
1537 for result in results:
1538 if result.fatal:
1539 exit_code = 1
1540 result.handle()
1541 sys.stdout.write('\n')
1542
1543 return exit_code
1544
rmistry@google.com5626a922015-02-26 14:03:30 +00001545
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001546class PresubmitExecuter(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001547 def __init__(self,
1548 change,
1549 committing,
1550 verbose,
1551 gerrit_obj,
1552 dry_run=None,
1553 thread_pool=None,
1554 parallel=False,
1555 no_diffs=False):
1556 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001557 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001558 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001559 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001560 gerrit_obj: provides basic Gerrit codereview functionality.
1561 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001562 parallel: if true, all tests reported via input_api.RunTests for all
1563 PRESUBMIT files will be run in parallel.
Bruce Dawson09c0c072022-05-26 20:28:58 +00001564 no_diffs: if true, implies that --files or --all was specified so some
1565 checks can be skipped, and some errors will be messages.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001566 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001567 self.change = change
1568 self.committing = committing
1569 self.gerrit = gerrit_obj
1570 self.verbose = verbose
1571 self.dry_run = dry_run
1572 self.more_cc = []
1573 self.thread_pool = thread_pool
1574 self.parallel = parallel
1575 self.no_diffs = no_diffs
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001576
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001577 def ExecPresubmitScript(self, script_text, presubmit_path):
1578 """Executes a single presubmit script.
Josip Sokcevic632bbc02022-05-19 05:32:50 +00001579 Caller is responsible for validating whether the hook should be executed
1580 and should only call this function if it should be.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001581
1582 Args:
1583 script_text: The text of the presubmit script.
1584 presubmit_path: The path to the presubmit file (this will be reported via
1585 input_api.PresubmitLocalPath()).
1586
1587 Return:
1588 A list of result objects, empty if no problems.
1589 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001590 # Change to the presubmit file's directory to support local imports.
1591 presubmit_dir = os.path.dirname(presubmit_path)
1592 main_path = os.getcwd()
1593 try:
1594 os.chdir(presubmit_dir)
1595 return self._execute_with_local_working_directory(
1596 script_text, presubmit_dir, presubmit_path)
1597 finally:
1598 # Return the process to the original working directory.
1599 os.chdir(main_path)
chase@chromium.org8e416c82009-10-06 04:30:44 +00001600
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001601 def _execute_with_local_working_directory(self, script_text, presubmit_dir,
1602 presubmit_path):
1603 # Load the presubmit script into context.
1604 input_api = InputApi(self.change,
1605 presubmit_path,
1606 self.committing,
1607 self.verbose,
1608 gerrit_obj=self.gerrit,
1609 dry_run=self.dry_run,
1610 thread_pool=self.thread_pool,
1611 parallel=self.parallel,
1612 no_diffs=self.no_diffs)
1613 output_api = OutputApi(self.committing)
1614 context = {}
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001615
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001616 try:
1617 exec(
1618 compile(script_text, presubmit_path, 'exec', dont_inherit=True),
1619 context)
1620 except Exception as e:
1621 raise PresubmitFailure('"%s" had an exception.\n%s' %
1622 (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001623
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001624 context['__args'] = (input_api, output_api)
Ben Pastene8351dc12020-08-06 05:01:35 +00001625
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001626 # Get path of presubmit directory relative to repository root.
1627 # Always use forward slashes, so that path is same in *nix and Windows
1628 root = input_api.change.RepositoryRoot()
1629 rel_path = os.path.relpath(presubmit_dir, root)
1630 rel_path = rel_path.replace(os.path.sep, '/')
Ben Pastene8351dc12020-08-06 05:01:35 +00001631
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001632 # Get the URL of git remote origin and use it to identify host and
1633 # project
1634 host = project = ''
1635 if self.gerrit:
1636 host = self.gerrit.host or ''
1637 project = self.gerrit.project or ''
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001638
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001639 # Prefix for test names
1640 prefix = 'presubmit:%s/%s:%s/' % (host, project, rel_path)
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001641
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001642 # Perform all the desired presubmit checks.
1643 results = []
Ben Pastene8351dc12020-08-06 05:01:35 +00001644
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001645 try:
1646 version = [
1647 int(x)
1648 for x in context.get('PRESUBMIT_VERSION', '0.0.0').split('.')
1649 ]
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001650
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001651 with rdb_wrapper.client(prefix) as sink:
1652 if version >= [2, 0, 0]:
1653 # Copy the keys to prevent "dictionary changed size during
1654 # iteration" exception if checks add globals to context.
1655 # E.g. sometimes the Python runtime will add
1656 # __warningregistry__.
1657 for function_name in list(context.keys()):
1658 if not function_name.startswith('Check'):
1659 continue
1660 if function_name.endswith(
1661 'Commit') and not self.committing:
1662 continue
1663 if function_name.endswith('Upload') and self.committing:
1664 continue
1665 logging.debug('Running %s in %s', function_name,
1666 presubmit_path)
1667 results.extend(
1668 self._run_check_function(function_name, context,
1669 sink, presubmit_path))
1670 logging.debug('Running %s done.', function_name)
1671 self.more_cc.extend(output_api.more_cc)
1672 # Clear the CC list between running each presubmit check
1673 # to prevent CCs from being repeatedly appended.
1674 output_api.more_cc = []
Scott Leecc2fe9b2020-11-19 19:38:06 +00001675
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001676 else: # Old format
1677 if self.committing:
1678 function_name = 'CheckChangeOnCommit'
1679 else:
1680 function_name = 'CheckChangeOnUpload'
1681 if function_name in list(context.keys()):
1682 logging.debug('Running %s in %s', function_name,
1683 presubmit_path)
1684 results.extend(
1685 self._run_check_function(function_name, context,
1686 sink, presubmit_path))
1687 logging.debug('Running %s done.', function_name)
1688 self.more_cc.extend(output_api.more_cc)
1689 # Clear the CC list between running each presubmit check
1690 # to prevent CCs from being repeatedly appended.
1691 output_api.more_cc = []
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001692
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001693 finally:
1694 for f in input_api._named_temporary_files:
1695 os.remove(f)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001696
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001697 self.more_cc = sorted(set(self.more_cc))
Daniel Cheng541638f2023-05-15 22:00:47 +00001698
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001699 return results
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001700
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001701 def _run_check_function(self, function_name, context, sink, presubmit_path):
1702 """Evaluates and returns the result of a given presubmit function.
Scott Leecc2fe9b2020-11-19 19:38:06 +00001703
1704 If sink is given, the result of the presubmit function will be reported
1705 to the ResultSink.
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001706
1707 Args:
Scott Leecc2fe9b2020-11-19 19:38:06 +00001708 function_name: the name of the presubmit function to evaluate
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001709 context: a context dictionary in which the function will be evaluated
Scott Leecc2fe9b2020-11-19 19:38:06 +00001710 sink: an instance of ResultSink. None, by default.
1711 Returns:
1712 the result of the presubmit function call.
1713 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001714 start_time = time_time()
1715 try:
1716 result = eval(function_name + '(*__args)', context)
1717 self._check_result_type(result)
1718 except Exception:
1719 _, e_value, _ = sys.exc_info()
1720 result = [
1721 OutputApi.PresubmitError(
1722 'Evaluation of %s failed: %s, %s' %
1723 (function_name, e_value, traceback.format_exc()))
1724 ]
Scott Leecc2fe9b2020-11-19 19:38:06 +00001725
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001726 elapsed_time = time_time() - start_time
1727 if elapsed_time > 10.0:
1728 sys.stdout.write('%6.1fs to run %s from %s.\n' %
1729 (elapsed_time, function_name, presubmit_path))
1730 if sink:
Liviu Rau7f223302023-11-13 12:16:27 +00001731 status, failure_reason = RDBStatusFrom(result)
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001732 sink.report(function_name, status, elapsed_time, failure_reason)
Scott Leecc2fe9b2020-11-19 19:38:06 +00001733
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001734 return result
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001735
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001736 def _check_result_type(self, result):
1737 """Helper function which ensures result is a list, and all elements are
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001738 instances of OutputApi.PresubmitResult"""
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001739 if not isinstance(result, (tuple, list)):
1740 raise PresubmitFailure(
1741 'Presubmit functions must return a tuple or list')
1742 if not all(
1743 isinstance(res, OutputApi.PresubmitResult) for res in result):
1744 raise PresubmitFailure(
1745 'All presubmit results must be of types derived from '
1746 'output_api.PresubmitResult')
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001747
1748
Liviu Rau7f223302023-11-13 12:16:27 +00001749def RDBStatusFrom(result):
1750 """Returns the status and failure reason for a PresubmitResult."""
1751 failure_reason = None
1752 status = rdb_wrapper.STATUS_PASS
1753 if any(r.fatal for r in result):
1754 status = rdb_wrapper.STATUS_FAIL
1755 failure_reasons = []
1756 for r in result:
1757 fields = r.json_format()
1758 message = fields['message']
1759 items = '\n'.join(' %s' % item for item in fields['items'])
1760 failure_reasons.append('\n'.join([message, items]))
1761 if failure_reasons:
1762 failure_reason = '\n'.join(failure_reasons)
1763 return status, failure_reason
1764
1765
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001766def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001767 committing,
1768 verbose,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001769 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001770 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001771 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001772 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001773 parallel=False,
Dirk Pranke6f0df682021-06-25 00:42:33 +00001774 json_output=None,
Bruce Dawson09c0c072022-05-26 20:28:58 +00001775 no_diffs=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001776 """Runs all presubmit checks that apply to the files in the change.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001777
1778 This finds all PRESUBMIT.py files in directories enclosing the files in the
1779 change (up to the repository root) and calls the relevant entrypoint function
1780 depending on whether the change is being committed or uploaded.
1781
1782 Prints errors, warnings and notifications. Prompts the user for warnings
1783 when needed.
1784
1785 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001786 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001787 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001788 verbose: Prints debug info.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001789 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001790 may_prompt: Enable (y/n) questions on warning or error. If False,
1791 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001792 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001793 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001794 parallel: if true, all tests specified by input_api.RunTests in all
1795 PRESUBMIT files will be run in parallel.
Bruce Dawson09c0c072022-05-26 20:28:58 +00001796 no_diffs: if true, implies that --files or --all was specified so some
1797 checks can be skipped, and some errors will be messages.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001798 Return:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001799 1 if presubmit checks failed or 0 otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001800 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001801 old_environ = os.environ
1802 try:
1803 # Make sure python subprocesses won't generate .pyc files.
1804 os.environ = os.environ.copy()
1805 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001806
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001807 python_version = 'Python %s' % sys.version_info.major
1808 if committing:
1809 sys.stdout.write('Running %s presubmit commit checks ...\n' %
1810 python_version)
1811 else:
1812 sys.stdout.write('Running %s presubmit upload checks ...\n' %
1813 python_version)
1814 start_time = time_time()
1815 presubmit_files = ListRelevantPresubmitFiles(
1816 change.AbsoluteLocalPaths(), change.RepositoryRoot())
1817 if not presubmit_files and verbose:
1818 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
1819 results = []
1820 thread_pool = ThreadPool()
1821 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1822 dry_run, thread_pool, parallel, no_diffs)
1823 if default_presubmit:
1824 if verbose:
1825 sys.stdout.write('Running default presubmit script.\n')
1826 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1827 results += executer.ExecPresubmitScript(default_presubmit,
1828 fake_path)
1829 for filename in presubmit_files:
1830 filename = os.path.abspath(filename)
1831 # Accept CRLF presubmit script.
1832 presubmit_script = gclient_utils.FileRead(filename).replace(
1833 '\r\n', '\n')
1834 if verbose:
1835 sys.stdout.write('Running %s\n' % filename)
1836 results += executer.ExecPresubmitScript(presubmit_script, filename)
Bruce Dawson76fe1a72022-05-25 20:52:21 +00001837
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001838 results += thread_pool.RunAsync()
Edward Lesmes8e282792018-04-03 18:50:29 -04001839
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001840 messages = {}
1841 should_prompt = False
1842 presubmits_failed = False
1843 for result in results:
1844 if result.fatal:
1845 presubmits_failed = True
1846 messages.setdefault('ERRORS', []).append(result)
1847 elif result.should_prompt:
1848 should_prompt = True
1849 messages.setdefault('Warnings', []).append(result)
1850 else:
1851 messages.setdefault('Messages', []).append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001852
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001853 # Print the different message types in a consistent order. ERRORS go
1854 # last so that they will be most visible in the local-presubmit output.
1855 for name in ['Messages', 'Warnings', 'ERRORS']:
1856 if name in messages:
1857 items = messages[name]
1858 sys.stdout.write('** Presubmit %s: %d **\n' %
1859 (name, len(items)))
1860 for item in items:
1861 item.handle()
1862 sys.stdout.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001863
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001864 total_time = time_time() - start_time
1865 if total_time > 1.0:
1866 sys.stdout.write('Presubmit checks took %.1fs to calculate.\n' %
1867 total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001868
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001869 if not should_prompt and not presubmits_failed:
1870 sys.stdout.write('%s presubmit checks passed.\n\n' % python_version)
1871 elif should_prompt and not presubmits_failed:
1872 sys.stdout.write('There were %s presubmit warnings. ' %
1873 python_version)
1874 if may_prompt:
1875 presubmits_failed = not prompt_should_continue(
1876 'Are you sure you wish to continue? (y/N): ')
1877 else:
1878 sys.stdout.write('\n')
1879 else:
1880 sys.stdout.write('There were %s presubmit errors.\n' %
1881 python_version)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001882
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001883 if json_output:
1884 # Write the presubmit results to json output
1885 presubmit_results = {
1886 'errors':
1887 [error.json_format() for error in messages.get('ERRORS', [])],
1888 'notifications': [
1889 notification.json_format()
1890 for notification in messages.get('Messages', [])
1891 ],
1892 'warnings': [
1893 warning.json_format()
1894 for warning in messages.get('Warnings', [])
1895 ],
1896 'more_cc':
1897 executer.more_cc,
1898 }
Edward Lemur1dc66e12020-02-21 21:36:34 +00001899
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001900 gclient_utils.FileWrite(
1901 json_output, json.dumps(presubmit_results, sort_keys=True))
Edward Lemur1dc66e12020-02-21 21:36:34 +00001902
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001903 global _ASKED_FOR_FEEDBACK
1904 # Ask for feedback one time out of 5.
1905 if (results and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
1906 sys.stdout.write(
1907 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1908 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1909 'on the file to figure out who to ask for help.\n')
1910 _ASKED_FOR_FEEDBACK = True
Edward Lemur6eb1d322020-02-27 22:20:15 +00001911
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001912 return 1 if presubmits_failed else 0
1913 finally:
1914 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001915
1916
Edward Lemur50984a62020-02-06 18:10:18 +00001917def _scan_sub_dirs(mask, recursive):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001918 if not recursive:
1919 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001920
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001921 results = []
1922 for root, dirs, files in os.walk('.'):
1923 if '.svn' in dirs:
1924 dirs.remove('.svn')
1925 if '.git' in dirs:
1926 dirs.remove('.git')
1927 for name in files:
1928 if fnmatch.fnmatch(name, mask):
1929 results.append(os.path.join(root, name))
1930 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001931
1932
Edward Lemur50984a62020-02-06 18:10:18 +00001933def _parse_files(args, recursive):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001934 logging.debug('Searching for %s', args)
1935 files = []
1936 for arg in args:
1937 files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
1938 return files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001939
1940
Edward Lemur50984a62020-02-06 18:10:18 +00001941def _parse_change(parser, options):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001942 """Process change options.
Edward Lemur50984a62020-02-06 18:10:18 +00001943
1944 Args:
1945 parser: The parser used to parse the arguments from command line.
1946 options: The arguments parsed from command line.
1947 Returns:
Josip Sokcevic7958e302023-03-01 23:02:21 +00001948 A GitChange if the change root is a git repository, or a Change otherwise.
Edward Lemur50984a62020-02-06 18:10:18 +00001949 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001950 if options.files and options.all_files:
1951 parser.error('<files> cannot be specified when --all-files is set.')
Edward Lemur50984a62020-02-06 18:10:18 +00001952
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001953 change_scm = scm.determine_scm(options.root)
1954 if change_scm != 'git' and not options.files:
1955 parser.error('<files> is not optional for unversioned directories.')
Edward Lemur50984a62020-02-06 18:10:18 +00001956
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001957 if options.files:
1958 if options.source_controlled_only:
1959 # Get the filtered set of files from SCM.
1960 change_files = []
1961 for name in scm.GIT.GetAllFiles(options.root):
1962 for mask in options.files:
1963 if fnmatch.fnmatch(name, mask):
1964 change_files.append(('M', name))
1965 break
1966 else:
1967 # Get the filtered set of files from a directory scan.
1968 change_files = _parse_files(options.files, options.recursive)
1969 elif options.all_files:
1970 change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
Josip Sokcevic017544d2022-03-31 23:47:53 +00001971 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001972 change_files = scm.GIT.CaptureStatus(options.root, options.upstream
1973 or None)
Edward Lemur50984a62020-02-06 18:10:18 +00001974
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001975 logging.info('Found %d file(s).', len(change_files))
Edward Lemur50984a62020-02-06 18:10:18 +00001976
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001977 change_class = GitChange if change_scm == 'git' else Change
1978 return change_class(options.name,
1979 options.description,
1980 options.root,
1981 change_files,
1982 options.issue,
1983 options.patchset,
1984 options.author,
1985 upstream=options.upstream)
Edward Lemur50984a62020-02-06 18:10:18 +00001986
1987
1988def _parse_gerrit_options(parser, options):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001989 """Process gerrit options.
Edward Lemur50984a62020-02-06 18:10:18 +00001990
1991 SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
1992 options.gerrit_fetch is set.
1993
1994 Args:
1995 parser: The parser used to parse the arguments from command line.
1996 options: The arguments parsed from command line.
1997 Returns:
Stephen Martinisfb09de22021-02-25 03:41:13 +00001998 A GerritAccessor object if options.gerrit_url is set, or None otherwise.
Edward Lemur50984a62020-02-06 18:10:18 +00001999 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002000 gerrit_obj = None
2001 if options.gerrit_url:
2002 gerrit_obj = GerritAccessor(url=options.gerrit_url,
2003 project=options.gerrit_project,
2004 branch=options.gerrit_branch)
Edward Lemur50984a62020-02-06 18:10:18 +00002005
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002006 if not options.gerrit_fetch:
2007 return gerrit_obj
2008
2009 if not options.gerrit_url or not options.issue or not options.patchset:
2010 parser.error(
2011 '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
2012
2013 options.author = gerrit_obj.GetChangeOwner(options.issue)
2014 options.description = gerrit_obj.GetChangeDescription(
2015 options.issue, options.patchset)
2016
2017 logging.info('Got author: "%s"', options.author)
2018 logging.info('Got description: """\n%s\n"""', options.description)
2019
Edward Lemur50984a62020-02-06 18:10:18 +00002020 return gerrit_obj
2021
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00002022
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00002023@contextlib.contextmanager
2024def canned_check_filter(method_names):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002025 filtered = {}
2026 try:
2027 for method_name in method_names:
2028 if not hasattr(presubmit_canned_checks, method_name):
2029 logging.warning('Skipping unknown "canned" check %s' %
2030 method_name)
2031 continue
2032 filtered[method_name] = getattr(presubmit_canned_checks,
2033 method_name)
2034 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
2035 yield
2036 finally:
2037 for name, method in filtered.items():
2038 setattr(presubmit_canned_checks, name, method)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00002039
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00002040
sbc@chromium.org013731e2015-02-26 18:28:43 +00002041def main(argv=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002042 parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
2043 hooks = parser.add_mutually_exclusive_group()
2044 hooks.add_argument('-c',
2045 '--commit',
2046 action='store_true',
2047 help='Use commit instead of upload checks.')
2048 hooks.add_argument('-u',
2049 '--upload',
2050 action='store_false',
2051 dest='commit',
2052 help='Use upload instead of commit checks.')
2053 hooks.add_argument('--post_upload',
2054 action='store_true',
2055 help='Run post-upload commit hooks.')
2056 parser.add_argument('-r',
2057 '--recursive',
2058 action='store_true',
2059 help='Act recursively.')
2060 parser.add_argument('-v',
2061 '--verbose',
2062 action='count',
2063 default=0,
2064 help='Use 2 times for more debug info.')
2065 parser.add_argument('--name', default='no name')
2066 parser.add_argument('--author')
2067 desc = parser.add_mutually_exclusive_group()
2068 desc.add_argument('--description',
2069 default='',
2070 help='The change description.')
2071 desc.add_argument('--description_file',
2072 help='File to read change description from.')
2073 parser.add_argument('--issue', type=int, default=0)
2074 parser.add_argument('--patchset', type=int, default=0)
2075 parser.add_argument('--root',
2076 default=os.getcwd(),
2077 help='Search for PRESUBMIT.py up to this directory. '
2078 'If inherit-review-settings-ok is present in this '
2079 'directory, parent directories up to the root file '
2080 'system directories will also be searched.')
2081 parser.add_argument(
2082 '--upstream',
2083 help='Git only: the base ref or upstream branch against '
2084 'which the diff should be computed.')
2085 parser.add_argument('--default_presubmit')
2086 parser.add_argument('--may_prompt', action='store_true', default=False)
2087 parser.add_argument(
2088 '--skip_canned',
2089 action='append',
2090 default=[],
2091 help='A list of checks to skip which appear in '
2092 'presubmit_canned_checks. Can be provided multiple times '
2093 'to skip multiple canned checks.')
2094 parser.add_argument('--dry_run',
2095 action='store_true',
2096 help=argparse.SUPPRESS)
2097 parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
2098 parser.add_argument('--gerrit_project', help=argparse.SUPPRESS)
2099 parser.add_argument('--gerrit_branch', help=argparse.SUPPRESS)
2100 parser.add_argument('--gerrit_fetch',
2101 action='store_true',
2102 help=argparse.SUPPRESS)
2103 parser.add_argument('--parallel',
2104 action='store_true',
2105 help='Run all tests specified by input_api.RunTests in '
2106 'all PRESUBMIT files in parallel.')
2107 parser.add_argument('--json_output',
2108 help='Write presubmit errors to json output.')
2109 parser.add_argument('--all_files',
2110 action='store_true',
2111 help='Mark all files under source control as modified.')
Bruce Dawson09c0c072022-05-26 20:28:58 +00002112
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002113 parser.add_argument('files',
2114 nargs='*',
2115 help='List of files to be marked as modified when '
2116 'executing presubmit or post-upload hooks. fnmatch '
2117 'wildcards can also be used.')
2118 parser.add_argument('--source_controlled_only',
2119 action='store_true',
2120 help='Constrain \'files\' to those in source control.')
2121 parser.add_argument('--no_diffs',
2122 action='store_true',
2123 help='Assume that all "modified" files have no diffs.')
2124 options = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00002125
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002126 log_level = logging.ERROR
2127 if options.verbose >= 2:
2128 log_level = logging.DEBUG
2129 elif options.verbose:
2130 log_level = logging.INFO
2131 log_format = ('[%(levelname).1s%(asctime)s %(process)d %(thread)d '
2132 '%(filename)s] %(message)s')
2133 logging.basicConfig(format=log_format, level=log_level)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00002134
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002135 # Print call stacks when _PresubmitResult objects are created with -v -v is
2136 # specified. This helps track down where presubmit messages are coming from.
2137 if options.verbose >= 2:
2138 global _SHOW_CALLSTACKS
2139 _SHOW_CALLSTACKS = True
Bruce Dawsondca14bc2022-09-15 20:59:38 +00002140
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002141 if options.description_file:
2142 options.description = gclient_utils.FileRead(options.description_file)
2143 gerrit_obj = _parse_gerrit_options(parser, options)
2144 change = _parse_change(parser, options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00002145
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002146 try:
2147 if options.post_upload:
2148 return DoPostUploadExecuter(change, gerrit_obj, options.verbose)
2149 with canned_check_filter(options.skip_canned):
2150 return DoPresubmitChecks(change, options.commit, options.verbose,
2151 options.default_presubmit,
2152 options.may_prompt, gerrit_obj,
2153 options.dry_run, options.parallel,
2154 options.json_output, options.no_diffs)
2155 except PresubmitFailure as e:
2156 import utils
2157 print(e, file=sys.stderr)
2158 print('Maybe your depot_tools is out of date?', file=sys.stderr)
2159 print('depot_tools version: %s' % utils.depot_tools_version(),
2160 file=sys.stderr)
2161 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002162
2163
2164if __name__ == '__main__':
Mike Frysinger124bb8e2023-09-06 05:48:55 +00002165 fix_encoding.fix_encoding()
2166 try:
2167 sys.exit(main())
2168 except KeyboardInterrupt:
2169 sys.stderr.write('interrupted\n')
2170 sys.exit(2)