blob: d72e81b4b284a21ddf9ed3da31d98cb09282b71c [file] [log] [blame]
maruel@chromium.org725f1c32011-04-01 20:24:54 +00001#!/usr/bin/env python
maruel@chromium.org3bbf2942012-01-10 16:52:06 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Enables directory-specific presubmit checks to run at upload and/or commit.
7"""
8
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00009__version__ = '1.8.0'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000010
11# TODO(joi) Add caching where appropriate/needed. The API is designed to allow
12# caching (between all different invocations of presubmit scripts for a given
13# change). We should add it as our presubmit scripts start feeling slow.
14
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 cPickle # Exposed through the API.
18import cpplint
19import cStringIO # Exposed through the API.
dcheng091b7db2016-06-16 01:27:51 -070020import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000021import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000022import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000023import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000024import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000025import logging
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000026import marshal # Exposed through the API.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000027import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000028import optparse
29import os # Somewhat exposed through the API.
30import pickle # Exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000031import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000032import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040033import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000034import sys # Parts exposed through API.
35import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040036import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000037import time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000038import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000039import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000040import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000041import urllib2 # Exposed through the API.
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000042import urlparse
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000043from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000044
45# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000046import fix_encoding
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000047import gclient_utils # Exposed through the API
Aaron Gableb584c4f2017-04-26 16:28:08 -070048import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000049import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000050import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020051import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000052import presubmit_canned_checks
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000053import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000054import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000055
56
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000057# Ask for feedback only once in program lifetime.
58_ASKED_FOR_FEEDBACK = False
59
60
maruel@chromium.org899e1c12011-04-07 17:03:18 +000061class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062 pass
63
64
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000065class CommandData(object):
66 def __init__(self, name, cmd, kwargs, message):
67 self.name = name
68 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040069 self.stdin = kwargs.get('stdin', None)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000070 self.kwargs = kwargs
Edward Lesmes8e282792018-04-03 18:50:29 -040071 self.kwargs['stdout'] = subprocess.PIPE
72 self.kwargs['stderr'] = subprocess.STDOUT
73 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000074 self.message = message
75 self.info = None
76
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000077
Edward Lesmes8e282792018-04-03 18:50:29 -040078# Adapted from
79# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
80#
81# An object that catches SIGINT sent to the Python process and notices
82# if processes passed to wait() die by SIGINT (we need to look for
83# both of those cases, because pressing Ctrl+C can result in either
84# the main process or one of the subprocesses getting the signal).
85#
86# Before a SIGINT is seen, wait(p) will simply call p.wait() and
87# return the result. Once a SIGINT has been seen (in the main process
88# or a subprocess, including the one the current call is waiting for),
89# wait(p) will call p.terminate() and raise ProcessWasInterrupted.
90class SigintHandler(object):
91 class ProcessWasInterrupted(Exception):
92 pass
93
94 sigint_returncodes = {-signal.SIGINT, # Unix
95 -1073741510, # Windows
96 }
97 def __init__(self):
98 self.__lock = threading.Lock()
99 self.__processes = set()
100 self.__got_sigint = False
101 signal.signal(signal.SIGINT, lambda signal_num, frame: self.interrupt())
102
103 def __on_sigint(self):
104 self.__got_sigint = True
105 while self.__processes:
106 try:
107 self.__processes.pop().terminate()
108 except OSError:
109 pass
110
111 def interrupt(self):
112 with self.__lock:
113 self.__on_sigint()
114
115 def got_sigint(self):
116 with self.__lock:
117 return self.__got_sigint
118
119 def wait(self, p, stdin):
120 with self.__lock:
121 if self.__got_sigint:
122 p.terminate()
123 self.__processes.add(p)
124 stdout, stderr = p.communicate(stdin)
125 code = p.returncode
126 with self.__lock:
127 self.__processes.discard(p)
128 if code in self.sigint_returncodes:
129 self.__on_sigint()
130 if self.__got_sigint:
131 raise self.ProcessWasInterrupted
132 return stdout, stderr
133
134sigint_handler = SigintHandler()
135
136
137class ThreadPool(object):
138 def __init__(self, pool_size=None):
139 self._pool_size = pool_size or multiprocessing.cpu_count()
140 self._messages = []
141 self._messages_lock = threading.Lock()
142 self._tests = []
143 self._tests_lock = threading.Lock()
144 self._nonparallel_tests = []
145
146 def CallCommand(self, test):
147 """Runs an external program.
148
149 This function converts invocation of .py files and invocations of "python"
150 to vpython invocations.
151 """
152 vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython'
153
154 cmd = test.cmd
155 if cmd[0] == 'python':
156 cmd = list(cmd)
157 cmd[0] = vpython
158 elif cmd[0].endswith('.py'):
159 cmd = [vpython] + cmd
160
161 try:
162 start = time.time()
163 p = subprocess.Popen(cmd, **test.kwargs)
164 stdout, _ = sigint_handler.wait(p, test.stdin)
165 duration = time.time() - start
166 except OSError as e:
167 duration = time.time() - start
168 return test.message(
169 '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e))
170 if p.returncode != 0:
171 return test.message(
172 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
173 if test.info:
174 return test.info('%s (%4.2fs)' % (test.name, duration))
175
176 def AddTests(self, tests, parallel=True):
177 if parallel:
178 self._tests.extend(tests)
179 else:
180 self._nonparallel_tests.extend(tests)
181
182 def RunAsync(self):
183 self._messages = []
184
185 def _WorkerFn():
186 while True:
187 test = None
188 with self._tests_lock:
189 if not self._tests:
190 break
191 test = self._tests.pop()
192 result = self.CallCommand(test)
193 if result:
194 with self._messages_lock:
195 self._messages.append(result)
196
197 def _StartDaemon():
198 t = threading.Thread(target=_WorkerFn)
199 t.daemon = True
200 t.start()
201 return t
202
203 while self._nonparallel_tests:
204 test = self._nonparallel_tests.pop()
205 result = self.CallCommand(test)
206 if result:
207 self._messages.append(result)
208
209 if self._tests:
210 threads = [_StartDaemon() for _ in range(self._pool_size)]
211 for worker in threads:
212 worker.join()
213
214 return self._messages
215
216
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000217def normpath(path):
218 '''Version of os.path.normpath that also changes backward slashes to
219 forward slashes when not running on Windows.
220 '''
221 # This is safe to always do because the Windows version of os.path.normpath
222 # will replace forward slashes with backward slashes.
223 path = path.replace(os.sep, '/')
224 return os.path.normpath(path)
225
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000226
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000227def _RightHandSideLinesImpl(affected_files):
228 """Implements RightHandSideLines for InputApi and GclChange."""
229 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000230 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000231 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000232 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000233
234
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000235class PresubmitOutput(object):
236 def __init__(self, input_stream=None, output_stream=None):
237 self.input_stream = input_stream
238 self.output_stream = output_stream
239 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800240 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000241 self.written_output = []
242 self.error_count = 0
243
244 def prompt_yes_no(self, prompt_string):
245 self.write(prompt_string)
246 if self.input_stream:
247 response = self.input_stream.readline().strip().lower()
248 if response not in ('y', 'yes'):
249 self.fail()
250 else:
251 self.fail()
252
253 def fail(self):
254 self.error_count += 1
255
256 def should_continue(self):
257 return not self.error_count
258
259 def write(self, s):
260 self.written_output.append(s)
261 if self.output_stream:
262 self.output_stream.write(s)
263
264 def getvalue(self):
265 return ''.join(self.written_output)
266
267
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000268# Top level object so multiprocessing can pickle
269# Public access through OutputApi object.
270class _PresubmitResult(object):
271 """Base class for result objects."""
272 fatal = False
273 should_prompt = False
274
275 def __init__(self, message, items=None, long_text=''):
276 """
277 message: A short one-line message to indicate errors.
278 items: A list of short strings to indicate where errors occurred.
279 long_text: multi-line text output, e.g. from another tool
280 """
281 self._message = message
282 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000283 self._long_text = long_text.rstrip()
284
285 def handle(self, output):
286 output.write(self._message)
287 output.write('\n')
288 for index, item in enumerate(self._items):
289 output.write(' ')
290 # Write separately in case it's unicode.
291 output.write(str(item))
292 if index < len(self._items) - 1:
293 output.write(' \\')
294 output.write('\n')
295 if self._long_text:
296 output.write('\n***************\n')
297 # Write separately in case it's unicode.
298 output.write(self._long_text)
299 output.write('\n***************\n')
300 if self.fatal:
301 output.fail()
302
303
304# Top level object so multiprocessing can pickle
305# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000306class _PresubmitError(_PresubmitResult):
307 """A hard presubmit error."""
308 fatal = True
309
310
311# Top level object so multiprocessing can pickle
312# Public access through OutputApi object.
313class _PresubmitPromptWarning(_PresubmitResult):
314 """An warning that prompts the user if they want to continue."""
315 should_prompt = True
316
317
318# Top level object so multiprocessing can pickle
319# Public access through OutputApi object.
320class _PresubmitNotifyResult(_PresubmitResult):
321 """Just print something to the screen -- but it's not even a warning."""
322 pass
323
324
325# Top level object so multiprocessing can pickle
326# Public access through OutputApi object.
327class _MailTextResult(_PresubmitResult):
328 """A warning that should be included in the review request email."""
329 def __init__(self, *args, **kwargs):
330 super(_MailTextResult, self).__init__()
331 raise NotImplementedError()
332
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000333class GerritAccessor(object):
334 """Limited Gerrit functionality for canned presubmit checks to work.
335
336 To avoid excessive Gerrit calls, caches the results.
337 """
338
339 def __init__(self, host):
340 self.host = host
341 self.cache = {}
342
343 def _FetchChangeDetail(self, issue):
344 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100345 try:
346 return gerrit_util.GetChangeDetail(
347 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700348 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100349 except gerrit_util.GerritError as e:
350 if e.http_status == 404:
351 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
352 'no credentials to fetch issue details' % issue)
353 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000354
355 def GetChangeInfo(self, issue):
356 """Returns labels and all revisions (patchsets) for this issue.
357
358 The result is a dictionary according to Gerrit REST Api.
359 https://gerrit-review.googlesource.com/Documentation/rest-api.html
360
361 However, API isn't very clear what's inside, so see tests for example.
362 """
363 assert issue
364 cache_key = int(issue)
365 if cache_key not in self.cache:
366 self.cache[cache_key] = self._FetchChangeDetail(issue)
367 return self.cache[cache_key]
368
369 def GetChangeDescription(self, issue, patchset=None):
370 """If patchset is none, fetches current patchset."""
371 info = self.GetChangeInfo(issue)
372 # info is a reference to cache. We'll modify it here adding description to
373 # it to the right patchset, if it is not yet there.
374
375 # Find revision info for the patchset we want.
376 if patchset is not None:
377 for rev, rev_info in info['revisions'].iteritems():
378 if str(rev_info['_number']) == str(patchset):
379 break
380 else:
381 raise Exception('patchset %s doesn\'t exist in issue %s' % (
382 patchset, issue))
383 else:
384 rev = info['current_revision']
385 rev_info = info['revisions'][rev]
386
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100387 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000388
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800389 def GetDestRef(self, issue):
390 ref = self.GetChangeInfo(issue)['branch']
391 if not ref.startswith('refs/'):
392 # NOTE: it is possible to create 'refs/x' branch,
393 # aka 'refs/heads/refs/x'. However, this is ill-advised.
394 ref = 'refs/heads/%s' % ref
395 return ref
396
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000397 def GetChangeOwner(self, issue):
398 return self.GetChangeInfo(issue)['owner']['email']
399
400 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700401 changeinfo = self.GetChangeInfo(issue)
402 if approving_only:
403 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
404 values = labelinfo.get('values', {}).keys()
405 try:
406 max_value = max(int(v) for v in values)
407 reviewers = [r for r in labelinfo.get('all', [])
408 if r.get('value', 0) == max_value]
409 except ValueError: # values is the empty list
410 reviewers = []
411 else:
412 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
413 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000414
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000415
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000416class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000417 """An instance of OutputApi gets passed to presubmit scripts so that they
418 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000420 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000421 PresubmitError = _PresubmitError
422 PresubmitPromptWarning = _PresubmitPromptWarning
423 PresubmitNotifyResult = _PresubmitNotifyResult
424 MailTextResult = _MailTextResult
425
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000426 def __init__(self, is_committing):
427 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800428 self.more_cc = []
429
430 def AppendCC(self, cc):
431 """Appends a user to cc for this change."""
432 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000433
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000434 def PresubmitPromptOrNotify(self, *args, **kwargs):
435 """Warn the user when uploading, but only notify if committing."""
436 if self.is_committing:
437 return self.PresubmitNotifyResult(*args, **kwargs)
438 return self.PresubmitPromptWarning(*args, **kwargs)
439
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800440 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
441 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
442
443 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
444 keeping it alphabetically sorted. Returns the results that should be
445 returned from the PostUploadHook.
446
447 Args:
448 cl: The git_cl.Changelist object.
449 bots_to_include: A list of strings of bots to include, in the form
450 "master:slave".
451 message: A message to be printed in the case that
452 CQ_INCLUDE_TRYBOTS was updated.
453 """
454 description = cl.GetDescription(force=True)
Aaron Gable4b23a2c2018-05-24 10:46:48 -0700455 trybot_footers = git_footers.parse_footers(description).get(
456 git_footers.normalize_name('Cq-Include-Trybots'), [])
Aaron Gableb584c4f2017-04-26 16:28:08 -0700457 prior_bots = []
Aaron Gable4b23a2c2018-05-24 10:46:48 -0700458 for f in trybot_footers:
459 prior_bots += [b.strip() for b in f.split(';') if b.strip()]
Aaron Gableb584c4f2017-04-26 16:28:08 -0700460
461 if set(prior_bots) >= set(bots_to_include):
462 return []
463 all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include)))
464
Aaron Gable4b23a2c2018-05-24 10:46:48 -0700465 description = git_footers.remove_footer(description, 'Cq-Include-Trybots')
466 description = git_footers.add_footer(
467 description, 'Cq-Include-Trybots', all_bots,
468 before_keys=['Change-Id'])
Aaron Gableb584c4f2017-04-26 16:28:08 -0700469
470 cl.UpdateDescription(description, force=True)
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800471 return [self.PresubmitNotifyResult(message)]
472
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000473
474class InputApi(object):
475 """An instance of this object is passed to presubmit scripts so they can
476 know stuff about the change they're looking at.
477 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000478 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800479 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000480
maruel@chromium.org3410d912009-06-09 20:56:16 +0000481 # File extensions that are considered source files from a style guide
482 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000483 #
484 # Files without an extension aren't included in the list. If you want to
485 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
486 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000487 DEFAULT_WHITE_LIST = (
488 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000489 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
490 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000491 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000492 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000493 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700494 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
495 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000496 )
497
498 # Path regexp that should be excluded from being considered containing source
499 # files. Don't modify this list from a presubmit script!
500 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000501 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000502 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900503 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
504 # (crbug.com/539768 and crbug.com/836555).
505 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000506 # Output directories (just in case)
507 r".*\bDebug[\\\/].*",
508 r".*\bRelease[\\\/].*",
509 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000510 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000511 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000512 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000513 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000514 r"(|.*[\\\/])\.git[\\\/].*",
515 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000516 # There is no point in processing a patch file.
517 r".+\.diff$",
518 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000519 )
520
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000521 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400522 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000523 """Builds an InputApi object.
524
525 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000526 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000527 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000528 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000529 gerrit_obj: provides basic Gerrit codereview functionality.
530 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400531 parallel: if true, all tests reported via input_api.RunTests for all
532 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000533 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000534 # Version number of the presubmit_support script.
535 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000536 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000537 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000538 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000539 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000540
Edward Lesmes8e282792018-04-03 18:50:29 -0400541 self.parallel = parallel
542 self.thread_pool = thread_pool or ThreadPool()
543
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000544 # We expose various modules and functions as attributes of the input_api
545 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900546 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000547 self.basename = os.path.basename
548 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000549 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000550 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700551 self.fnmatch = fnmatch
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000552 self.gclient_utils = gclient_utils
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000553 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000554 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000555 self.logging = logging.getLogger('PRESUBMIT')
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000556 self.marshal = marshal
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000557 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000558 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000559 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000560 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000561 self.pickle = pickle
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000562 self.re = re
563 self.subprocess = subprocess
564 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000565 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000566 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000567 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000568 self.urllib2 = urllib2
569
Robert Iannucci50258932018-03-19 10:30:59 -0700570 self.is_windows = sys.platform == 'win32'
571
572 # Set python_executable to 'python'. This is interpreted in CallCommand to
573 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
574 # to automatically pick up that repo's .vpython file, instead of inheriting
575 # the one in depot_tools.
576 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000577 self.environ = os.environ
578
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000579 # InputApi.platform is the platform you're currently running on.
580 self.platform = sys.platform
581
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000582 self.cpu_count = multiprocessing.cpu_count()
583
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000584 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000585 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000586
587 # We carry the canned checks so presubmit scripts can easily use them.
588 self.canned_checks = presubmit_canned_checks
589
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100590 # Temporary files we must manually remove at the end of a run.
591 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200592
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000593 # TODO(dpranke): figure out a list of all approved owners for a repo
594 # in order to be able to handle wildcard OWNERS files?
595 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200596 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200597 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000598 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000599 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000600
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000601 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000602 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000603 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800604 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000605 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000606 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000607 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
608 for (a, b, header) in cpplint._re_pattern_templates
609 ]
610
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000611 def PresubmitLocalPath(self):
612 """Returns the local path of the presubmit script currently being run.
613
614 This is useful if you don't want to hard-code absolute paths in the
615 presubmit script. For example, It can be used to find another file
616 relative to the PRESUBMIT.py script, so the whole tree can be branched and
617 the presubmit script still works, without editing its content.
618 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000619 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000620
agable0b65e732016-11-22 09:25:46 -0800621 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622 """Same as input_api.change.AffectedFiles() except only lists files
623 (and optionally directories) in the same directory as the current presubmit
624 script, or subdirectories thereof.
625 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000626 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000627 if len(dir_with_slash) == 1:
628 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000629
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000630 return filter(
631 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800632 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000633
agable0b65e732016-11-22 09:25:46 -0800634 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000635 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800636 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000637 logging.debug("LocalPaths: %s", paths)
638 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000639
agable0b65e732016-11-22 09:25:46 -0800640 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000641 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800642 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000643
John Budorick16162372018-04-18 10:39:53 -0700644 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800645 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000646 in the same directory as the current presubmit script, or subdirectories
647 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000648 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000649 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800650 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000651 " is deprecated and ignored" % str(include_deletes),
652 category=DeprecationWarning,
653 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800654 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -0700655 self.AffectedFiles(include_deletes=False, **kwargs))
agable0b65e732016-11-22 09:25:46 -0800656
657 def AffectedTextFiles(self, include_deletes=None):
658 """An alias to AffectedTestableFiles for backwards compatibility."""
659 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000660
maruel@chromium.org3410d912009-06-09 20:56:16 +0000661 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
662 """Filters out files that aren't considered "source file".
663
664 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
665 and InputApi.DEFAULT_BLACK_LIST is used respectively.
666
667 The lists will be compiled as regular expression and
668 AffectedFile.LocalPath() needs to pass both list.
669
670 Note: Copy-paste this function to suit your needs or use a lambda function.
671 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000672 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000673 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000674 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000675 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000676 return True
677 return False
678 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
679 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
680
681 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800682 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000683
684 If source_file is None, InputApi.FilterSourceFile() is used.
685 """
686 if not source_file:
687 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800688 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000689
690 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000691 """An iterator over all text lines in "new" version of changed files.
692
693 Only lists lines from new or modified text files in the change that are
694 contained by the directory of the currently executing presubmit script.
695
696 This is useful for doing line-by-line regex checks, like checking for
697 trailing whitespace.
698
699 Yields:
700 a 3 tuple:
701 the AffectedFile instance of the current file;
702 integer line number (1-based); and
703 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000704
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000705 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000706 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000707 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000708 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000709
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000710 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000711 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000712
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000713 Deny reading anything outside the repository.
714 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000715 if isinstance(file_item, AffectedFile):
716 file_item = file_item.AbsoluteLocalPath()
717 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000718 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000719 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000720
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100721 def CreateTemporaryFile(self, **kwargs):
722 """Returns a named temporary file that must be removed with a call to
723 RemoveTemporaryFiles().
724
725 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
726 except for |delete|, which is always set to False.
727
728 Presubmit checks that need to create a temporary file and pass it for
729 reading should use this function instead of NamedTemporaryFile(), as
730 Windows fails to open a file that is already open for writing.
731
732 with input_api.CreateTemporaryFile() as f:
733 f.write('xyz')
734 f.close()
735 input_api.subprocess.check_output(['script-that', '--reads-from',
736 f.name])
737
738
739 Note that callers of CreateTemporaryFile() should not worry about removing
740 any temporary file; this is done transparently by the presubmit handling
741 code.
742 """
743 if 'delete' in kwargs:
744 # Prevent users from passing |delete|; we take care of file deletion
745 # ourselves and this prevents unintuitive error messages when we pass
746 # delete=False and 'delete' is also in kwargs.
747 raise TypeError('CreateTemporaryFile() does not take a "delete" '
748 'argument, file deletion is handled automatically by '
749 'the same presubmit_support code that creates InputApi '
750 'objects.')
751 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
752 self._named_temporary_files.append(temp_file.name)
753 return temp_file
754
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000755 @property
756 def tbr(self):
757 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400758 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000759
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000760 def RunTests(self, tests_mix, parallel=True):
Edward Lesmes8e282792018-04-03 18:50:29 -0400761 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
762 # will run all tests once all PRESUBMIT files are processed.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000763 tests = []
764 msgs = []
765 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400766 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000767 msgs.append(t)
768 else:
769 assert issubclass(t.message, _PresubmitResult)
770 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000771 if self.verbose:
772 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400773 if not t.kwargs.get('cwd'):
774 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400775 self.thread_pool.AddTests(tests, parallel)
776 if not self.parallel:
777 msgs.extend(self.thread_pool.RunAsync())
778 return msgs
scottmg86099d72016-09-01 09:16:51 -0700779
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000780
nick@chromium.orgff526192013-06-10 19:30:26 +0000781class _DiffCache(object):
782 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000783 def __init__(self, upstream=None):
784 """Stores the upstream revision against which all diffs will be computed."""
785 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000786
787 def GetDiff(self, path, local_root):
788 """Get the diff for a particular path."""
789 raise NotImplementedError()
790
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700791 def GetOldContents(self, path, local_root):
792 """Get the old version for a particular path."""
793 raise NotImplementedError()
794
nick@chromium.orgff526192013-06-10 19:30:26 +0000795
nick@chromium.orgff526192013-06-10 19:30:26 +0000796class _GitDiffCache(_DiffCache):
797 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000798 def __init__(self, upstream):
799 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000800 self._diffs_by_file = None
801
802 def GetDiff(self, path, local_root):
803 if not self._diffs_by_file:
804 # Compute a single diff for all files and parse the output; should
805 # with git this is much faster than computing one diff for each file.
806 diffs = {}
807
808 # Don't specify any filenames below, because there are command line length
809 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000810 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
811 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000812
813 # This regex matches the path twice, separated by a space. Note that
814 # filename itself may contain spaces.
815 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
816 current_diff = []
817 keep_line_endings = True
818 for x in unified_diff.splitlines(keep_line_endings):
819 match = file_marker.match(x)
820 if match:
821 # Marks the start of a new per-file section.
822 diffs[match.group('filename')] = current_diff = [x]
823 elif x.startswith('diff --git'):
824 raise PresubmitFailure('Unexpected diff line: %s' % x)
825 else:
826 current_diff.append(x)
827
828 self._diffs_by_file = dict(
829 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
830
831 if path not in self._diffs_by_file:
832 raise PresubmitFailure(
833 'Unified diff did not contain entry for file %s' % path)
834
835 return self._diffs_by_file[path]
836
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700837 def GetOldContents(self, path, local_root):
838 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
839
nick@chromium.orgff526192013-06-10 19:30:26 +0000840
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000841class AffectedFile(object):
842 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000843
844 DIFF_CACHE = _DiffCache
845
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000846 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800847 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000848 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000849 self._path = path
850 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000851 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000852 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000853 self._cached_changed_contents = None
854 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000855 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700856 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000857
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858 def LocalPath(self):
859 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400860
861 This should be used for error messages but not for accessing files,
862 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
863 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000864 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000865 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000866
867 def AbsoluteLocalPath(self):
868 """Returns the absolute path of this file on the local disk.
869 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000870 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000872 def Action(self):
873 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000874 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000875
agable0b65e732016-11-22 09:25:46 -0800876 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000877 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000878
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000879 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000880 raise NotImplementedError() # Implement when needed
881
agable0b65e732016-11-22 09:25:46 -0800882 def IsTextFile(self):
883 """An alias to IsTestableFile for backwards compatibility."""
884 return self.IsTestableFile()
885
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700886 def OldContents(self):
887 """Returns an iterator over the lines in the old version of file.
888
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700889 The old version is the file before any modifications in the user's
890 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700891
892 Contents will be empty if the file is a directory or does not exist.
893 Note: The carriage returns (LF or CR) are stripped off.
894 """
895 return self._diff_cache.GetOldContents(self.LocalPath(),
896 self._local_root).splitlines()
897
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 def NewContents(self):
899 """Returns an iterator over the lines in the new version of file.
900
901 The new version is the file in the user's workspace, i.e. the "right hand
902 side".
903
904 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000905 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000906 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000907 if self._cached_new_contents is None:
908 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800909 try:
910 self._cached_new_contents = gclient_utils.FileRead(
911 self.AbsoluteLocalPath(), 'rU').splitlines()
912 except IOError:
913 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000914 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000915
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000916 def ChangedContents(self):
917 """Returns a list of tuples (line number, line text) of all new lines.
918
919 This relies on the scm diff output describing each changed code section
920 with a line of the form
921
922 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
923 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000924 if self._cached_changed_contents is not None:
925 return self._cached_changed_contents[:]
926 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000927 line_num = 0
928
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000929 for line in self.GenerateScmDiff().splitlines():
930 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
931 if m:
932 line_num = int(m.groups(1)[0])
933 continue
934 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000935 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000936 if not line.startswith('-'):
937 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000938 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000939
maruel@chromium.org5de13972009-06-10 18:16:06 +0000940 def __str__(self):
941 return self.LocalPath()
942
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000943 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000944 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000945
maruel@chromium.org58407af2011-04-12 23:15:57 +0000946
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000947class GitAffectedFile(AffectedFile):
948 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000949 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800950 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000951
nick@chromium.orgff526192013-06-10 19:30:26 +0000952 DIFF_CACHE = _GitDiffCache
953
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000954 def __init__(self, *args, **kwargs):
955 AffectedFile.__init__(self, *args, **kwargs)
956 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800957 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000958
agable0b65e732016-11-22 09:25:46 -0800959 def IsTestableFile(self):
960 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000961 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800962 # A deleted file is not testable.
963 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000964 else:
agable0b65e732016-11-22 09:25:46 -0800965 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
966 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000967
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000968
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000969class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000970 """Describe a change.
971
972 Used directly by the presubmit scripts to query the current change being
973 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000974
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000975 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000976 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000977 self.KEY: equivalent to tags['KEY']
978 """
979
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000980 _AFFECTED_FILES = AffectedFile
981
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000982 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000983 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000984 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000985 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000986
maruel@chromium.org58407af2011-04-12 23:15:57 +0000987 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000988 self, name, description, local_root, files, issue, patchset, author,
989 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000990 if files is None:
991 files = []
992 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000993 # Convert root into an absolute path.
994 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000995 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000996 self.issue = issue
997 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000998 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000999
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001000 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001001 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001002 self._description_without_tags = ''
1003 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004
maruel@chromium.orge085d812011-10-10 19:49:15 +00001005 assert all(
1006 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1007
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001008 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001009 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001010 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1011 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001012 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001013
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001014 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001015 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001016 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001017
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001018 def DescriptionText(self):
1019 """Returns the user-entered changelist description, minus tags.
1020
1021 Any line in the user-provided description starting with e.g. "FOO="
1022 (whitespace permitted before and around) is considered a tag line. Such
1023 lines are stripped out of the description this function returns.
1024 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001025 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001026
1027 def FullDescriptionText(self):
1028 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001029 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001030
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001031 def SetDescriptionText(self, description):
1032 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001033
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001034 Also updates the list of tags."""
1035 self._full_description = description
1036
1037 # From the description text, build up a dictionary of key/value pairs
1038 # plus the description minus all key/value or "tag" lines.
1039 description_without_tags = []
1040 self.tags = {}
1041 for line in self._full_description.splitlines():
1042 m = self.TAG_LINE_RE.match(line)
1043 if m:
1044 self.tags[m.group('key')] = m.group('value')
1045 else:
1046 description_without_tags.append(line)
1047
1048 # Change back to text and remove whitespace at end.
1049 self._description_without_tags = (
1050 '\n'.join(description_without_tags).rstrip())
1051
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001052 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001053 """Returns the repository (checkout) root directory for this change,
1054 as an absolute path.
1055 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001056 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001057
1058 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001059 """Return tags directly as attributes on the object."""
1060 if not re.match(r"^[A-Z_]*$", attr):
1061 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001062 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001063
Aaron Gablefc03e672017-05-15 14:09:42 -07001064 def BugsFromDescription(self):
1065 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001066 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
1067 footers = git_footers.parse_footers(self._full_description).get('Bug', [])
1068 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001069
1070 def ReviewersFromDescription(self):
1071 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001072 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1073 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1074 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001075
1076 def TBRsFromDescription(self):
1077 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001078 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1079 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1080 # determined by self-CR+1s.
1081 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1082 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001083
1084 # TODO(agable): Delete these once we're sure they're unused.
1085 @property
1086 def BUG(self):
1087 return ','.join(self.BugsFromDescription())
1088 @property
1089 def R(self):
1090 return ','.join(self.ReviewersFromDescription())
1091 @property
1092 def TBR(self):
1093 return ','.join(self.TBRsFromDescription())
1094
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001095 def AllFiles(self, root=None):
1096 """List all files under source control in the repo."""
1097 raise NotImplementedError()
1098
agable0b65e732016-11-22 09:25:46 -08001099 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001100 """Returns a list of AffectedFile instances for all files in the change.
1101
1102 Args:
1103 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001104 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001105
1106 Returns:
1107 [AffectedFile(path, action), AffectedFile(path, action)]
1108 """
agable0b65e732016-11-22 09:25:46 -08001109 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +00001110
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001111 if include_deletes:
1112 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -07001113 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001114
John Budorick16162372018-04-18 10:39:53 -07001115 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001116 """Return a list of the existing text files in a change."""
1117 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001118 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001119 " is deprecated and ignored" % str(include_deletes),
1120 category=DeprecationWarning,
1121 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -08001122 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -07001123 self.AffectedFiles(include_deletes=False, **kwargs))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001124
agable0b65e732016-11-22 09:25:46 -08001125 def AffectedTextFiles(self, include_deletes=None):
1126 """An alias to AffectedTestableFiles for backwards compatibility."""
1127 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001128
agable0b65e732016-11-22 09:25:46 -08001129 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001130 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001131 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001132
agable0b65e732016-11-22 09:25:46 -08001133 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001134 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001135 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001136
1137 def RightHandSideLines(self):
1138 """An iterator over all text lines in "new" version of changed files.
1139
1140 Lists lines from new or modified text files in the change.
1141
1142 This is useful for doing line-by-line regex checks, like checking for
1143 trailing whitespace.
1144
1145 Yields:
1146 a 3 tuple:
1147 the AffectedFile instance of the current file;
1148 integer line number (1-based); and
1149 the contents of the line as a string.
1150 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001151 return _RightHandSideLinesImpl(
1152 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001153 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001154
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001155 def OriginalOwnersFiles(self):
1156 """A map from path names of affected OWNERS files to their old content."""
1157 def owners_file_filter(f):
1158 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1159 files = self.AffectedFiles(file_filter=owners_file_filter)
1160 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1161
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001162
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001163class GitChange(Change):
1164 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001165 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001166
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001167 def AllFiles(self, root=None):
1168 """List all files under source control in the repo."""
1169 root = root or self.RepositoryRoot()
1170 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001171 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1172 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001173
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001174
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001175def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001176 """Finds all presubmit files that apply to a given set of source files.
1177
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001178 If inherit-review-settings-ok is present right under root, looks for
1179 PRESUBMIT.py in directories enclosing root.
1180
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001181 Args:
1182 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001183 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001184
1185 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001186 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001187 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001188 files = [normpath(os.path.join(root, f)) for f in files]
1189
1190 # List all the individual directories containing files.
1191 directories = set([os.path.dirname(f) for f in files])
1192
1193 # Ignore root if inherit-review-settings-ok is present.
1194 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1195 root = None
1196
1197 # Collect all unique directories that may contain PRESUBMIT.py.
1198 candidates = set()
1199 for directory in directories:
1200 while True:
1201 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001202 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001203 candidates.add(directory)
1204 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001205 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001206 parent_dir = os.path.dirname(directory)
1207 if parent_dir == directory:
1208 # We hit the system root directory.
1209 break
1210 directory = parent_dir
1211
1212 # Look for PRESUBMIT.py in all candidate directories.
1213 results = []
1214 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001215 try:
1216 for f in os.listdir(directory):
1217 p = os.path.join(directory, f)
1218 if os.path.isfile(p) and re.match(
1219 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1220 results.append(p)
1221 except OSError:
1222 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001223
tobiasjs2836bcf2016-08-16 04:08:16 -07001224 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001225 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001226
1227
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001228class GetTryMastersExecuter(object):
1229 @staticmethod
1230 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1231 """Executes GetPreferredTryMasters() from a single presubmit script.
1232
1233 Args:
1234 script_text: The text of the presubmit script.
1235 presubmit_path: Project script to run.
1236 project: Project name to pass to presubmit script for bot selection.
1237
1238 Return:
1239 A map of try masters to map of builders to set of tests.
1240 """
1241 context = {}
1242 try:
1243 exec script_text in context
1244 except Exception, e:
1245 raise PresubmitFailure('"%s" had an exception.\n%s'
1246 % (presubmit_path, e))
1247
1248 function_name = 'GetPreferredTryMasters'
1249 if function_name not in context:
1250 return {}
1251 get_preferred_try_masters = context[function_name]
1252 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1253 raise PresubmitFailure(
1254 'Expected function "GetPreferredTryMasters" to take two arguments.')
1255 return get_preferred_try_masters(project, change)
1256
1257
rmistry@google.com5626a922015-02-26 14:03:30 +00001258class GetPostUploadExecuter(object):
1259 @staticmethod
1260 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1261 """Executes PostUploadHook() from a single presubmit script.
1262
1263 Args:
1264 script_text: The text of the presubmit script.
1265 presubmit_path: Project script to run.
1266 cl: The Changelist object.
1267 change: The Change object.
1268
1269 Return:
1270 A list of results objects.
1271 """
1272 context = {}
1273 try:
1274 exec script_text in context
1275 except Exception, e:
1276 raise PresubmitFailure('"%s" had an exception.\n%s'
1277 % (presubmit_path, e))
1278
1279 function_name = 'PostUploadHook'
1280 if function_name not in context:
1281 return {}
1282 post_upload_hook = context[function_name]
1283 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1284 raise PresubmitFailure(
1285 'Expected function "PostUploadHook" to take three arguments.')
1286 return post_upload_hook(cl, change, OutputApi(False))
1287
1288
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001289def _MergeMasters(masters1, masters2):
1290 """Merges two master maps. Merges also the tests of each builder."""
1291 result = {}
1292 for (master, builders) in itertools.chain(masters1.iteritems(),
1293 masters2.iteritems()):
1294 new_builders = result.setdefault(master, {})
1295 for (builder, tests) in builders.iteritems():
1296 new_builders.setdefault(builder, set([])).update(tests)
1297 return result
1298
1299
1300def DoGetTryMasters(change,
1301 changed_files,
1302 repository_root,
1303 default_presubmit,
1304 project,
1305 verbose,
1306 output_stream):
1307 """Get the list of try masters from the presubmit scripts.
1308
1309 Args:
1310 changed_files: List of modified files.
1311 repository_root: The repository root.
1312 default_presubmit: A default presubmit script to execute in any case.
1313 project: Optional name of a project used in selecting trybots.
1314 verbose: Prints debug info.
1315 output_stream: A stream to write debug output to.
1316
1317 Return:
1318 Map of try masters to map of builders to set of tests.
1319 """
1320 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1321 if not presubmit_files and verbose:
1322 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1323 results = {}
1324 executer = GetTryMastersExecuter()
1325
1326 if default_presubmit:
1327 if verbose:
1328 output_stream.write("Running default presubmit script.\n")
1329 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1330 results = _MergeMasters(results, executer.ExecPresubmitScript(
1331 default_presubmit, fake_path, project, change))
1332 for filename in presubmit_files:
1333 filename = os.path.abspath(filename)
1334 if verbose:
1335 output_stream.write("Running %s\n" % filename)
1336 # Accept CRLF presubmit script.
1337 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1338 results = _MergeMasters(results, executer.ExecPresubmitScript(
1339 presubmit_script, filename, project, change))
1340
1341 # Make sets to lists again for later JSON serialization.
1342 for builders in results.itervalues():
1343 for builder in builders:
1344 builders[builder] = list(builders[builder])
1345
1346 if results and verbose:
1347 output_stream.write('%s\n' % str(results))
1348 return results
1349
1350
rmistry@google.com5626a922015-02-26 14:03:30 +00001351def DoPostUploadExecuter(change,
1352 cl,
1353 repository_root,
1354 verbose,
1355 output_stream):
1356 """Execute the post upload hook.
1357
1358 Args:
1359 change: The Change object.
1360 cl: The Changelist object.
1361 repository_root: The repository root.
1362 verbose: Prints debug info.
1363 output_stream: A stream to write debug output to.
1364 """
1365 presubmit_files = ListRelevantPresubmitFiles(
1366 change.LocalPaths(), repository_root)
1367 if not presubmit_files and verbose:
1368 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1369 results = []
1370 executer = GetPostUploadExecuter()
1371 # The root presubmit file should be executed after the ones in subdirectories.
1372 # i.e. the specific post upload hooks should run before the general ones.
1373 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1374 presubmit_files.reverse()
1375
1376 for filename in presubmit_files:
1377 filename = os.path.abspath(filename)
1378 if verbose:
1379 output_stream.write("Running %s\n" % filename)
1380 # Accept CRLF presubmit script.
1381 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1382 results.extend(executer.ExecPresubmitScript(
1383 presubmit_script, filename, cl, change))
1384 output_stream.write('\n')
1385 if results:
1386 output_stream.write('** Post Upload Hook Messages **\n')
1387 for result in results:
1388 result.handle(output_stream)
1389 output_stream.write('\n')
1390
1391 return results
1392
1393
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001394class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001395 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001396 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001397 """
1398 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001399 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001400 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001401 gerrit_obj: provides basic Gerrit codereview functionality.
1402 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001403 parallel: if true, all tests reported via input_api.RunTests for all
1404 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001405 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001406 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001407 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001408 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001409 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001410 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001411 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001412 self.thread_pool = thread_pool
1413 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001414
1415 def ExecPresubmitScript(self, script_text, presubmit_path):
1416 """Executes a single presubmit script.
1417
1418 Args:
1419 script_text: The text of the presubmit script.
1420 presubmit_path: The path to the presubmit file (this will be reported via
1421 input_api.PresubmitLocalPath()).
1422
1423 Return:
1424 A list of result objects, empty if no problems.
1425 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001426
chase@chromium.org8e416c82009-10-06 04:30:44 +00001427 # Change to the presubmit file's directory to support local imports.
1428 main_path = os.getcwd()
1429 os.chdir(os.path.dirname(presubmit_path))
1430
1431 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001432 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001433 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001434 dry_run=self.dry_run, thread_pool=self.thread_pool,
1435 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001436 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001437 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001438 try:
1439 exec script_text in context
1440 except Exception, e:
1441 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001442
1443 # These function names must change if we make substantial changes to
1444 # the presubmit API that are not backwards compatible.
1445 if self.committing:
1446 function_name = 'CheckChangeOnCommit'
1447 else:
1448 function_name = 'CheckChangeOnUpload'
1449 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001450 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001451 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001452 logging.debug('Running %s in %s', function_name, presubmit_path)
1453 result = eval(function_name + '(*__args)', context)
1454 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001455 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001456 finally:
1457 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001458 if not (isinstance(result, types.TupleType) or
1459 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001460 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001461 'Presubmit functions must return a tuple or list')
1462 for item in result:
1463 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001464 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001465 'All presubmit results must be of types derived from '
1466 'output_api.PresubmitResult')
1467 else:
1468 result = () # no error since the script doesn't care about current event.
1469
chase@chromium.org8e416c82009-10-06 04:30:44 +00001470 # Return the process to the original working directory.
1471 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001472 return result
1473
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001474def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001475 committing,
1476 verbose,
1477 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001478 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001479 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001480 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001481 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001482 dry_run=None,
1483 parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001484 """Runs all presubmit checks that apply to the files in the change.
1485
1486 This finds all PRESUBMIT.py files in directories enclosing the files in the
1487 change (up to the repository root) and calls the relevant entrypoint function
1488 depending on whether the change is being committed or uploaded.
1489
1490 Prints errors, warnings and notifications. Prompts the user for warnings
1491 when needed.
1492
1493 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001494 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001495 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001496 verbose: Prints debug info.
1497 output_stream: A stream to write output from presubmit tests to.
1498 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001499 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001500 may_prompt: Enable (y/n) questions on warning or error. If False,
1501 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001502 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001503 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001504 parallel: if true, all tests specified by input_api.RunTests in all
1505 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001506
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001507 Warning:
1508 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1509 SHOULD be sys.stdin.
1510
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001511 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001512 A PresubmitOutput object. Use output.should_continue() to figure out
1513 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001514 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001515 old_environ = os.environ
1516 try:
1517 # Make sure python subprocesses won't generate .pyc files.
1518 os.environ = os.environ.copy()
1519 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001520
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001521 output = PresubmitOutput(input_stream, output_stream)
1522 if committing:
1523 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001524 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001525 output.write("Running presubmit upload checks ...\n")
1526 start_time = time.time()
1527 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001528 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001529 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001530 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001531 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001532 thread_pool = ThreadPool()
Aaron Gable668c1d82018-04-03 10:19:16 -07001533 executer = PresubmitExecuter(change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001534 gerrit_obj, dry_run, thread_pool)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001535 if default_presubmit:
1536 if verbose:
1537 output.write("Running default presubmit script.\n")
1538 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1539 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1540 for filename in presubmit_files:
1541 filename = os.path.abspath(filename)
1542 if verbose:
1543 output.write("Running %s\n" % filename)
1544 # Accept CRLF presubmit script.
1545 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1546 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001547
Edward Lesmes8e282792018-04-03 18:50:29 -04001548 results += thread_pool.RunAsync()
1549
Daniel Cheng7227d212017-11-17 08:12:37 -08001550 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001551 errors = []
1552 notifications = []
1553 warnings = []
1554 for result in results:
1555 if result.fatal:
1556 errors.append(result)
1557 elif result.should_prompt:
1558 warnings.append(result)
1559 else:
1560 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001561
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001562 output.write('\n')
1563 for name, items in (('Messages', notifications),
1564 ('Warnings', warnings),
1565 ('ERRORS', errors)):
1566 if items:
1567 output.write('** Presubmit %s **\n' % name)
1568 for item in items:
1569 item.handle(output)
1570 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001571
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001572 total_time = time.time() - start_time
1573 if total_time > 1.0:
1574 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001575
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001576 if errors:
1577 output.fail()
1578 elif warnings:
1579 output.write('There were presubmit warnings. ')
1580 if may_prompt:
1581 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1582 else:
1583 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001584
1585 global _ASKED_FOR_FEEDBACK
1586 # Ask for feedback one time out of 5.
1587 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001588 output.write(
1589 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1590 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1591 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001592 _ASKED_FOR_FEEDBACK = True
1593 return output
1594 finally:
1595 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001596
1597
1598def ScanSubDirs(mask, recursive):
1599 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001600 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001601
1602 results = []
1603 for root, dirs, files in os.walk('.'):
1604 if '.svn' in dirs:
1605 dirs.remove('.svn')
1606 if '.git' in dirs:
1607 dirs.remove('.git')
1608 for name in files:
1609 if fnmatch.fnmatch(name, mask):
1610 results.append(os.path.join(root, name))
1611 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001612
1613
1614def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001615 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001616 files = []
1617 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001618 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001619 return files
1620
1621
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001622def load_files(options, args):
1623 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001624 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001625 if args:
1626 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001627 change_scm = scm.determine_scm(options.root)
1628 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001629 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001630 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001631 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001632 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001633 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001634 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001635 if not files:
1636 return None, None
1637 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001638 return change_class, files
1639
1640
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001641@contextlib.contextmanager
1642def canned_check_filter(method_names):
1643 filtered = {}
1644 try:
1645 for method_name in method_names:
1646 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001647 logging.warn('Skipping unknown "canned" check %s' % method_name)
1648 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001649 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1650 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1651 yield
1652 finally:
1653 for name, method in filtered.iteritems():
1654 setattr(presubmit_canned_checks, name, method)
1655
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001656
sbc@chromium.org013731e2015-02-26 18:28:43 +00001657def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001658 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001659 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001660 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001661 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001662 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1663 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001664 parser.add_option("-r", "--recursive", action="store_true",
1665 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001666 parser.add_option("-v", "--verbose", action="count", default=0,
1667 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001668 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001669 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001670 parser.add_option("--description", default='')
1671 parser.add_option("--issue", type='int', default=0)
1672 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001673 parser.add_option("--root", default=os.getcwd(),
1674 help="Search for PRESUBMIT.py up to this directory. "
1675 "If inherit-review-settings-ok is present in this "
1676 "directory, parent directories up to the root file "
1677 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001678 parser.add_option("--upstream",
1679 help="Git only: the base ref or upstream branch against "
1680 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001681 parser.add_option("--default_presubmit")
1682 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001683 parser.add_option("--skip_canned", action='append', default=[],
1684 help="A list of checks to skip which appear in "
1685 "presubmit_canned_checks. Can be provided multiple times "
1686 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001687 parser.add_option("--dry_run", action='store_true',
1688 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001689 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001690 parser.add_option("--gerrit_fetch", action='store_true',
1691 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001692 parser.add_option('--parallel', action='store_true',
1693 help='Run all tests specified by input_api.RunTests in all '
1694 'PRESUBMIT files in parallel.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001695
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001696 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001697
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001698 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001699 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001700 elif options.verbose:
1701 logging.basicConfig(level=logging.INFO)
1702 else:
1703 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001704
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001705 change_class, files = load_files(options, args)
1706 if not change_class:
1707 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001708 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001709
Aaron Gable668c1d82018-04-03 10:19:16 -07001710 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001711 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001712 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001713 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1714 options.author = gerrit_obj.GetChangeOwner(options.issue)
1715 options.description = gerrit_obj.GetChangeDescription(options.issue,
1716 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001717 logging.info('Got author: "%s"', options.author)
1718 logging.info('Got description: """\n%s\n"""', options.description)
1719
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001720 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001721 with canned_check_filter(options.skip_canned):
1722 results = DoPresubmitChecks(
1723 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001724 options.description,
1725 options.root,
1726 files,
1727 options.issue,
1728 options.patchset,
1729 options.author,
1730 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001731 options.commit,
1732 options.verbose,
1733 sys.stdout,
1734 sys.stdin,
1735 options.default_presubmit,
1736 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001737 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001738 options.dry_run,
1739 options.parallel)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001740 return not results.should_continue()
1741 except PresubmitFailure, e:
1742 print >> sys.stderr, e
1743 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001744 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001745
1746
1747if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001748 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001749 try:
1750 sys.exit(main())
1751 except KeyboardInterrupt:
1752 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001753 sys.exit(2)