blob: d80985c1f0d9a96c04e24bbb19257d7e00bf0e3a [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.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033import sys # Parts exposed through API.
34import tempfile # Exposed through the API.
jam@chromium.org2a891dc2009-08-20 20:33:37 +000035import time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000036import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000037import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000038import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000039import urllib2 # Exposed through the API.
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000040import urlparse
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000041from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000042
43# Local imports.
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +000044import auth
maruel@chromium.org35625c72011-03-23 17:34:02 +000045import fix_encoding
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000046import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070047import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000048import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000049import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020050import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000051import presubmit_canned_checks
maruel@chromium.org239f4112011-06-03 20:08:23 +000052import rietveld
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000053import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000054import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000055
56
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000057# Ask for feedback only once in program lifetime.
58_ASKED_FOR_FEEDBACK = False
59
60
maruel@chromium.org899e1c12011-04-07 17:03:18 +000061class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062 pass
63
64
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000065class CommandData(object):
66 def __init__(self, name, cmd, kwargs, message):
67 self.name = name
68 self.cmd = cmd
69 self.kwargs = kwargs
70 self.message = message
71 self.info = None
72
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000073
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000074def normpath(path):
75 '''Version of os.path.normpath that also changes backward slashes to
76 forward slashes when not running on Windows.
77 '''
78 # This is safe to always do because the Windows version of os.path.normpath
79 # will replace forward slashes with backward slashes.
80 path = path.replace(os.sep, '/')
81 return os.path.normpath(path)
82
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000083
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000084def _RightHandSideLinesImpl(affected_files):
85 """Implements RightHandSideLines for InputApi and GclChange."""
86 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000087 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000088 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000089 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000090
91
dpranke@chromium.org5ac21012011-03-16 02:58:25 +000092class PresubmitOutput(object):
93 def __init__(self, input_stream=None, output_stream=None):
94 self.input_stream = input_stream
95 self.output_stream = output_stream
96 self.reviewers = []
97 self.written_output = []
98 self.error_count = 0
99
100 def prompt_yes_no(self, prompt_string):
101 self.write(prompt_string)
102 if self.input_stream:
103 response = self.input_stream.readline().strip().lower()
104 if response not in ('y', 'yes'):
105 self.fail()
106 else:
107 self.fail()
108
109 def fail(self):
110 self.error_count += 1
111
112 def should_continue(self):
113 return not self.error_count
114
115 def write(self, s):
116 self.written_output.append(s)
117 if self.output_stream:
118 self.output_stream.write(s)
119
120 def getvalue(self):
121 return ''.join(self.written_output)
122
123
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000124# Top level object so multiprocessing can pickle
125# Public access through OutputApi object.
126class _PresubmitResult(object):
127 """Base class for result objects."""
128 fatal = False
129 should_prompt = False
130
131 def __init__(self, message, items=None, long_text=''):
132 """
133 message: A short one-line message to indicate errors.
134 items: A list of short strings to indicate where errors occurred.
135 long_text: multi-line text output, e.g. from another tool
136 """
137 self._message = message
138 self._items = items or []
139 if items:
140 self._items = items
141 self._long_text = long_text.rstrip()
142
143 def handle(self, output):
144 output.write(self._message)
145 output.write('\n')
146 for index, item in enumerate(self._items):
147 output.write(' ')
148 # Write separately in case it's unicode.
149 output.write(str(item))
150 if index < len(self._items) - 1:
151 output.write(' \\')
152 output.write('\n')
153 if self._long_text:
154 output.write('\n***************\n')
155 # Write separately in case it's unicode.
156 output.write(self._long_text)
157 output.write('\n***************\n')
158 if self.fatal:
159 output.fail()
160
161
162# Top level object so multiprocessing can pickle
163# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000164class _PresubmitError(_PresubmitResult):
165 """A hard presubmit error."""
166 fatal = True
167
168
169# Top level object so multiprocessing can pickle
170# Public access through OutputApi object.
171class _PresubmitPromptWarning(_PresubmitResult):
172 """An warning that prompts the user if they want to continue."""
173 should_prompt = True
174
175
176# Top level object so multiprocessing can pickle
177# Public access through OutputApi object.
178class _PresubmitNotifyResult(_PresubmitResult):
179 """Just print something to the screen -- but it's not even a warning."""
180 pass
181
182
183# Top level object so multiprocessing can pickle
184# Public access through OutputApi object.
185class _MailTextResult(_PresubmitResult):
186 """A warning that should be included in the review request email."""
187 def __init__(self, *args, **kwargs):
188 super(_MailTextResult, self).__init__()
189 raise NotImplementedError()
190
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000191class GerritAccessor(object):
192 """Limited Gerrit functionality for canned presubmit checks to work.
193
194 To avoid excessive Gerrit calls, caches the results.
195 """
196
197 def __init__(self, host):
198 self.host = host
199 self.cache = {}
200
201 def _FetchChangeDetail(self, issue):
202 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100203 try:
204 return gerrit_util.GetChangeDetail(
205 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700206 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100207 except gerrit_util.GerritError as e:
208 if e.http_status == 404:
209 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
210 'no credentials to fetch issue details' % issue)
211 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000212
213 def GetChangeInfo(self, issue):
214 """Returns labels and all revisions (patchsets) for this issue.
215
216 The result is a dictionary according to Gerrit REST Api.
217 https://gerrit-review.googlesource.com/Documentation/rest-api.html
218
219 However, API isn't very clear what's inside, so see tests for example.
220 """
221 assert issue
222 cache_key = int(issue)
223 if cache_key not in self.cache:
224 self.cache[cache_key] = self._FetchChangeDetail(issue)
225 return self.cache[cache_key]
226
227 def GetChangeDescription(self, issue, patchset=None):
228 """If patchset is none, fetches current patchset."""
229 info = self.GetChangeInfo(issue)
230 # info is a reference to cache. We'll modify it here adding description to
231 # it to the right patchset, if it is not yet there.
232
233 # Find revision info for the patchset we want.
234 if patchset is not None:
235 for rev, rev_info in info['revisions'].iteritems():
236 if str(rev_info['_number']) == str(patchset):
237 break
238 else:
239 raise Exception('patchset %s doesn\'t exist in issue %s' % (
240 patchset, issue))
241 else:
242 rev = info['current_revision']
243 rev_info = info['revisions'][rev]
244
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100245 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000246
247 def GetChangeOwner(self, issue):
248 return self.GetChangeInfo(issue)['owner']['email']
249
250 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700251 changeinfo = self.GetChangeInfo(issue)
252 if approving_only:
253 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
254 values = labelinfo.get('values', {}).keys()
255 try:
256 max_value = max(int(v) for v in values)
257 reviewers = [r for r in labelinfo.get('all', [])
258 if r.get('value', 0) == max_value]
259 except ValueError: # values is the empty list
260 reviewers = []
261 else:
262 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
263 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000264
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000265
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000266class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000267 """An instance of OutputApi gets passed to presubmit scripts so that they
268 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000269 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000270 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000271 PresubmitError = _PresubmitError
272 PresubmitPromptWarning = _PresubmitPromptWarning
273 PresubmitNotifyResult = _PresubmitNotifyResult
274 MailTextResult = _MailTextResult
275
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000276 def __init__(self, is_committing):
277 self.is_committing = is_committing
278
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000279 def PresubmitPromptOrNotify(self, *args, **kwargs):
280 """Warn the user when uploading, but only notify if committing."""
281 if self.is_committing:
282 return self.PresubmitNotifyResult(*args, **kwargs)
283 return self.PresubmitPromptWarning(*args, **kwargs)
284
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800285 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
286 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
287
288 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
289 keeping it alphabetically sorted. Returns the results that should be
290 returned from the PostUploadHook.
291
292 Args:
293 cl: The git_cl.Changelist object.
294 bots_to_include: A list of strings of bots to include, in the form
295 "master:slave".
296 message: A message to be printed in the case that
297 CQ_INCLUDE_TRYBOTS was updated.
298 """
299 description = cl.GetDescription(force=True)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700300 include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)$', re.M | re.I)
301
302 prior_bots = []
303 if cl.IsGerrit():
304 trybot_footers = git_footers.parse_footers(description).get(
305 git_footers.normalize_name('Cq-Include-Trybots'), [])
306 for f in trybot_footers:
307 prior_bots += [b.strip() for b in f.split(';') if b.strip()]
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800308 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700309 trybot_tags = include_re.finditer(description)
310 for t in trybot_tags:
311 prior_bots += [b.strip() for b in t.group(1).split(';') if b.strip()]
312
313 if set(prior_bots) >= set(bots_to_include):
314 return []
315 all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include)))
316
317 if cl.IsGerrit():
318 description = git_footers.remove_footer(
319 description, 'Cq-Include-Trybots')
320 description = git_footers.add_footer(
321 description, 'Cq-Include-Trybots', all_bots,
322 before_keys=['Change-Id'])
323 else:
324 new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % all_bots
325 m = include_re.search(description)
326 if m:
327 description = include_re.sub(new_include_trybots, description)
Kenneth Russelldf6e7342017-04-24 17:07:41 -0700328 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700329 description = '%s\n%s\n' % (description, new_include_trybots)
330
331 cl.UpdateDescription(description, force=True)
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800332 return [self.PresubmitNotifyResult(message)]
333
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000334
335class InputApi(object):
336 """An instance of this object is passed to presubmit scripts so they can
337 know stuff about the change they're looking at.
338 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000339 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800340 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000341
maruel@chromium.org3410d912009-06-09 20:56:16 +0000342 # File extensions that are considered source files from a style guide
343 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000344 #
345 # Files without an extension aren't included in the list. If you want to
346 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
347 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000348 DEFAULT_WHITE_LIST = (
349 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000350 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
351 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000352 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000353 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000354 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000355 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000356 )
357
358 # Path regexp that should be excluded from being considered containing source
359 # files. Don't modify this list from a presubmit script!
360 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000361 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000362 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000363 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
364 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000365 # Output directories (just in case)
366 r".*\bDebug[\\\/].*",
367 r".*\bRelease[\\\/].*",
368 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000369 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000370 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000371 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000372 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000373 r"(|.*[\\\/])\.git[\\\/].*",
374 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000375 # There is no point in processing a patch file.
376 r".+\.diff$",
377 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000378 )
379
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000380 def __init__(self, change, presubmit_path, is_committing,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000381 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000382 """Builds an InputApi object.
383
384 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000385 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000386 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000387 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000388 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000389 gerrit_obj: provides basic Gerrit codereview functionality.
390 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000391 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000392 # Version number of the presubmit_support script.
393 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000394 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000395 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000396 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000397 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000398 self.dry_run = dry_run
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000399 # TBD
400 self.host_url = 'http://codereview.chromium.org'
401 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000402 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000403
404 # We expose various modules and functions as attributes of the input_api
405 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900406 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000407 self.basename = os.path.basename
408 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000409 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000410 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700411 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000412 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000413 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000414 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000415 self.os_listdir = os.listdir
416 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000417 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000418 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 self.pickle = pickle
420 self.marshal = marshal
421 self.re = re
422 self.subprocess = subprocess
423 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000424 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000425 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000426 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000427 self.urllib2 = urllib2
428
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000429 # To easily fork python.
430 self.python_executable = sys.executable
431 self.environ = os.environ
432
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000433 # InputApi.platform is the platform you're currently running on.
434 self.platform = sys.platform
435
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000436 self.cpu_count = multiprocessing.cpu_count()
437
Aaron Gable5254da12017-09-06 21:05:39 +0000438 # this is done here because in RunTests, the current working directory has
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000439 # changed, which causes Pool() to explode fantastically when run on windows
440 # (because it tries to load the __main__ module, which imports lots of
441 # things relative to the current working directory).
Aaron Gable5254da12017-09-06 21:05:39 +0000442 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000443
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000444 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000445 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000446
447 # We carry the canned checks so presubmit scripts can easily use them.
448 self.canned_checks = presubmit_canned_checks
449
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100450 # Temporary files we must manually remove at the end of a run.
451 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200452
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000453 # TODO(dpranke): figure out a list of all approved owners for a repo
454 # in order to be able to handle wildcard OWNERS files?
455 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200456 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200457 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000458 self.verbose = verbose
Dan Jacques94652a32017-10-09 23:18:46 -0400459 self.is_windows = sys.platform == 'win32'
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000460 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000461
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000462 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000463 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000464 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800465 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000466 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000467 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000468 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
469 for (a, b, header) in cpplint._re_pattern_templates
470 ]
471
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000472 def PresubmitLocalPath(self):
473 """Returns the local path of the presubmit script currently being run.
474
475 This is useful if you don't want to hard-code absolute paths in the
476 presubmit script. For example, It can be used to find another file
477 relative to the PRESUBMIT.py script, so the whole tree can be branched and
478 the presubmit script still works, without editing its content.
479 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000480 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000481
agable0b65e732016-11-22 09:25:46 -0800482 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000483 """Same as input_api.change.AffectedFiles() except only lists files
484 (and optionally directories) in the same directory as the current presubmit
485 script, or subdirectories thereof.
486 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000487 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000488 if len(dir_with_slash) == 1:
489 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000490
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000491 return filter(
492 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800493 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000494
agable0b65e732016-11-22 09:25:46 -0800495 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000496 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800497 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000498 logging.debug("LocalPaths: %s", paths)
499 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000500
agable0b65e732016-11-22 09:25:46 -0800501 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000502 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800503 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000504
agable0b65e732016-11-22 09:25:46 -0800505 def AffectedTestableFiles(self, include_deletes=None):
506 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000507 in the same directory as the current presubmit script, or subdirectories
508 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000509 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000510 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800511 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000512 " is deprecated and ignored" % str(include_deletes),
513 category=DeprecationWarning,
514 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800515 return filter(lambda x: x.IsTestableFile(),
516 self.AffectedFiles(include_deletes=False))
517
518 def AffectedTextFiles(self, include_deletes=None):
519 """An alias to AffectedTestableFiles for backwards compatibility."""
520 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000521
maruel@chromium.org3410d912009-06-09 20:56:16 +0000522 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
523 """Filters out files that aren't considered "source file".
524
525 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
526 and InputApi.DEFAULT_BLACK_LIST is used respectively.
527
528 The lists will be compiled as regular expression and
529 AffectedFile.LocalPath() needs to pass both list.
530
531 Note: Copy-paste this function to suit your needs or use a lambda function.
532 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000533 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000534 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000535 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000536 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000537 return True
538 return False
539 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
540 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
541
542 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800543 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000544
545 If source_file is None, InputApi.FilterSourceFile() is used.
546 """
547 if not source_file:
548 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800549 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000550
551 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000552 """An iterator over all text lines in "new" version of changed files.
553
554 Only lists lines from new or modified text files in the change that are
555 contained by the directory of the currently executing presubmit script.
556
557 This is useful for doing line-by-line regex checks, like checking for
558 trailing whitespace.
559
560 Yields:
561 a 3 tuple:
562 the AffectedFile instance of the current file;
563 integer line number (1-based); and
564 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000565
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000566 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000568 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000569 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000570
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000571 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000572 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000573
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000574 Deny reading anything outside the repository.
575 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000576 if isinstance(file_item, AffectedFile):
577 file_item = file_item.AbsoluteLocalPath()
578 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000579 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000580 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000581
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100582 def CreateTemporaryFile(self, **kwargs):
583 """Returns a named temporary file that must be removed with a call to
584 RemoveTemporaryFiles().
585
586 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
587 except for |delete|, which is always set to False.
588
589 Presubmit checks that need to create a temporary file and pass it for
590 reading should use this function instead of NamedTemporaryFile(), as
591 Windows fails to open a file that is already open for writing.
592
593 with input_api.CreateTemporaryFile() as f:
594 f.write('xyz')
595 f.close()
596 input_api.subprocess.check_output(['script-that', '--reads-from',
597 f.name])
598
599
600 Note that callers of CreateTemporaryFile() should not worry about removing
601 any temporary file; this is done transparently by the presubmit handling
602 code.
603 """
604 if 'delete' in kwargs:
605 # Prevent users from passing |delete|; we take care of file deletion
606 # ourselves and this prevents unintuitive error messages when we pass
607 # delete=False and 'delete' is also in kwargs.
608 raise TypeError('CreateTemporaryFile() does not take a "delete" '
609 'argument, file deletion is handled automatically by '
610 'the same presubmit_support code that creates InputApi '
611 'objects.')
612 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
613 self._named_temporary_files.append(temp_file.name)
614 return temp_file
615
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000616 @property
617 def tbr(self):
618 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400619 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000620
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000621 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000622 tests = []
623 msgs = []
624 for t in tests_mix:
625 if isinstance(t, OutputApi.PresubmitResult):
626 msgs.append(t)
627 else:
628 assert issubclass(t.message, _PresubmitResult)
629 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000630 if self.verbose:
631 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000632 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000633 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000634 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000635 else:
636 msgs.extend(map(CallCommand, tests))
637 return [m for m in msgs if m]
638
scottmg86099d72016-09-01 09:16:51 -0700639 def ShutdownPool(self):
640 self._run_tests_pool.close()
641 self._run_tests_pool.join()
642 self._run_tests_pool = None
643
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000644
nick@chromium.orgff526192013-06-10 19:30:26 +0000645class _DiffCache(object):
646 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000647 def __init__(self, upstream=None):
648 """Stores the upstream revision against which all diffs will be computed."""
649 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000650
651 def GetDiff(self, path, local_root):
652 """Get the diff for a particular path."""
653 raise NotImplementedError()
654
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700655 def GetOldContents(self, path, local_root):
656 """Get the old version for a particular path."""
657 raise NotImplementedError()
658
nick@chromium.orgff526192013-06-10 19:30:26 +0000659
nick@chromium.orgff526192013-06-10 19:30:26 +0000660class _GitDiffCache(_DiffCache):
661 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000662 def __init__(self, upstream):
663 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000664 self._diffs_by_file = None
665
666 def GetDiff(self, path, local_root):
667 if not self._diffs_by_file:
668 # Compute a single diff for all files and parse the output; should
669 # with git this is much faster than computing one diff for each file.
670 diffs = {}
671
672 # Don't specify any filenames below, because there are command line length
673 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000674 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
675 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000676
677 # This regex matches the path twice, separated by a space. Note that
678 # filename itself may contain spaces.
679 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
680 current_diff = []
681 keep_line_endings = True
682 for x in unified_diff.splitlines(keep_line_endings):
683 match = file_marker.match(x)
684 if match:
685 # Marks the start of a new per-file section.
686 diffs[match.group('filename')] = current_diff = [x]
687 elif x.startswith('diff --git'):
688 raise PresubmitFailure('Unexpected diff line: %s' % x)
689 else:
690 current_diff.append(x)
691
692 self._diffs_by_file = dict(
693 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
694
695 if path not in self._diffs_by_file:
696 raise PresubmitFailure(
697 'Unified diff did not contain entry for file %s' % path)
698
699 return self._diffs_by_file[path]
700
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700701 def GetOldContents(self, path, local_root):
702 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
703
nick@chromium.orgff526192013-06-10 19:30:26 +0000704
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000705class AffectedFile(object):
706 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000707
708 DIFF_CACHE = _DiffCache
709
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000710 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800711 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000712 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000713 self._path = path
714 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000715 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000716 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000717 self._cached_changed_contents = None
718 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000719 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700720 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000721
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000722 def LocalPath(self):
723 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400724
725 This should be used for error messages but not for accessing files,
726 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
727 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000728 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000729 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000730
731 def AbsoluteLocalPath(self):
732 """Returns the absolute path of this file on the local disk.
733 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000734 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000735
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000736 def Action(self):
737 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000738 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000739
agable0b65e732016-11-22 09:25:46 -0800740 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000741 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000742
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000743 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000744 raise NotImplementedError() # Implement when needed
745
agable0b65e732016-11-22 09:25:46 -0800746 def IsTextFile(self):
747 """An alias to IsTestableFile for backwards compatibility."""
748 return self.IsTestableFile()
749
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700750 def OldContents(self):
751 """Returns an iterator over the lines in the old version of file.
752
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700753 The old version is the file before any modifications in the user's
754 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700755
756 Contents will be empty if the file is a directory or does not exist.
757 Note: The carriage returns (LF or CR) are stripped off.
758 """
759 return self._diff_cache.GetOldContents(self.LocalPath(),
760 self._local_root).splitlines()
761
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000762 def NewContents(self):
763 """Returns an iterator over the lines in the new version of file.
764
765 The new version is the file in the user's workspace, i.e. the "right hand
766 side".
767
768 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000769 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000770 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000771 if self._cached_new_contents is None:
772 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800773 try:
774 self._cached_new_contents = gclient_utils.FileRead(
775 self.AbsoluteLocalPath(), 'rU').splitlines()
776 except IOError:
777 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000778 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000779
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000780 def ChangedContents(self):
781 """Returns a list of tuples (line number, line text) of all new lines.
782
783 This relies on the scm diff output describing each changed code section
784 with a line of the form
785
786 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
787 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000788 if self._cached_changed_contents is not None:
789 return self._cached_changed_contents[:]
790 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000791 line_num = 0
792
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000793 for line in self.GenerateScmDiff().splitlines():
794 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
795 if m:
796 line_num = int(m.groups(1)[0])
797 continue
798 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000799 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000800 if not line.startswith('-'):
801 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000802 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000803
maruel@chromium.org5de13972009-06-10 18:16:06 +0000804 def __str__(self):
805 return self.LocalPath()
806
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000807 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000808 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000809
maruel@chromium.org58407af2011-04-12 23:15:57 +0000810
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000811class GitAffectedFile(AffectedFile):
812 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000813 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800814 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000815
nick@chromium.orgff526192013-06-10 19:30:26 +0000816 DIFF_CACHE = _GitDiffCache
817
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000818 def __init__(self, *args, **kwargs):
819 AffectedFile.__init__(self, *args, **kwargs)
820 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800821 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000822
agable0b65e732016-11-22 09:25:46 -0800823 def IsTestableFile(self):
824 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000825 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800826 # A deleted file is not testable.
827 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000828 else:
agable0b65e732016-11-22 09:25:46 -0800829 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
830 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000831
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000832
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000833class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000834 """Describe a change.
835
836 Used directly by the presubmit scripts to query the current change being
837 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000838
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000839 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000840 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000841 self.KEY: equivalent to tags['KEY']
842 """
843
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000844 _AFFECTED_FILES = AffectedFile
845
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000846 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000847 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000848 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000849 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000850
maruel@chromium.org58407af2011-04-12 23:15:57 +0000851 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000852 self, name, description, local_root, files, issue, patchset, author,
853 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000854 if files is None:
855 files = []
856 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000857 # Convert root into an absolute path.
858 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000859 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000860 self.issue = issue
861 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000862 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000863
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000864 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000865 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000866 self._description_without_tags = ''
867 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000868
maruel@chromium.orge085d812011-10-10 19:49:15 +0000869 assert all(
870 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
871
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000872 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000873 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000874 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
875 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000876 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000877
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000878 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000879 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000880 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000881
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000882 def DescriptionText(self):
883 """Returns the user-entered changelist description, minus tags.
884
885 Any line in the user-provided description starting with e.g. "FOO="
886 (whitespace permitted before and around) is considered a tag line. Such
887 lines are stripped out of the description this function returns.
888 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000889 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000890
891 def FullDescriptionText(self):
892 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000893 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000894
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000895 def SetDescriptionText(self, description):
896 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000897
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000898 Also updates the list of tags."""
899 self._full_description = description
900
901 # From the description text, build up a dictionary of key/value pairs
902 # plus the description minus all key/value or "tag" lines.
903 description_without_tags = []
904 self.tags = {}
905 for line in self._full_description.splitlines():
906 m = self.TAG_LINE_RE.match(line)
907 if m:
908 self.tags[m.group('key')] = m.group('value')
909 else:
910 description_without_tags.append(line)
911
912 # Change back to text and remove whitespace at end.
913 self._description_without_tags = (
914 '\n'.join(description_without_tags).rstrip())
915
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000916 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000917 """Returns the repository (checkout) root directory for this change,
918 as an absolute path.
919 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000920 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000921
922 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000923 """Return tags directly as attributes on the object."""
924 if not re.match(r"^[A-Z_]*$", attr):
925 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000926 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000927
Aaron Gablefc03e672017-05-15 14:09:42 -0700928 def BugsFromDescription(self):
929 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700930 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
931 footers = git_footers.parse_footers(self._full_description).get('Bug', [])
932 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700933
934 def ReviewersFromDescription(self):
935 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700936 # We don't support a "R:" git-footer for reviewers; that is in metadata.
937 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
938 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -0700939
940 def TBRsFromDescription(self):
941 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700942 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
943 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
944 # determined by self-CR+1s.
945 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
946 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700947
948 # TODO(agable): Delete these once we're sure they're unused.
949 @property
950 def BUG(self):
951 return ','.join(self.BugsFromDescription())
952 @property
953 def R(self):
954 return ','.join(self.ReviewersFromDescription())
955 @property
956 def TBR(self):
957 return ','.join(self.TBRsFromDescription())
958
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000959 def AllFiles(self, root=None):
960 """List all files under source control in the repo."""
961 raise NotImplementedError()
962
agable0b65e732016-11-22 09:25:46 -0800963 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000964 """Returns a list of AffectedFile instances for all files in the change.
965
966 Args:
967 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +0000968 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000969
970 Returns:
971 [AffectedFile(path, action), AffectedFile(path, action)]
972 """
agable0b65e732016-11-22 09:25:46 -0800973 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +0000974
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000975 if include_deletes:
976 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -0700977 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000978
agable0b65e732016-11-22 09:25:46 -0800979 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000980 """Return a list of the existing text files in a change."""
981 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800982 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000983 " is deprecated and ignored" % str(include_deletes),
984 category=DeprecationWarning,
985 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800986 return filter(lambda x: x.IsTestableFile(),
987 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000988
agable0b65e732016-11-22 09:25:46 -0800989 def AffectedTextFiles(self, include_deletes=None):
990 """An alias to AffectedTestableFiles for backwards compatibility."""
991 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000992
agable0b65e732016-11-22 09:25:46 -0800993 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000994 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800995 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000996
agable0b65e732016-11-22 09:25:46 -0800997 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000998 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800999 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000
1001 def RightHandSideLines(self):
1002 """An iterator over all text lines in "new" version of changed files.
1003
1004 Lists lines from new or modified text files in the change.
1005
1006 This is useful for doing line-by-line regex checks, like checking for
1007 trailing whitespace.
1008
1009 Yields:
1010 a 3 tuple:
1011 the AffectedFile instance of the current file;
1012 integer line number (1-based); and
1013 the contents of the line as a string.
1014 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001015 return _RightHandSideLinesImpl(
1016 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001017 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001018
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001019 def OriginalOwnersFiles(self):
1020 """A map from path names of affected OWNERS files to their old content."""
1021 def owners_file_filter(f):
1022 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1023 files = self.AffectedFiles(file_filter=owners_file_filter)
1024 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1025
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001026
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001027class GitChange(Change):
1028 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001029 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001030
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001031 def AllFiles(self, root=None):
1032 """List all files under source control in the repo."""
1033 root = root or self.RepositoryRoot()
1034 return subprocess.check_output(
1035 ['git', 'ls-files', '--', '.'], cwd=root).splitlines()
1036
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001037
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001038def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001039 """Finds all presubmit files that apply to a given set of source files.
1040
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001041 If inherit-review-settings-ok is present right under root, looks for
1042 PRESUBMIT.py in directories enclosing root.
1043
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001044 Args:
1045 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001046 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001047
1048 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001049 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001050 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001051 files = [normpath(os.path.join(root, f)) for f in files]
1052
1053 # List all the individual directories containing files.
1054 directories = set([os.path.dirname(f) for f in files])
1055
1056 # Ignore root if inherit-review-settings-ok is present.
1057 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1058 root = None
1059
1060 # Collect all unique directories that may contain PRESUBMIT.py.
1061 candidates = set()
1062 for directory in directories:
1063 while True:
1064 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001065 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001066 candidates.add(directory)
1067 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001068 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001069 parent_dir = os.path.dirname(directory)
1070 if parent_dir == directory:
1071 # We hit the system root directory.
1072 break
1073 directory = parent_dir
1074
1075 # Look for PRESUBMIT.py in all candidate directories.
1076 results = []
1077 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001078 try:
1079 for f in os.listdir(directory):
1080 p = os.path.join(directory, f)
1081 if os.path.isfile(p) and re.match(
1082 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1083 results.append(p)
1084 except OSError:
1085 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001086
tobiasjs2836bcf2016-08-16 04:08:16 -07001087 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001088 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001089
1090
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001091class GetTryMastersExecuter(object):
1092 @staticmethod
1093 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1094 """Executes GetPreferredTryMasters() from a single presubmit script.
1095
1096 Args:
1097 script_text: The text of the presubmit script.
1098 presubmit_path: Project script to run.
1099 project: Project name to pass to presubmit script for bot selection.
1100
1101 Return:
1102 A map of try masters to map of builders to set of tests.
1103 """
1104 context = {}
1105 try:
1106 exec script_text in context
1107 except Exception, e:
1108 raise PresubmitFailure('"%s" had an exception.\n%s'
1109 % (presubmit_path, e))
1110
1111 function_name = 'GetPreferredTryMasters'
1112 if function_name not in context:
1113 return {}
1114 get_preferred_try_masters = context[function_name]
1115 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1116 raise PresubmitFailure(
1117 'Expected function "GetPreferredTryMasters" to take two arguments.')
1118 return get_preferred_try_masters(project, change)
1119
1120
rmistry@google.com5626a922015-02-26 14:03:30 +00001121class GetPostUploadExecuter(object):
1122 @staticmethod
1123 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1124 """Executes PostUploadHook() from a single presubmit script.
1125
1126 Args:
1127 script_text: The text of the presubmit script.
1128 presubmit_path: Project script to run.
1129 cl: The Changelist object.
1130 change: The Change object.
1131
1132 Return:
1133 A list of results objects.
1134 """
1135 context = {}
1136 try:
1137 exec script_text in context
1138 except Exception, e:
1139 raise PresubmitFailure('"%s" had an exception.\n%s'
1140 % (presubmit_path, e))
1141
1142 function_name = 'PostUploadHook'
1143 if function_name not in context:
1144 return {}
1145 post_upload_hook = context[function_name]
1146 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1147 raise PresubmitFailure(
1148 'Expected function "PostUploadHook" to take three arguments.')
1149 return post_upload_hook(cl, change, OutputApi(False))
1150
1151
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001152def _MergeMasters(masters1, masters2):
1153 """Merges two master maps. Merges also the tests of each builder."""
1154 result = {}
1155 for (master, builders) in itertools.chain(masters1.iteritems(),
1156 masters2.iteritems()):
1157 new_builders = result.setdefault(master, {})
1158 for (builder, tests) in builders.iteritems():
1159 new_builders.setdefault(builder, set([])).update(tests)
1160 return result
1161
1162
1163def DoGetTryMasters(change,
1164 changed_files,
1165 repository_root,
1166 default_presubmit,
1167 project,
1168 verbose,
1169 output_stream):
1170 """Get the list of try masters from the presubmit scripts.
1171
1172 Args:
1173 changed_files: List of modified files.
1174 repository_root: The repository root.
1175 default_presubmit: A default presubmit script to execute in any case.
1176 project: Optional name of a project used in selecting trybots.
1177 verbose: Prints debug info.
1178 output_stream: A stream to write debug output to.
1179
1180 Return:
1181 Map of try masters to map of builders to set of tests.
1182 """
1183 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1184 if not presubmit_files and verbose:
1185 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1186 results = {}
1187 executer = GetTryMastersExecuter()
1188
1189 if default_presubmit:
1190 if verbose:
1191 output_stream.write("Running default presubmit script.\n")
1192 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1193 results = _MergeMasters(results, executer.ExecPresubmitScript(
1194 default_presubmit, fake_path, project, change))
1195 for filename in presubmit_files:
1196 filename = os.path.abspath(filename)
1197 if verbose:
1198 output_stream.write("Running %s\n" % filename)
1199 # Accept CRLF presubmit script.
1200 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1201 results = _MergeMasters(results, executer.ExecPresubmitScript(
1202 presubmit_script, filename, project, change))
1203
1204 # Make sets to lists again for later JSON serialization.
1205 for builders in results.itervalues():
1206 for builder in builders:
1207 builders[builder] = list(builders[builder])
1208
1209 if results and verbose:
1210 output_stream.write('%s\n' % str(results))
1211 return results
1212
1213
rmistry@google.com5626a922015-02-26 14:03:30 +00001214def DoPostUploadExecuter(change,
1215 cl,
1216 repository_root,
1217 verbose,
1218 output_stream):
1219 """Execute the post upload hook.
1220
1221 Args:
1222 change: The Change object.
1223 cl: The Changelist object.
1224 repository_root: The repository root.
1225 verbose: Prints debug info.
1226 output_stream: A stream to write debug output to.
1227 """
1228 presubmit_files = ListRelevantPresubmitFiles(
1229 change.LocalPaths(), repository_root)
1230 if not presubmit_files and verbose:
1231 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1232 results = []
1233 executer = GetPostUploadExecuter()
1234 # The root presubmit file should be executed after the ones in subdirectories.
1235 # i.e. the specific post upload hooks should run before the general ones.
1236 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1237 presubmit_files.reverse()
1238
1239 for filename in presubmit_files:
1240 filename = os.path.abspath(filename)
1241 if verbose:
1242 output_stream.write("Running %s\n" % filename)
1243 # Accept CRLF presubmit script.
1244 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1245 results.extend(executer.ExecPresubmitScript(
1246 presubmit_script, filename, cl, change))
1247 output_stream.write('\n')
1248 if results:
1249 output_stream.write('** Post Upload Hook Messages **\n')
1250 for result in results:
1251 result.handle(output_stream)
1252 output_stream.write('\n')
1253
1254 return results
1255
1256
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001257class PresubmitExecuter(object):
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001258 def __init__(self, change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001259 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001260 """
1261 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001262 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001263 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001264 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001265 gerrit_obj: provides basic Gerrit codereview functionality.
1266 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001267 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001268 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001269 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001270 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001271 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001272 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001273 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001274
1275 def ExecPresubmitScript(self, script_text, presubmit_path):
1276 """Executes a single presubmit script.
1277
1278 Args:
1279 script_text: The text of the presubmit script.
1280 presubmit_path: The path to the presubmit file (this will be reported via
1281 input_api.PresubmitLocalPath()).
1282
1283 Return:
1284 A list of result objects, empty if no problems.
1285 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001286
chase@chromium.org8e416c82009-10-06 04:30:44 +00001287 # Change to the presubmit file's directory to support local imports.
1288 main_path = os.getcwd()
1289 os.chdir(os.path.dirname(presubmit_path))
1290
1291 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001292 input_api = InputApi(self.change, presubmit_path, self.committing,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001293 self.rietveld, self.verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001294 gerrit_obj=self.gerrit, dry_run=self.dry_run)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001295 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001296 try:
1297 exec script_text in context
1298 except Exception, e:
1299 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001300
1301 # These function names must change if we make substantial changes to
1302 # the presubmit API that are not backwards compatible.
1303 if self.committing:
1304 function_name = 'CheckChangeOnCommit'
1305 else:
1306 function_name = 'CheckChangeOnUpload'
1307 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001308 try:
1309 context['__args'] = (input_api, OutputApi(self.committing))
1310 logging.debug('Running %s in %s', function_name, presubmit_path)
1311 result = eval(function_name + '(*__args)', context)
1312 logging.debug('Running %s done.', function_name)
1313 finally:
1314 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001315 if not (isinstance(result, types.TupleType) or
1316 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001317 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001318 'Presubmit functions must return a tuple or list')
1319 for item in result:
1320 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001321 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001322 'All presubmit results must be of types derived from '
1323 'output_api.PresubmitResult')
1324 else:
1325 result = () # no error since the script doesn't care about current event.
1326
scottmg86099d72016-09-01 09:16:51 -07001327 input_api.ShutdownPool()
1328
chase@chromium.org8e416c82009-10-06 04:30:44 +00001329 # Return the process to the original working directory.
1330 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001331 return result
1332
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001333def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001334 committing,
1335 verbose,
1336 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001337 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001338 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001339 may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001340 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001341 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001342 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001343 """Runs all presubmit checks that apply to the files in the change.
1344
1345 This finds all PRESUBMIT.py files in directories enclosing the files in the
1346 change (up to the repository root) and calls the relevant entrypoint function
1347 depending on whether the change is being committed or uploaded.
1348
1349 Prints errors, warnings and notifications. Prompts the user for warnings
1350 when needed.
1351
1352 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001353 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001354 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001355 verbose: Prints debug info.
1356 output_stream: A stream to write output from presubmit tests to.
1357 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001358 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001359 may_prompt: Enable (y/n) questions on warning or error. If False,
1360 any questions are answered with yes by default.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001361 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001362 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001363 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001364
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001365 Warning:
1366 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1367 SHOULD be sys.stdin.
1368
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001369 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001370 A PresubmitOutput object. Use output.should_continue() to figure out
1371 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001372 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001373 old_environ = os.environ
1374 try:
1375 # Make sure python subprocesses won't generate .pyc files.
1376 os.environ = os.environ.copy()
1377 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001378
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001379 output = PresubmitOutput(input_stream, output_stream)
1380 if committing:
1381 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001382 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001383 output.write("Running presubmit upload checks ...\n")
1384 start_time = time.time()
1385 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001386 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001387 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001388 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001389 results = []
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001390 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001391 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001392 if default_presubmit:
1393 if verbose:
1394 output.write("Running default presubmit script.\n")
1395 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1396 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1397 for filename in presubmit_files:
1398 filename = os.path.abspath(filename)
1399 if verbose:
1400 output.write("Running %s\n" % filename)
1401 # Accept CRLF presubmit script.
1402 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1403 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001404
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001405 errors = []
1406 notifications = []
1407 warnings = []
1408 for result in results:
1409 if result.fatal:
1410 errors.append(result)
1411 elif result.should_prompt:
1412 warnings.append(result)
1413 else:
1414 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001415
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001416 output.write('\n')
1417 for name, items in (('Messages', notifications),
1418 ('Warnings', warnings),
1419 ('ERRORS', errors)):
1420 if items:
1421 output.write('** Presubmit %s **\n' % name)
1422 for item in items:
1423 item.handle(output)
1424 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001425
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001426 total_time = time.time() - start_time
1427 if total_time > 1.0:
1428 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001429
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001430 if errors:
1431 output.fail()
1432 elif warnings:
1433 output.write('There were presubmit warnings. ')
1434 if may_prompt:
1435 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1436 else:
1437 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001438
1439 global _ASKED_FOR_FEEDBACK
1440 # Ask for feedback one time out of 5.
1441 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001442 output.write(
1443 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1444 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1445 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001446 _ASKED_FOR_FEEDBACK = True
1447 return output
1448 finally:
1449 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001450
1451
1452def ScanSubDirs(mask, recursive):
1453 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001454 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001455
1456 results = []
1457 for root, dirs, files in os.walk('.'):
1458 if '.svn' in dirs:
1459 dirs.remove('.svn')
1460 if '.git' in dirs:
1461 dirs.remove('.git')
1462 for name in files:
1463 if fnmatch.fnmatch(name, mask):
1464 results.append(os.path.join(root, name))
1465 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001466
1467
1468def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001469 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001470 files = []
1471 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001472 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001473 return files
1474
1475
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001476def load_files(options, args):
1477 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001478 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001479 if args:
1480 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001481 change_scm = scm.determine_scm(options.root)
1482 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001483 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001484 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001485 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001486 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001487 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001488 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001489 if not files:
1490 return None, None
1491 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001492 return change_class, files
1493
1494
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001495class NonexistantCannedCheckFilter(Exception):
1496 pass
1497
1498
1499@contextlib.contextmanager
1500def canned_check_filter(method_names):
1501 filtered = {}
1502 try:
1503 for method_name in method_names:
1504 if not hasattr(presubmit_canned_checks, method_name):
1505 raise NonexistantCannedCheckFilter(method_name)
1506 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1507 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1508 yield
1509 finally:
1510 for name, method in filtered.iteritems():
1511 setattr(presubmit_canned_checks, name, method)
1512
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001513
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001514def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001515 """Runs an external program, potentially from a child process created by the
1516 multiprocessing module.
1517
1518 multiprocessing needs a top level function with a single argument.
1519 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001520 cmd_data.kwargs['stdout'] = subprocess.PIPE
1521 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1522 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001523 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001524 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001525 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001526 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001527 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001528 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001529 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1530 if code != 0:
1531 return cmd_data.message(
1532 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1533 if cmd_data.info:
1534 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001535
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001536
sbc@chromium.org013731e2015-02-26 18:28:43 +00001537def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001538 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001539 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001540 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001541 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001542 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1543 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001544 parser.add_option("-r", "--recursive", action="store_true",
1545 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001546 parser.add_option("-v", "--verbose", action="count", default=0,
1547 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001548 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001549 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001550 parser.add_option("--description", default='')
1551 parser.add_option("--issue", type='int', default=0)
1552 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001553 parser.add_option("--root", default=os.getcwd(),
1554 help="Search for PRESUBMIT.py up to this directory. "
1555 "If inherit-review-settings-ok is present in this "
1556 "directory, parent directories up to the root file "
1557 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001558 parser.add_option("--upstream",
1559 help="Git only: the base ref or upstream branch against "
1560 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001561 parser.add_option("--default_presubmit")
1562 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001563 parser.add_option("--skip_canned", action='append', default=[],
1564 help="A list of checks to skip which appear in "
1565 "presubmit_canned_checks. Can be provided multiple times "
1566 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001567 parser.add_option("--dry_run", action='store_true',
1568 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001569 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001570 parser.add_option("--gerrit_fetch", action='store_true',
1571 help=optparse.SUPPRESS_HELP)
maruel@chromium.org239f4112011-06-03 20:08:23 +00001572 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1573 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001574 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1575 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001576 # These are for OAuth2 authentication for bots. See also apply_issue.py
1577 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1578 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1579
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001580 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001581 options, args = parser.parse_args(argv)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001582 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001583
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001584 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001585 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001586 elif options.verbose:
1587 logging.basicConfig(level=logging.INFO)
1588 else:
1589 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001590
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001591 if (any((options.rietveld_url, options.rietveld_email_file,
1592 options.rietveld_fetch, options.rietveld_private_key_file))
1593 and any((options.gerrit_url, options.gerrit_fetch))):
1594 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1595 'allowed')
1596
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001597 if options.rietveld_email and options.rietveld_email_file:
1598 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1599 "can be passed to this program.")
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001600 if options.rietveld_email_file:
1601 with open(options.rietveld_email_file, "rb") as f:
1602 options.rietveld_email = f.read().strip()
1603
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001604 change_class, files = load_files(options, args)
1605 if not change_class:
1606 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001607 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001608
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001609 rietveld_obj, gerrit_obj = None, None
1610
maruel@chromium.org239f4112011-06-03 20:08:23 +00001611 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001612 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001613 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001614 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1615 options.rietveld_url,
1616 options.rietveld_email,
1617 options.rietveld_private_key_file)
1618 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001619 rietveld_obj = rietveld.CachingRietveld(
1620 options.rietveld_url,
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001621 auth_config,
1622 options.rietveld_email)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001623 if options.rietveld_fetch:
1624 assert options.issue
1625 props = rietveld_obj.get_issue_properties(options.issue, False)
1626 options.author = props['owner_email']
1627 options.description = props['description']
1628 logging.info('Got author: "%s"', options.author)
1629 logging.info('Got description: """\n%s\n"""', options.description)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001630
1631 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001632 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001633 rietveld_obj = None
1634 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1635 options.author = gerrit_obj.GetChangeOwner(options.issue)
1636 options.description = gerrit_obj.GetChangeDescription(options.issue,
1637 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001638 logging.info('Got author: "%s"', options.author)
1639 logging.info('Got description: """\n%s\n"""', options.description)
1640
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001641 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001642 with canned_check_filter(options.skip_canned):
1643 results = DoPresubmitChecks(
1644 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001645 options.description,
1646 options.root,
1647 files,
1648 options.issue,
1649 options.patchset,
1650 options.author,
1651 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001652 options.commit,
1653 options.verbose,
1654 sys.stdout,
1655 sys.stdin,
1656 options.default_presubmit,
1657 options.may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001658 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001659 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001660 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001661 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001662 except NonexistantCannedCheckFilter, e:
1663 print >> sys.stderr, (
1664 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1665 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001666 except PresubmitFailure, e:
1667 print >> sys.stderr, e
1668 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1669 print >> sys.stderr, 'If all fails, contact maruel@'
1670 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001671
1672
1673if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001674 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001675 try:
1676 sys.exit(main())
1677 except KeyboardInterrupt:
1678 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001679 sys.exit(2)