blob: 9f8115d3fe98d70f44300b58fc6973cc89c3b5e4 [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.
enne@chromium.orge72c5f52013-04-16 00:36:40 +000016import cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000017import cPickle # Exposed through the API.
18import cStringIO # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000019import contextlib
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 Lesmesc7d0b342018-03-28 21:19:00 -040033import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000034import sys # Parts exposed through API.
35import tempfile # Exposed through the API.
Edward Lesmesc7d0b342018-03-28 21:19:00 -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.
Aaron Gableaa6ddc62018-04-02 14:54:30 -070046import auth
maruel@chromium.org35625c72011-03-23 17:34:02 +000047import fix_encoding
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000048import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070049import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000050import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000051import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020052import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000053import presubmit_canned_checks
Aaron Gableaa6ddc62018-04-02 14:54:30 -070054import rietveld
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000055import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000056import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000057
58
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000059# Ask for feedback only once in program lifetime.
60_ASKED_FOR_FEEDBACK = False
61
62
maruel@chromium.org899e1c12011-04-07 17:03:18 +000063class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000064 pass
65
66
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000067class CommandData(object):
68 def __init__(self, name, cmd, kwargs, message):
69 self.name = name
70 self.cmd = cmd
Edward Lesmesc7d0b342018-03-28 21:19:00 -040071 self.stdin = kwargs.get('stdin', None)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000072 self.kwargs = kwargs
Edward Lesmesc7d0b342018-03-28 21:19:00 -040073 self.kwargs['stdout'] = subprocess.PIPE
74 self.kwargs['stderr'] = subprocess.STDOUT
75 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000076 self.message = message
77 self.info = None
78
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000079
Edward Lesmesc7d0b342018-03-28 21:19:00 -040080# Adapted from
81# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
82#
83# An object that catches SIGINT sent to the Python process and notices
84# if processes passed to wait() die by SIGINT (we need to look for
85# both of those cases, because pressing Ctrl+C can result in either
86# the main process or one of the subprocesses getting the signal).
87#
88# Before a SIGINT is seen, wait(p) will simply call p.wait() and
89# return the result. Once a SIGINT has been seen (in the main process
90# or a subprocess, including the one the current call is waiting for),
91# wait(p) will call p.terminate() and raise ProcessWasInterrupted.
92class SigintHandler(object):
93 class ProcessWasInterrupted(Exception):
94 pass
95
96 sigint_returncodes = {-signal.SIGINT, # Unix
97 -1073741510, # Windows
98 }
99 def __init__(self):
100 self.__lock = threading.Lock()
101 self.__processes = set()
102 self.__got_sigint = False
103 signal.signal(signal.SIGINT, lambda signal_num, frame: self.interrupt())
104
105 def __on_sigint(self):
106 self.__got_sigint = True
107 while self.__processes:
108 try:
109 self.__processes.pop().terminate()
110 except OSError:
111 pass
112
113 def interrupt(self):
114 with self.__lock:
115 self.__on_sigint()
116
117 def got_sigint(self):
118 with self.__lock:
119 return self.__got_sigint
120
121 def wait(self, p, stdin):
122 with self.__lock:
123 if self.__got_sigint:
124 p.terminate()
125 self.__processes.add(p)
126 stdout, stderr = p.communicate(stdin)
127 code = p.returncode
128 with self.__lock:
129 self.__processes.discard(p)
130 if code in self.sigint_returncodes:
131 self.__on_sigint()
132 if self.__got_sigint:
133 raise self.ProcessWasInterrupted
134 return stdout, stderr
135
136sigint_handler = SigintHandler()
137
138
139class ThreadPool(object):
140 def __init__(self, pool_size=None):
141 self._tests = []
142 self._nonparallel_tests = []
143 self._pool_size = pool_size or multiprocessing.cpu_count()
144 self._messages = []
145 self._messages_lock = threading.Lock()
146 self._current_index = 0
147 self._current_index_lock = threading.Lock()
148
149 def CallCommand(self, test):
150 """Runs an external program.
151
152 This function converts invocation of .py files and invocations of "python"
153 to vpython invocations.
154 """
155 vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython'
156
157 cmd = test.cmd
158 if cmd[0] == 'python':
159 cmd = list(cmd)
160 cmd[0] = vpython
161 elif cmd[0].endswith('.py'):
162 cmd = [vpython] + cmd
163
164 try:
165 start = time.time()
166 p = subprocess.Popen(cmd, **test.kwargs)
167 stdout, _ = sigint_handler.wait(p, test.stdin)
168 duration = time.time() - start
169 except OSError as e:
170 duration = time.time() - start
171 return test.message(
172 '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e))
173 if p.returncode != 0:
174 return test.message(
175 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
176 if test.info:
177 return test.info('%s (%4.2fs)' % (test.name, duration))
178
179 def AddTests(self, tests, parallel=True):
180 if parallel:
181 self._tests.extend(tests)
182 else:
183 self._nonparallel_tests.extend(tests)
184
185 def RunAsync(self):
186 def _WorkerFn():
187 while True:
188 test_index = None
189 with self._current_index_lock:
190 if self._current_index == len(self._tests):
191 break
192 test_index = self._current_index
193 self._current_index += 1
194 result = self.CallCommand(self._tests[test_index])
195 if result:
196 with self._messages_lock:
197 self._messages.append(result)
198
199 def _StartDaemon():
200 t = threading.Thread(target=_WorkerFn)
201 t.daemon = True
202 t.start()
203 return t
204
205 for test in self._nonparallel_tests:
206 result = self.CallCommand(test)
207 if result:
208 self._messages.append(result)
209
210 if self._tests:
211 threads = [_StartDaemon() for _ in range(self._pool_size)]
212 for worker in threads:
213 worker.join()
214
215 return self._messages
216
217
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000218def normpath(path):
219 '''Version of os.path.normpath that also changes backward slashes to
220 forward slashes when not running on Windows.
221 '''
222 # This is safe to always do because the Windows version of os.path.normpath
223 # will replace forward slashes with backward slashes.
224 path = path.replace(os.sep, '/')
225 return os.path.normpath(path)
226
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000227
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000228def _RightHandSideLinesImpl(affected_files):
229 """Implements RightHandSideLines for InputApi and GclChange."""
230 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000231 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000232 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000233 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000234
235
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000236class PresubmitOutput(object):
237 def __init__(self, input_stream=None, output_stream=None):
238 self.input_stream = input_stream
239 self.output_stream = output_stream
240 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800241 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000242 self.written_output = []
243 self.error_count = 0
244
245 def prompt_yes_no(self, prompt_string):
246 self.write(prompt_string)
247 if self.input_stream:
248 response = self.input_stream.readline().strip().lower()
249 if response not in ('y', 'yes'):
250 self.fail()
251 else:
252 self.fail()
253
254 def fail(self):
255 self.error_count += 1
256
257 def should_continue(self):
258 return not self.error_count
259
260 def write(self, s):
261 self.written_output.append(s)
262 if self.output_stream:
263 self.output_stream.write(s)
264
265 def getvalue(self):
266 return ''.join(self.written_output)
267
268
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000269# Top level object so multiprocessing can pickle
270# Public access through OutputApi object.
271class _PresubmitResult(object):
272 """Base class for result objects."""
273 fatal = False
274 should_prompt = False
275
276 def __init__(self, message, items=None, long_text=''):
277 """
278 message: A short one-line message to indicate errors.
279 items: A list of short strings to indicate where errors occurred.
280 long_text: multi-line text output, e.g. from another tool
281 """
282 self._message = message
283 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000284 self._long_text = long_text.rstrip()
285
286 def handle(self, output):
287 output.write(self._message)
288 output.write('\n')
289 for index, item in enumerate(self._items):
290 output.write(' ')
291 # Write separately in case it's unicode.
292 output.write(str(item))
293 if index < len(self._items) - 1:
294 output.write(' \\')
295 output.write('\n')
296 if self._long_text:
297 output.write('\n***************\n')
298 # Write separately in case it's unicode.
299 output.write(self._long_text)
300 output.write('\n***************\n')
301 if self.fatal:
302 output.fail()
303
304
305# Top level object so multiprocessing can pickle
306# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000307class _PresubmitError(_PresubmitResult):
308 """A hard presubmit error."""
309 fatal = True
310
311
312# Top level object so multiprocessing can pickle
313# Public access through OutputApi object.
314class _PresubmitPromptWarning(_PresubmitResult):
315 """An warning that prompts the user if they want to continue."""
316 should_prompt = True
317
318
319# Top level object so multiprocessing can pickle
320# Public access through OutputApi object.
321class _PresubmitNotifyResult(_PresubmitResult):
322 """Just print something to the screen -- but it's not even a warning."""
323 pass
324
325
326# Top level object so multiprocessing can pickle
327# Public access through OutputApi object.
328class _MailTextResult(_PresubmitResult):
329 """A warning that should be included in the review request email."""
330 def __init__(self, *args, **kwargs):
331 super(_MailTextResult, self).__init__()
332 raise NotImplementedError()
333
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000334class GerritAccessor(object):
335 """Limited Gerrit functionality for canned presubmit checks to work.
336
337 To avoid excessive Gerrit calls, caches the results.
338 """
339
340 def __init__(self, host):
341 self.host = host
342 self.cache = {}
343
344 def _FetchChangeDetail(self, issue):
345 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100346 try:
347 return gerrit_util.GetChangeDetail(
348 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700349 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100350 except gerrit_util.GerritError as e:
351 if e.http_status == 404:
352 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
353 'no credentials to fetch issue details' % issue)
354 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000355
356 def GetChangeInfo(self, issue):
357 """Returns labels and all revisions (patchsets) for this issue.
358
359 The result is a dictionary according to Gerrit REST Api.
360 https://gerrit-review.googlesource.com/Documentation/rest-api.html
361
362 However, API isn't very clear what's inside, so see tests for example.
363 """
364 assert issue
365 cache_key = int(issue)
366 if cache_key not in self.cache:
367 self.cache[cache_key] = self._FetchChangeDetail(issue)
368 return self.cache[cache_key]
369
370 def GetChangeDescription(self, issue, patchset=None):
371 """If patchset is none, fetches current patchset."""
372 info = self.GetChangeInfo(issue)
373 # info is a reference to cache. We'll modify it here adding description to
374 # it to the right patchset, if it is not yet there.
375
376 # Find revision info for the patchset we want.
377 if patchset is not None:
378 for rev, rev_info in info['revisions'].iteritems():
379 if str(rev_info['_number']) == str(patchset):
380 break
381 else:
382 raise Exception('patchset %s doesn\'t exist in issue %s' % (
383 patchset, issue))
384 else:
385 rev = info['current_revision']
386 rev_info = info['revisions'][rev]
387
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100388 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000389
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800390 def GetDestRef(self, issue):
391 ref = self.GetChangeInfo(issue)['branch']
392 if not ref.startswith('refs/'):
393 # NOTE: it is possible to create 'refs/x' branch,
394 # aka 'refs/heads/refs/x'. However, this is ill-advised.
395 ref = 'refs/heads/%s' % ref
396 return ref
397
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000398 def GetChangeOwner(self, issue):
399 return self.GetChangeInfo(issue)['owner']['email']
400
401 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700402 changeinfo = self.GetChangeInfo(issue)
403 if approving_only:
404 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
405 values = labelinfo.get('values', {}).keys()
406 try:
407 max_value = max(int(v) for v in values)
408 reviewers = [r for r in labelinfo.get('all', [])
409 if r.get('value', 0) == max_value]
410 except ValueError: # values is the empty list
411 reviewers = []
412 else:
413 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
414 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000415
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000416
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000417class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000418 """An instance of OutputApi gets passed to presubmit scripts so that they
419 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000420 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000421 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000422 PresubmitError = _PresubmitError
423 PresubmitPromptWarning = _PresubmitPromptWarning
424 PresubmitNotifyResult = _PresubmitNotifyResult
425 MailTextResult = _MailTextResult
426
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000427 def __init__(self, is_committing):
428 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800429 self.more_cc = []
430
431 def AppendCC(self, cc):
432 """Appends a user to cc for this change."""
433 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000434
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000435 def PresubmitPromptOrNotify(self, *args, **kwargs):
436 """Warn the user when uploading, but only notify if committing."""
437 if self.is_committing:
438 return self.PresubmitNotifyResult(*args, **kwargs)
439 return self.PresubmitPromptWarning(*args, **kwargs)
440
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800441 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
442 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
443
444 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
445 keeping it alphabetically sorted. Returns the results that should be
446 returned from the PostUploadHook.
447
448 Args:
449 cl: The git_cl.Changelist object.
450 bots_to_include: A list of strings of bots to include, in the form
451 "master:slave".
452 message: A message to be printed in the case that
453 CQ_INCLUDE_TRYBOTS was updated.
454 """
455 description = cl.GetDescription(force=True)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700456 include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)$', re.M | re.I)
457
458 prior_bots = []
459 if cl.IsGerrit():
460 trybot_footers = git_footers.parse_footers(description).get(
461 git_footers.normalize_name('Cq-Include-Trybots'), [])
462 for f in trybot_footers:
463 prior_bots += [b.strip() for b in f.split(';') if b.strip()]
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800464 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700465 trybot_tags = include_re.finditer(description)
466 for t in trybot_tags:
467 prior_bots += [b.strip() for b in t.group(1).split(';') if b.strip()]
468
469 if set(prior_bots) >= set(bots_to_include):
470 return []
471 all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include)))
472
473 if cl.IsGerrit():
474 description = git_footers.remove_footer(
475 description, 'Cq-Include-Trybots')
476 description = git_footers.add_footer(
477 description, 'Cq-Include-Trybots', all_bots,
478 before_keys=['Change-Id'])
479 else:
480 new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % all_bots
481 m = include_re.search(description)
482 if m:
483 description = include_re.sub(new_include_trybots, description)
Kenneth Russelldf6e7342017-04-24 17:07:41 -0700484 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700485 description = '%s\n%s\n' % (description, new_include_trybots)
486
487 cl.UpdateDescription(description, force=True)
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800488 return [self.PresubmitNotifyResult(message)]
489
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000490
491class InputApi(object):
492 """An instance of this object is passed to presubmit scripts so they can
493 know stuff about the change they're looking at.
494 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000495 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800496 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000497
maruel@chromium.org3410d912009-06-09 20:56:16 +0000498 # File extensions that are considered source files from a style guide
499 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000500 #
501 # Files without an extension aren't included in the list. If you want to
502 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
503 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000504 DEFAULT_WHITE_LIST = (
505 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000506 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
507 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000508 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000509 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000510 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000511 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000512 )
513
514 # Path regexp that should be excluded from being considered containing source
515 # files. Don't modify this list from a presubmit script!
516 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000517 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000518 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000519 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
520 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000521 # Output directories (just in case)
522 r".*\bDebug[\\\/].*",
523 r".*\bRelease[\\\/].*",
524 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000525 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000526 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000527 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000528 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000529 r"(|.*[\\\/])\.git[\\\/].*",
530 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000531 # There is no point in processing a patch file.
532 r".+\.diff$",
533 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000534 )
535
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000536 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmesc7d0b342018-03-28 21:19:00 -0400537 rietveld_obj, verbose, gerrit_obj=None, dry_run=None, thread_pool=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000538 """Builds an InputApi object.
539
540 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000541 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000542 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000543 is_committing: True if the change is about to be committed.
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700544 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000545 gerrit_obj: provides basic Gerrit codereview functionality.
546 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000547 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000548 # Version number of the presubmit_support script.
549 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000550 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000551 self.is_committing = is_committing
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700552 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000553 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000554 self.dry_run = dry_run
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700555 # TBD
556 self.host_url = 'http://codereview.chromium.org'
557 if self.rietveld:
558 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000559
Edward Lesmesc7d0b342018-03-28 21:19:00 -0400560 self.thread_pool = thread_pool or ThreadPool()
561
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000562 # We expose various modules and functions as attributes of the input_api
563 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900564 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000565 self.basename = os.path.basename
566 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000567 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000568 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700569 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000570 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000571 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000572 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000573 self.os_listdir = os.listdir
574 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000575 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000576 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000577 self.pickle = pickle
578 self.marshal = marshal
579 self.re = re
580 self.subprocess = subprocess
581 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000582 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000583 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000584 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000585 self.urllib2 = urllib2
586
Robert Iannucci50258932018-03-19 10:30:59 -0700587 self.is_windows = sys.platform == 'win32'
588
589 # Set python_executable to 'python'. This is interpreted in CallCommand to
590 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
591 # to automatically pick up that repo's .vpython file, instead of inheriting
592 # the one in depot_tools.
593 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000594 self.environ = os.environ
595
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000596 # InputApi.platform is the platform you're currently running on.
597 self.platform = sys.platform
598
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000599 self.cpu_count = multiprocessing.cpu_count()
600
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000601 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000602 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000603
604 # We carry the canned checks so presubmit scripts can easily use them.
605 self.canned_checks = presubmit_canned_checks
606
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100607 # Temporary files we must manually remove at the end of a run.
608 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200609
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000610 # TODO(dpranke): figure out a list of all approved owners for a repo
611 # in order to be able to handle wildcard OWNERS files?
612 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200613 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200614 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000615 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000616 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000617
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000618 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000619 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000620 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800621 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000622 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000623 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000624 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
625 for (a, b, header) in cpplint._re_pattern_templates
626 ]
627
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000628 def PresubmitLocalPath(self):
629 """Returns the local path of the presubmit script currently being run.
630
631 This is useful if you don't want to hard-code absolute paths in the
632 presubmit script. For example, It can be used to find another file
633 relative to the PRESUBMIT.py script, so the whole tree can be branched and
634 the presubmit script still works, without editing its content.
635 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000636 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000637
agable0b65e732016-11-22 09:25:46 -0800638 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000639 """Same as input_api.change.AffectedFiles() except only lists files
640 (and optionally directories) in the same directory as the current presubmit
641 script, or subdirectories thereof.
642 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000643 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000644 if len(dir_with_slash) == 1:
645 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000646
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000647 return filter(
648 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800649 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000650
agable0b65e732016-11-22 09:25:46 -0800651 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000652 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800653 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000654 logging.debug("LocalPaths: %s", paths)
655 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000656
agable0b65e732016-11-22 09:25:46 -0800657 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000658 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800659 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000660
agable0b65e732016-11-22 09:25:46 -0800661 def AffectedTestableFiles(self, include_deletes=None):
662 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000663 in the same directory as the current presubmit script, or subdirectories
664 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000665 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000666 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800667 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000668 " is deprecated and ignored" % str(include_deletes),
669 category=DeprecationWarning,
670 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800671 return filter(lambda x: x.IsTestableFile(),
672 self.AffectedFiles(include_deletes=False))
673
674 def AffectedTextFiles(self, include_deletes=None):
675 """An alias to AffectedTestableFiles for backwards compatibility."""
676 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000677
maruel@chromium.org3410d912009-06-09 20:56:16 +0000678 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
679 """Filters out files that aren't considered "source file".
680
681 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
682 and InputApi.DEFAULT_BLACK_LIST is used respectively.
683
684 The lists will be compiled as regular expression and
685 AffectedFile.LocalPath() needs to pass both list.
686
687 Note: Copy-paste this function to suit your needs or use a lambda function.
688 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000689 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000690 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000691 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000692 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000693 return True
694 return False
695 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
696 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
697
698 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800699 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000700
701 If source_file is None, InputApi.FilterSourceFile() is used.
702 """
703 if not source_file:
704 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800705 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000706
707 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000708 """An iterator over all text lines in "new" version of changed files.
709
710 Only lists lines from new or modified text files in the change that are
711 contained by the directory of the currently executing presubmit script.
712
713 This is useful for doing line-by-line regex checks, like checking for
714 trailing whitespace.
715
716 Yields:
717 a 3 tuple:
718 the AffectedFile instance of the current file;
719 integer line number (1-based); and
720 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000721
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000722 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000723 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000724 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000725 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000726
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000727 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000728 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000729
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000730 Deny reading anything outside the repository.
731 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000732 if isinstance(file_item, AffectedFile):
733 file_item = file_item.AbsoluteLocalPath()
734 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000735 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000736 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000737
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100738 def CreateTemporaryFile(self, **kwargs):
739 """Returns a named temporary file that must be removed with a call to
740 RemoveTemporaryFiles().
741
742 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
743 except for |delete|, which is always set to False.
744
745 Presubmit checks that need to create a temporary file and pass it for
746 reading should use this function instead of NamedTemporaryFile(), as
747 Windows fails to open a file that is already open for writing.
748
749 with input_api.CreateTemporaryFile() as f:
750 f.write('xyz')
751 f.close()
752 input_api.subprocess.check_output(['script-that', '--reads-from',
753 f.name])
754
755
756 Note that callers of CreateTemporaryFile() should not worry about removing
757 any temporary file; this is done transparently by the presubmit handling
758 code.
759 """
760 if 'delete' in kwargs:
761 # Prevent users from passing |delete|; we take care of file deletion
762 # ourselves and this prevents unintuitive error messages when we pass
763 # delete=False and 'delete' is also in kwargs.
764 raise TypeError('CreateTemporaryFile() does not take a "delete" '
765 'argument, file deletion is handled automatically by '
766 'the same presubmit_support code that creates InputApi '
767 'objects.')
768 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
769 self._named_temporary_files.append(temp_file.name)
770 return temp_file
771
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000772 @property
773 def tbr(self):
774 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400775 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000776
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000777 def RunTests(self, tests_mix, parallel=True):
Edward Lesmesc7d0b342018-03-28 21:19:00 -0400778 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
779 # will run all tests once all PRESUBMIT files are processed.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000780 tests = []
781 msgs = []
782 for t in tests_mix:
Edward Lesmesc7d0b342018-03-28 21:19:00 -0400783 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000784 msgs.append(t)
785 else:
786 assert issubclass(t.message, _PresubmitResult)
787 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000788 if self.verbose:
789 t.info = _PresubmitNotifyResult
Edward Lesmesc7d0b342018-03-28 21:19:00 -0400790 t.kwargs['cwd'] = self.PresubmitLocalPath()
791 self.thread_pool.AddTests(tests, parallel)
792 return msgs
scottmg86099d72016-09-01 09:16:51 -0700793
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000794
nick@chromium.orgff526192013-06-10 19:30:26 +0000795class _DiffCache(object):
796 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000797 def __init__(self, upstream=None):
798 """Stores the upstream revision against which all diffs will be computed."""
799 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000800
801 def GetDiff(self, path, local_root):
802 """Get the diff for a particular path."""
803 raise NotImplementedError()
804
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700805 def GetOldContents(self, path, local_root):
806 """Get the old version for a particular path."""
807 raise NotImplementedError()
808
nick@chromium.orgff526192013-06-10 19:30:26 +0000809
nick@chromium.orgff526192013-06-10 19:30:26 +0000810class _GitDiffCache(_DiffCache):
811 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000812 def __init__(self, upstream):
813 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000814 self._diffs_by_file = None
815
816 def GetDiff(self, path, local_root):
817 if not self._diffs_by_file:
818 # Compute a single diff for all files and parse the output; should
819 # with git this is much faster than computing one diff for each file.
820 diffs = {}
821
822 # Don't specify any filenames below, because there are command line length
823 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000824 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
825 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000826
827 # This regex matches the path twice, separated by a space. Note that
828 # filename itself may contain spaces.
829 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
830 current_diff = []
831 keep_line_endings = True
832 for x in unified_diff.splitlines(keep_line_endings):
833 match = file_marker.match(x)
834 if match:
835 # Marks the start of a new per-file section.
836 diffs[match.group('filename')] = current_diff = [x]
837 elif x.startswith('diff --git'):
838 raise PresubmitFailure('Unexpected diff line: %s' % x)
839 else:
840 current_diff.append(x)
841
842 self._diffs_by_file = dict(
843 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
844
845 if path not in self._diffs_by_file:
846 raise PresubmitFailure(
847 'Unified diff did not contain entry for file %s' % path)
848
849 return self._diffs_by_file[path]
850
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700851 def GetOldContents(self, path, local_root):
852 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
853
nick@chromium.orgff526192013-06-10 19:30:26 +0000854
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000855class AffectedFile(object):
856 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000857
858 DIFF_CACHE = _DiffCache
859
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000860 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800861 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000862 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000863 self._path = path
864 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000865 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000866 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000867 self._cached_changed_contents = None
868 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000869 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700870 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000872 def LocalPath(self):
873 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400874
875 This should be used for error messages but not for accessing files,
876 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
877 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000878 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000879 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000880
881 def AbsoluteLocalPath(self):
882 """Returns the absolute path of this file on the local disk.
883 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000884 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000885
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000886 def Action(self):
887 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000888 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000889
agable0b65e732016-11-22 09:25:46 -0800890 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000891 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000892
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000893 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000894 raise NotImplementedError() # Implement when needed
895
agable0b65e732016-11-22 09:25:46 -0800896 def IsTextFile(self):
897 """An alias to IsTestableFile for backwards compatibility."""
898 return self.IsTestableFile()
899
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700900 def OldContents(self):
901 """Returns an iterator over the lines in the old version of file.
902
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700903 The old version is the file before any modifications in the user's
904 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700905
906 Contents will be empty if the file is a directory or does not exist.
907 Note: The carriage returns (LF or CR) are stripped off.
908 """
909 return self._diff_cache.GetOldContents(self.LocalPath(),
910 self._local_root).splitlines()
911
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000912 def NewContents(self):
913 """Returns an iterator over the lines in the new version of file.
914
915 The new version is the file in the user's workspace, i.e. the "right hand
916 side".
917
918 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000919 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000920 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000921 if self._cached_new_contents is None:
922 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800923 try:
924 self._cached_new_contents = gclient_utils.FileRead(
925 self.AbsoluteLocalPath(), 'rU').splitlines()
926 except IOError:
927 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000928 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000929
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000930 def ChangedContents(self):
931 """Returns a list of tuples (line number, line text) of all new lines.
932
933 This relies on the scm diff output describing each changed code section
934 with a line of the form
935
936 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
937 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000938 if self._cached_changed_contents is not None:
939 return self._cached_changed_contents[:]
940 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000941 line_num = 0
942
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000943 for line in self.GenerateScmDiff().splitlines():
944 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
945 if m:
946 line_num = int(m.groups(1)[0])
947 continue
948 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000949 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000950 if not line.startswith('-'):
951 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000952 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000953
maruel@chromium.org5de13972009-06-10 18:16:06 +0000954 def __str__(self):
955 return self.LocalPath()
956
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000957 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000958 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000959
maruel@chromium.org58407af2011-04-12 23:15:57 +0000960
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000961class GitAffectedFile(AffectedFile):
962 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000963 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800964 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000965
nick@chromium.orgff526192013-06-10 19:30:26 +0000966 DIFF_CACHE = _GitDiffCache
967
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000968 def __init__(self, *args, **kwargs):
969 AffectedFile.__init__(self, *args, **kwargs)
970 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800971 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000972
agable0b65e732016-11-22 09:25:46 -0800973 def IsTestableFile(self):
974 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000975 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800976 # A deleted file is not testable.
977 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000978 else:
agable0b65e732016-11-22 09:25:46 -0800979 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
980 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000981
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000982
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000983class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000984 """Describe a change.
985
986 Used directly by the presubmit scripts to query the current change being
987 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000988
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000989 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000990 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000991 self.KEY: equivalent to tags['KEY']
992 """
993
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000994 _AFFECTED_FILES = AffectedFile
995
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000996 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000997 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000998 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000999 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000
maruel@chromium.org58407af2011-04-12 23:15:57 +00001001 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001002 self, name, description, local_root, files, issue, patchset, author,
1003 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001004 if files is None:
1005 files = []
1006 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +00001007 # Convert root into an absolute path.
1008 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001009 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001010 self.issue = issue
1011 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +00001012 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001013
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001014 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001015 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001016 self._description_without_tags = ''
1017 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001018
maruel@chromium.orge085d812011-10-10 19:49:15 +00001019 assert all(
1020 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1021
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001022 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001023 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001024 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1025 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001026 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001027
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001028 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001029 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001030 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001031
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001032 def DescriptionText(self):
1033 """Returns the user-entered changelist description, minus tags.
1034
1035 Any line in the user-provided description starting with e.g. "FOO="
1036 (whitespace permitted before and around) is considered a tag line. Such
1037 lines are stripped out of the description this function returns.
1038 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001039 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001040
1041 def FullDescriptionText(self):
1042 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001043 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001044
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001045 def SetDescriptionText(self, description):
1046 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001047
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001048 Also updates the list of tags."""
1049 self._full_description = description
1050
1051 # From the description text, build up a dictionary of key/value pairs
1052 # plus the description minus all key/value or "tag" lines.
1053 description_without_tags = []
1054 self.tags = {}
1055 for line in self._full_description.splitlines():
1056 m = self.TAG_LINE_RE.match(line)
1057 if m:
1058 self.tags[m.group('key')] = m.group('value')
1059 else:
1060 description_without_tags.append(line)
1061
1062 # Change back to text and remove whitespace at end.
1063 self._description_without_tags = (
1064 '\n'.join(description_without_tags).rstrip())
1065
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001066 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001067 """Returns the repository (checkout) root directory for this change,
1068 as an absolute path.
1069 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001070 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001071
1072 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001073 """Return tags directly as attributes on the object."""
1074 if not re.match(r"^[A-Z_]*$", attr):
1075 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001076 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001077
Aaron Gablefc03e672017-05-15 14:09:42 -07001078 def BugsFromDescription(self):
1079 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001080 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
1081 footers = git_footers.parse_footers(self._full_description).get('Bug', [])
1082 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001083
1084 def ReviewersFromDescription(self):
1085 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001086 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1087 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1088 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001089
1090 def TBRsFromDescription(self):
1091 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001092 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1093 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1094 # determined by self-CR+1s.
1095 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1096 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001097
1098 # TODO(agable): Delete these once we're sure they're unused.
1099 @property
1100 def BUG(self):
1101 return ','.join(self.BugsFromDescription())
1102 @property
1103 def R(self):
1104 return ','.join(self.ReviewersFromDescription())
1105 @property
1106 def TBR(self):
1107 return ','.join(self.TBRsFromDescription())
1108
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001109 def AllFiles(self, root=None):
1110 """List all files under source control in the repo."""
1111 raise NotImplementedError()
1112
agable0b65e732016-11-22 09:25:46 -08001113 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001114 """Returns a list of AffectedFile instances for all files in the change.
1115
1116 Args:
1117 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001118 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001119
1120 Returns:
1121 [AffectedFile(path, action), AffectedFile(path, action)]
1122 """
agable0b65e732016-11-22 09:25:46 -08001123 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +00001124
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001125 if include_deletes:
1126 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -07001127 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001128
agable0b65e732016-11-22 09:25:46 -08001129 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001130 """Return a list of the existing text files in a change."""
1131 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001132 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001133 " is deprecated and ignored" % str(include_deletes),
1134 category=DeprecationWarning,
1135 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -08001136 return filter(lambda x: x.IsTestableFile(),
1137 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001138
agable0b65e732016-11-22 09:25:46 -08001139 def AffectedTextFiles(self, include_deletes=None):
1140 """An alias to AffectedTestableFiles for backwards compatibility."""
1141 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001142
agable0b65e732016-11-22 09:25:46 -08001143 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001144 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001145 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001146
agable0b65e732016-11-22 09:25:46 -08001147 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001148 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001149 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001150
1151 def RightHandSideLines(self):
1152 """An iterator over all text lines in "new" version of changed files.
1153
1154 Lists lines from new or modified text files in the change.
1155
1156 This is useful for doing line-by-line regex checks, like checking for
1157 trailing whitespace.
1158
1159 Yields:
1160 a 3 tuple:
1161 the AffectedFile instance of the current file;
1162 integer line number (1-based); and
1163 the contents of the line as a string.
1164 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001165 return _RightHandSideLinesImpl(
1166 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001167 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001168
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001169 def OriginalOwnersFiles(self):
1170 """A map from path names of affected OWNERS files to their old content."""
1171 def owners_file_filter(f):
1172 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1173 files = self.AffectedFiles(file_filter=owners_file_filter)
1174 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1175
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001176
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001177class GitChange(Change):
1178 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001179 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001180
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001181 def AllFiles(self, root=None):
1182 """List all files under source control in the repo."""
1183 root = root or self.RepositoryRoot()
1184 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001185 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1186 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001187
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001188
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001189def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001190 """Finds all presubmit files that apply to a given set of source files.
1191
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001192 If inherit-review-settings-ok is present right under root, looks for
1193 PRESUBMIT.py in directories enclosing root.
1194
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001195 Args:
1196 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001197 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001198
1199 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001200 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001201 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001202 files = [normpath(os.path.join(root, f)) for f in files]
1203
1204 # List all the individual directories containing files.
1205 directories = set([os.path.dirname(f) for f in files])
1206
1207 # Ignore root if inherit-review-settings-ok is present.
1208 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1209 root = None
1210
1211 # Collect all unique directories that may contain PRESUBMIT.py.
1212 candidates = set()
1213 for directory in directories:
1214 while True:
1215 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001216 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001217 candidates.add(directory)
1218 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001219 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001220 parent_dir = os.path.dirname(directory)
1221 if parent_dir == directory:
1222 # We hit the system root directory.
1223 break
1224 directory = parent_dir
1225
1226 # Look for PRESUBMIT.py in all candidate directories.
1227 results = []
1228 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001229 try:
1230 for f in os.listdir(directory):
1231 p = os.path.join(directory, f)
1232 if os.path.isfile(p) and re.match(
1233 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1234 results.append(p)
1235 except OSError:
1236 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001237
tobiasjs2836bcf2016-08-16 04:08:16 -07001238 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001239 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001240
1241
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001242class GetTryMastersExecuter(object):
1243 @staticmethod
1244 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1245 """Executes GetPreferredTryMasters() from a single presubmit script.
1246
1247 Args:
1248 script_text: The text of the presubmit script.
1249 presubmit_path: Project script to run.
1250 project: Project name to pass to presubmit script for bot selection.
1251
1252 Return:
1253 A map of try masters to map of builders to set of tests.
1254 """
1255 context = {}
1256 try:
1257 exec script_text in context
1258 except Exception, e:
1259 raise PresubmitFailure('"%s" had an exception.\n%s'
1260 % (presubmit_path, e))
1261
1262 function_name = 'GetPreferredTryMasters'
1263 if function_name not in context:
1264 return {}
1265 get_preferred_try_masters = context[function_name]
1266 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1267 raise PresubmitFailure(
1268 'Expected function "GetPreferredTryMasters" to take two arguments.')
1269 return get_preferred_try_masters(project, change)
1270
1271
rmistry@google.com5626a922015-02-26 14:03:30 +00001272class GetPostUploadExecuter(object):
1273 @staticmethod
1274 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1275 """Executes PostUploadHook() from a single presubmit script.
1276
1277 Args:
1278 script_text: The text of the presubmit script.
1279 presubmit_path: Project script to run.
1280 cl: The Changelist object.
1281 change: The Change object.
1282
1283 Return:
1284 A list of results objects.
1285 """
1286 context = {}
1287 try:
1288 exec script_text in context
1289 except Exception, e:
1290 raise PresubmitFailure('"%s" had an exception.\n%s'
1291 % (presubmit_path, e))
1292
1293 function_name = 'PostUploadHook'
1294 if function_name not in context:
1295 return {}
1296 post_upload_hook = context[function_name]
1297 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1298 raise PresubmitFailure(
1299 'Expected function "PostUploadHook" to take three arguments.')
1300 return post_upload_hook(cl, change, OutputApi(False))
1301
1302
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001303def _MergeMasters(masters1, masters2):
1304 """Merges two master maps. Merges also the tests of each builder."""
1305 result = {}
1306 for (master, builders) in itertools.chain(masters1.iteritems(),
1307 masters2.iteritems()):
1308 new_builders = result.setdefault(master, {})
1309 for (builder, tests) in builders.iteritems():
1310 new_builders.setdefault(builder, set([])).update(tests)
1311 return result
1312
1313
1314def DoGetTryMasters(change,
1315 changed_files,
1316 repository_root,
1317 default_presubmit,
1318 project,
1319 verbose,
1320 output_stream):
1321 """Get the list of try masters from the presubmit scripts.
1322
1323 Args:
1324 changed_files: List of modified files.
1325 repository_root: The repository root.
1326 default_presubmit: A default presubmit script to execute in any case.
1327 project: Optional name of a project used in selecting trybots.
1328 verbose: Prints debug info.
1329 output_stream: A stream to write debug output to.
1330
1331 Return:
1332 Map of try masters to map of builders to set of tests.
1333 """
1334 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1335 if not presubmit_files and verbose:
1336 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1337 results = {}
1338 executer = GetTryMastersExecuter()
1339
1340 if default_presubmit:
1341 if verbose:
1342 output_stream.write("Running default presubmit script.\n")
1343 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1344 results = _MergeMasters(results, executer.ExecPresubmitScript(
1345 default_presubmit, fake_path, project, change))
1346 for filename in presubmit_files:
1347 filename = os.path.abspath(filename)
1348 if verbose:
1349 output_stream.write("Running %s\n" % filename)
1350 # Accept CRLF presubmit script.
1351 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1352 results = _MergeMasters(results, executer.ExecPresubmitScript(
1353 presubmit_script, filename, project, change))
1354
1355 # Make sets to lists again for later JSON serialization.
1356 for builders in results.itervalues():
1357 for builder in builders:
1358 builders[builder] = list(builders[builder])
1359
1360 if results and verbose:
1361 output_stream.write('%s\n' % str(results))
1362 return results
1363
1364
rmistry@google.com5626a922015-02-26 14:03:30 +00001365def DoPostUploadExecuter(change,
1366 cl,
1367 repository_root,
1368 verbose,
1369 output_stream):
1370 """Execute the post upload hook.
1371
1372 Args:
1373 change: The Change object.
1374 cl: The Changelist object.
1375 repository_root: The repository root.
1376 verbose: Prints debug info.
1377 output_stream: A stream to write debug output to.
1378 """
1379 presubmit_files = ListRelevantPresubmitFiles(
1380 change.LocalPaths(), repository_root)
1381 if not presubmit_files and verbose:
1382 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1383 results = []
1384 executer = GetPostUploadExecuter()
1385 # The root presubmit file should be executed after the ones in subdirectories.
1386 # i.e. the specific post upload hooks should run before the general ones.
1387 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1388 presubmit_files.reverse()
1389
1390 for filename in presubmit_files:
1391 filename = os.path.abspath(filename)
1392 if verbose:
1393 output_stream.write("Running %s\n" % filename)
1394 # Accept CRLF presubmit script.
1395 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1396 results.extend(executer.ExecPresubmitScript(
1397 presubmit_script, filename, cl, change))
1398 output_stream.write('\n')
1399 if results:
1400 output_stream.write('** Post Upload Hook Messages **\n')
1401 for result in results:
1402 result.handle(output_stream)
1403 output_stream.write('\n')
1404
1405 return results
1406
1407
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001408class PresubmitExecuter(object):
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001409 def __init__(self, change, committing, rietveld_obj, verbose,
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001410 gerrit_obj=None, dry_run=None, thread_pool=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001411 """
1412 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001413 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001414 committing: True if 'git cl land' is running, False if 'git cl upload' is.
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001415 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001416 gerrit_obj: provides basic Gerrit codereview functionality.
1417 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001418 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001419 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001420 self.committing = committing
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001421 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001422 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001423 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001424 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001425 self.more_cc = []
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001426 self.thread_pool = thread_pool
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001427
1428 def ExecPresubmitScript(self, script_text, presubmit_path):
1429 """Executes a single presubmit script.
1430
1431 Args:
1432 script_text: The text of the presubmit script.
1433 presubmit_path: The path to the presubmit file (this will be reported via
1434 input_api.PresubmitLocalPath()).
1435
1436 Return:
1437 A list of result objects, empty if no problems.
1438 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001439
chase@chromium.org8e416c82009-10-06 04:30:44 +00001440 # Change to the presubmit file's directory to support local imports.
1441 main_path = os.getcwd()
1442 os.chdir(os.path.dirname(presubmit_path))
1443
1444 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001445 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001446 self.rietveld, self.verbose,
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001447 gerrit_obj=self.gerrit, dry_run=self.dry_run,
1448 thread_pool=self.thread_pool)
Daniel Cheng7227d212017-11-17 08:12:37 -08001449 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001450 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001451 try:
1452 exec script_text in context
1453 except Exception, e:
1454 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001455
1456 # These function names must change if we make substantial changes to
1457 # the presubmit API that are not backwards compatible.
1458 if self.committing:
1459 function_name = 'CheckChangeOnCommit'
1460 else:
1461 function_name = 'CheckChangeOnUpload'
1462 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001463 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001464 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001465 logging.debug('Running %s in %s', function_name, presubmit_path)
1466 result = eval(function_name + '(*__args)', context)
1467 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001468 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001469 finally:
1470 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001471 if not (isinstance(result, types.TupleType) or
1472 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001473 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001474 'Presubmit functions must return a tuple or list')
1475 for item in result:
1476 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001477 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001478 'All presubmit results must be of types derived from '
1479 'output_api.PresubmitResult')
1480 else:
1481 result = () # no error since the script doesn't care about current event.
1482
chase@chromium.org8e416c82009-10-06 04:30:44 +00001483 # Return the process to the original working directory.
1484 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001485 return result
1486
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001487def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001488 committing,
1489 verbose,
1490 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001491 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001492 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001493 may_prompt,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001494 rietveld_obj,
1495 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001496 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001497 """Runs all presubmit checks that apply to the files in the change.
1498
1499 This finds all PRESUBMIT.py files in directories enclosing the files in the
1500 change (up to the repository root) and calls the relevant entrypoint function
1501 depending on whether the change is being committed or uploaded.
1502
1503 Prints errors, warnings and notifications. Prompts the user for warnings
1504 when needed.
1505
1506 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001507 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001508 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001509 verbose: Prints debug info.
1510 output_stream: A stream to write output from presubmit tests to.
1511 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001512 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001513 may_prompt: Enable (y/n) questions on warning or error. If False,
1514 any questions are answered with yes by default.
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001515 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001516 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001517 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001518
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001519 Warning:
1520 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1521 SHOULD be sys.stdin.
1522
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001523 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001524 A PresubmitOutput object. Use output.should_continue() to figure out
1525 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001526 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001527 old_environ = os.environ
1528 try:
1529 # Make sure python subprocesses won't generate .pyc files.
1530 os.environ = os.environ.copy()
1531 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001532
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001533 output = PresubmitOutput(input_stream, output_stream)
1534 if committing:
1535 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001536 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001537 output.write("Running presubmit upload checks ...\n")
1538 start_time = time.time()
1539 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001540 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001541 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001542 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001543 results = []
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001544 thread_pool = ThreadPool()
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001545 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001546 gerrit_obj, dry_run, thread_pool)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001547 if default_presubmit:
1548 if verbose:
1549 output.write("Running default presubmit script.\n")
1550 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1551 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1552 for filename in presubmit_files:
1553 filename = os.path.abspath(filename)
1554 if verbose:
1555 output.write("Running %s\n" % filename)
1556 # Accept CRLF presubmit script.
1557 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1558 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001559
Edward Lesmesc7d0b342018-03-28 21:19:00 -04001560 results += thread_pool.RunAsync()
1561
Daniel Cheng7227d212017-11-17 08:12:37 -08001562 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001563 errors = []
1564 notifications = []
1565 warnings = []
1566 for result in results:
1567 if result.fatal:
1568 errors.append(result)
1569 elif result.should_prompt:
1570 warnings.append(result)
1571 else:
1572 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001573
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001574 output.write('\n')
1575 for name, items in (('Messages', notifications),
1576 ('Warnings', warnings),
1577 ('ERRORS', errors)):
1578 if items:
1579 output.write('** Presubmit %s **\n' % name)
1580 for item in items:
1581 item.handle(output)
1582 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001583
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001584 total_time = time.time() - start_time
1585 if total_time > 1.0:
1586 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001587
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001588 if errors:
1589 output.fail()
1590 elif warnings:
1591 output.write('There were presubmit warnings. ')
1592 if may_prompt:
1593 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1594 else:
1595 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001596
1597 global _ASKED_FOR_FEEDBACK
1598 # Ask for feedback one time out of 5.
1599 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001600 output.write(
1601 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1602 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1603 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001604 _ASKED_FOR_FEEDBACK = True
1605 return output
1606 finally:
1607 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001608
1609
1610def ScanSubDirs(mask, recursive):
1611 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001612 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001613
1614 results = []
1615 for root, dirs, files in os.walk('.'):
1616 if '.svn' in dirs:
1617 dirs.remove('.svn')
1618 if '.git' in dirs:
1619 dirs.remove('.git')
1620 for name in files:
1621 if fnmatch.fnmatch(name, mask):
1622 results.append(os.path.join(root, name))
1623 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001624
1625
1626def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001627 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001628 files = []
1629 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001630 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001631 return files
1632
1633
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001634def load_files(options, args):
1635 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001636 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001637 if args:
1638 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001639 change_scm = scm.determine_scm(options.root)
1640 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001641 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001642 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001643 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001644 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001645 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001646 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001647 if not files:
1648 return None, None
1649 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001650 return change_class, files
1651
1652
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001653@contextlib.contextmanager
1654def canned_check_filter(method_names):
1655 filtered = {}
1656 try:
1657 for method_name in method_names:
1658 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001659 logging.warn('Skipping unknown "canned" check %s' % method_name)
1660 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001661 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1662 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1663 yield
1664 finally:
1665 for name, method in filtered.iteritems():
1666 setattr(presubmit_canned_checks, name, method)
1667
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001668
sbc@chromium.org013731e2015-02-26 18:28:43 +00001669def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001670 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001671 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001672 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001673 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001674 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1675 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001676 parser.add_option("-r", "--recursive", action="store_true",
1677 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001678 parser.add_option("-v", "--verbose", action="count", default=0,
1679 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001680 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001681 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001682 parser.add_option("--description", default='')
1683 parser.add_option("--issue", type='int', default=0)
1684 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001685 parser.add_option("--root", default=os.getcwd(),
1686 help="Search for PRESUBMIT.py up to this directory. "
1687 "If inherit-review-settings-ok is present in this "
1688 "directory, parent directories up to the root file "
1689 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001690 parser.add_option("--upstream",
1691 help="Git only: the base ref or upstream branch against "
1692 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001693 parser.add_option("--default_presubmit")
1694 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001695 parser.add_option("--skip_canned", action='append', default=[],
1696 help="A list of checks to skip which appear in "
1697 "presubmit_canned_checks. Can be provided multiple times "
1698 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001699 parser.add_option("--dry_run", action='store_true',
1700 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001701 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001702 parser.add_option("--gerrit_fetch", action='store_true',
1703 help=optparse.SUPPRESS_HELP)
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001704 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1705 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
1706 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1707 help=optparse.SUPPRESS_HELP)
1708 # These are for OAuth2 authentication for bots. See also apply_issue.py
1709 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1710 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001711
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001712 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001713 options, args = parser.parse_args(argv)
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001714 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001715
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001716 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001717 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001718 elif options.verbose:
1719 logging.basicConfig(level=logging.INFO)
1720 else:
1721 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001722
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001723 if (any((options.rietveld_url, options.rietveld_email_file,
1724 options.rietveld_fetch, options.rietveld_private_key_file))
1725 and any((options.gerrit_url, options.gerrit_fetch))):
1726 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1727 'allowed')
1728
1729 if options.rietveld_email and options.rietveld_email_file:
1730 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1731 "can be passed to this program.")
1732 if options.rietveld_email_file:
1733 with open(options.rietveld_email_file, "rb") as f:
1734 options.rietveld_email = f.read().strip()
1735
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001736 change_class, files = load_files(options, args)
1737 if not change_class:
1738 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001739 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001740
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001741 rietveld_obj, gerrit_obj = None, None
1742
1743 if options.rietveld_url:
1744 # The empty password is permitted: '' is not None.
1745 if options.rietveld_private_key_file:
1746 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1747 options.rietveld_url,
1748 options.rietveld_email,
1749 options.rietveld_private_key_file)
1750 else:
1751 rietveld_obj = rietveld.CachingRietveld(
1752 options.rietveld_url,
1753 auth_config,
1754 options.rietveld_email)
1755 if options.rietveld_fetch:
1756 assert options.issue
1757 props = rietveld_obj.get_issue_properties(options.issue, False)
1758 options.author = props['owner_email']
1759 options.description = props['description']
1760 logging.info('Got author: "%s"', options.author)
1761 logging.info('Got description: """\n%s\n"""', options.description)
1762
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001763 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001764 assert options.issue and options.patchset
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001765 rietveld_obj = None
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001766 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1767 options.author = gerrit_obj.GetChangeOwner(options.issue)
1768 options.description = gerrit_obj.GetChangeDescription(options.issue,
1769 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001770 logging.info('Got author: "%s"', options.author)
1771 logging.info('Got description: """\n%s\n"""', options.description)
1772
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001773 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001774 with canned_check_filter(options.skip_canned):
1775 results = DoPresubmitChecks(
1776 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001777 options.description,
1778 options.root,
1779 files,
1780 options.issue,
1781 options.patchset,
1782 options.author,
1783 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001784 options.commit,
1785 options.verbose,
1786 sys.stdout,
1787 sys.stdin,
1788 options.default_presubmit,
1789 options.may_prompt,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001790 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001791 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001792 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001793 return not results.should_continue()
1794 except PresubmitFailure, e:
1795 print >> sys.stderr, e
1796 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001797 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001798
1799
1800if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001801 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001802 try:
1803 sys.exit(main())
1804 except KeyboardInterrupt:
1805 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001806 sys.exit(2)