blob: 59bc4c1f47acd9abbad0dc4426a55905589a31d0 [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 = []
Daniel Cheng7227d212017-11-17 08:12:37 -080097 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +000098 self.written_output = []
99 self.error_count = 0
100
101 def prompt_yes_no(self, prompt_string):
102 self.write(prompt_string)
103 if self.input_stream:
104 response = self.input_stream.readline().strip().lower()
105 if response not in ('y', 'yes'):
106 self.fail()
107 else:
108 self.fail()
109
110 def fail(self):
111 self.error_count += 1
112
113 def should_continue(self):
114 return not self.error_count
115
116 def write(self, s):
117 self.written_output.append(s)
118 if self.output_stream:
119 self.output_stream.write(s)
120
121 def getvalue(self):
122 return ''.join(self.written_output)
123
124
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000125# Top level object so multiprocessing can pickle
126# Public access through OutputApi object.
127class _PresubmitResult(object):
128 """Base class for result objects."""
129 fatal = False
130 should_prompt = False
131
132 def __init__(self, message, items=None, long_text=''):
133 """
134 message: A short one-line message to indicate errors.
135 items: A list of short strings to indicate where errors occurred.
136 long_text: multi-line text output, e.g. from another tool
137 """
138 self._message = message
139 self._items = items or []
140 if items:
141 self._items = items
142 self._long_text = long_text.rstrip()
143
144 def handle(self, output):
145 output.write(self._message)
146 output.write('\n')
147 for index, item in enumerate(self._items):
148 output.write(' ')
149 # Write separately in case it's unicode.
150 output.write(str(item))
151 if index < len(self._items) - 1:
152 output.write(' \\')
153 output.write('\n')
154 if self._long_text:
155 output.write('\n***************\n')
156 # Write separately in case it's unicode.
157 output.write(self._long_text)
158 output.write('\n***************\n')
159 if self.fatal:
160 output.fail()
161
162
163# Top level object so multiprocessing can pickle
164# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000165class _PresubmitError(_PresubmitResult):
166 """A hard presubmit error."""
167 fatal = True
168
169
170# Top level object so multiprocessing can pickle
171# Public access through OutputApi object.
172class _PresubmitPromptWarning(_PresubmitResult):
173 """An warning that prompts the user if they want to continue."""
174 should_prompt = True
175
176
177# Top level object so multiprocessing can pickle
178# Public access through OutputApi object.
179class _PresubmitNotifyResult(_PresubmitResult):
180 """Just print something to the screen -- but it's not even a warning."""
181 pass
182
183
184# Top level object so multiprocessing can pickle
185# Public access through OutputApi object.
186class _MailTextResult(_PresubmitResult):
187 """A warning that should be included in the review request email."""
188 def __init__(self, *args, **kwargs):
189 super(_MailTextResult, self).__init__()
190 raise NotImplementedError()
191
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000192class GerritAccessor(object):
193 """Limited Gerrit functionality for canned presubmit checks to work.
194
195 To avoid excessive Gerrit calls, caches the results.
196 """
197
198 def __init__(self, host):
199 self.host = host
200 self.cache = {}
201
202 def _FetchChangeDetail(self, issue):
203 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100204 try:
205 return gerrit_util.GetChangeDetail(
206 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700207 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100208 except gerrit_util.GerritError as e:
209 if e.http_status == 404:
210 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
211 'no credentials to fetch issue details' % issue)
212 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000213
214 def GetChangeInfo(self, issue):
215 """Returns labels and all revisions (patchsets) for this issue.
216
217 The result is a dictionary according to Gerrit REST Api.
218 https://gerrit-review.googlesource.com/Documentation/rest-api.html
219
220 However, API isn't very clear what's inside, so see tests for example.
221 """
222 assert issue
223 cache_key = int(issue)
224 if cache_key not in self.cache:
225 self.cache[cache_key] = self._FetchChangeDetail(issue)
226 return self.cache[cache_key]
227
228 def GetChangeDescription(self, issue, patchset=None):
229 """If patchset is none, fetches current patchset."""
230 info = self.GetChangeInfo(issue)
231 # info is a reference to cache. We'll modify it here adding description to
232 # it to the right patchset, if it is not yet there.
233
234 # Find revision info for the patchset we want.
235 if patchset is not None:
236 for rev, rev_info in info['revisions'].iteritems():
237 if str(rev_info['_number']) == str(patchset):
238 break
239 else:
240 raise Exception('patchset %s doesn\'t exist in issue %s' % (
241 patchset, issue))
242 else:
243 rev = info['current_revision']
244 rev_info = info['revisions'][rev]
245
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100246 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000247
248 def GetChangeOwner(self, issue):
249 return self.GetChangeInfo(issue)['owner']['email']
250
251 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700252 changeinfo = self.GetChangeInfo(issue)
253 if approving_only:
254 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
255 values = labelinfo.get('values', {}).keys()
256 try:
257 max_value = max(int(v) for v in values)
258 reviewers = [r for r in labelinfo.get('all', [])
259 if r.get('value', 0) == max_value]
260 except ValueError: # values is the empty list
261 reviewers = []
262 else:
263 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
264 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000265
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000266
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000267class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000268 """An instance of OutputApi gets passed to presubmit scripts so that they
269 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000270 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000271 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000272 PresubmitError = _PresubmitError
273 PresubmitPromptWarning = _PresubmitPromptWarning
274 PresubmitNotifyResult = _PresubmitNotifyResult
275 MailTextResult = _MailTextResult
276
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000277 def __init__(self, is_committing):
278 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800279 self.more_cc = []
280
281 def AppendCC(self, cc):
282 """Appends a user to cc for this change."""
283 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000284
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000285 def PresubmitPromptOrNotify(self, *args, **kwargs):
286 """Warn the user when uploading, but only notify if committing."""
287 if self.is_committing:
288 return self.PresubmitNotifyResult(*args, **kwargs)
289 return self.PresubmitPromptWarning(*args, **kwargs)
290
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800291 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
292 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
293
294 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
295 keeping it alphabetically sorted. Returns the results that should be
296 returned from the PostUploadHook.
297
298 Args:
299 cl: The git_cl.Changelist object.
300 bots_to_include: A list of strings of bots to include, in the form
301 "master:slave".
302 message: A message to be printed in the case that
303 CQ_INCLUDE_TRYBOTS was updated.
304 """
305 description = cl.GetDescription(force=True)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700306 include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)$', re.M | re.I)
307
308 prior_bots = []
309 if cl.IsGerrit():
310 trybot_footers = git_footers.parse_footers(description).get(
311 git_footers.normalize_name('Cq-Include-Trybots'), [])
312 for f in trybot_footers:
313 prior_bots += [b.strip() for b in f.split(';') if b.strip()]
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800314 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700315 trybot_tags = include_re.finditer(description)
316 for t in trybot_tags:
317 prior_bots += [b.strip() for b in t.group(1).split(';') if b.strip()]
318
319 if set(prior_bots) >= set(bots_to_include):
320 return []
321 all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include)))
322
323 if cl.IsGerrit():
324 description = git_footers.remove_footer(
325 description, 'Cq-Include-Trybots')
326 description = git_footers.add_footer(
327 description, 'Cq-Include-Trybots', all_bots,
328 before_keys=['Change-Id'])
329 else:
330 new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % all_bots
331 m = include_re.search(description)
332 if m:
333 description = include_re.sub(new_include_trybots, description)
Kenneth Russelldf6e7342017-04-24 17:07:41 -0700334 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700335 description = '%s\n%s\n' % (description, new_include_trybots)
336
337 cl.UpdateDescription(description, force=True)
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800338 return [self.PresubmitNotifyResult(message)]
339
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000340
341class InputApi(object):
342 """An instance of this object is passed to presubmit scripts so they can
343 know stuff about the change they're looking at.
344 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000345 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800346 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000347
maruel@chromium.org3410d912009-06-09 20:56:16 +0000348 # File extensions that are considered source files from a style guide
349 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000350 #
351 # Files without an extension aren't included in the list. If you want to
352 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
353 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000354 DEFAULT_WHITE_LIST = (
355 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000356 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
357 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000358 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000359 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000360 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000361 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000362 )
363
364 # Path regexp that should be excluded from being considered containing source
365 # files. Don't modify this list from a presubmit script!
366 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000367 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000368 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000369 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
370 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000371 # Output directories (just in case)
372 r".*\bDebug[\\\/].*",
373 r".*\bRelease[\\\/].*",
374 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000375 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000376 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000377 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000378 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000379 r"(|.*[\\\/])\.git[\\\/].*",
380 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000381 # There is no point in processing a patch file.
382 r".+\.diff$",
383 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000384 )
385
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000386 def __init__(self, change, presubmit_path, is_committing,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000387 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000388 """Builds an InputApi object.
389
390 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000391 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000392 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000393 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000394 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000395 gerrit_obj: provides basic Gerrit codereview functionality.
396 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000397 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000398 # Version number of the presubmit_support script.
399 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000400 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000401 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000402 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000403 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000404 self.dry_run = dry_run
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000405 # TBD
406 self.host_url = 'http://codereview.chromium.org'
407 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000408 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000409
410 # We expose various modules and functions as attributes of the input_api
411 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900412 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000413 self.basename = os.path.basename
414 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000415 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000416 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700417 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000418 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000419 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000420 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000421 self.os_listdir = os.listdir
422 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000423 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000424 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000425 self.pickle = pickle
426 self.marshal = marshal
427 self.re = re
428 self.subprocess = subprocess
429 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000430 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000431 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000432 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000433 self.urllib2 = urllib2
434
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000435 # To easily fork python.
436 self.python_executable = sys.executable
437 self.environ = os.environ
438
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000439 # InputApi.platform is the platform you're currently running on.
440 self.platform = sys.platform
441
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000442 self.cpu_count = multiprocessing.cpu_count()
443
Aaron Gable5254da12017-09-06 21:05:39 +0000444 # this is done here because in RunTests, the current working directory has
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000445 # changed, which causes Pool() to explode fantastically when run on windows
446 # (because it tries to load the __main__ module, which imports lots of
447 # things relative to the current working directory).
Aaron Gable5254da12017-09-06 21:05:39 +0000448 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000449
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000450 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000451 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000452
453 # We carry the canned checks so presubmit scripts can easily use them.
454 self.canned_checks = presubmit_canned_checks
455
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100456 # Temporary files we must manually remove at the end of a run.
457 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200458
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000459 # TODO(dpranke): figure out a list of all approved owners for a repo
460 # in order to be able to handle wildcard OWNERS files?
461 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200462 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200463 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000464 self.verbose = verbose
Dan Jacques94652a32017-10-09 23:18:46 -0400465 self.is_windows = sys.platform == 'win32'
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000466 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000467
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000468 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000469 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000470 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800471 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000472 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000473 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000474 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
475 for (a, b, header) in cpplint._re_pattern_templates
476 ]
477
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000478 def PresubmitLocalPath(self):
479 """Returns the local path of the presubmit script currently being run.
480
481 This is useful if you don't want to hard-code absolute paths in the
482 presubmit script. For example, It can be used to find another file
483 relative to the PRESUBMIT.py script, so the whole tree can be branched and
484 the presubmit script still works, without editing its content.
485 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000486 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000487
agable0b65e732016-11-22 09:25:46 -0800488 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000489 """Same as input_api.change.AffectedFiles() except only lists files
490 (and optionally directories) in the same directory as the current presubmit
491 script, or subdirectories thereof.
492 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000493 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000494 if len(dir_with_slash) == 1:
495 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000496
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000497 return filter(
498 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800499 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000500
agable0b65e732016-11-22 09:25:46 -0800501 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000502 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800503 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000504 logging.debug("LocalPaths: %s", paths)
505 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000506
agable0b65e732016-11-22 09:25:46 -0800507 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000508 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800509 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000510
agable0b65e732016-11-22 09:25:46 -0800511 def AffectedTestableFiles(self, include_deletes=None):
512 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000513 in the same directory as the current presubmit script, or subdirectories
514 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000515 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000516 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800517 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000518 " is deprecated and ignored" % str(include_deletes),
519 category=DeprecationWarning,
520 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800521 return filter(lambda x: x.IsTestableFile(),
522 self.AffectedFiles(include_deletes=False))
523
524 def AffectedTextFiles(self, include_deletes=None):
525 """An alias to AffectedTestableFiles for backwards compatibility."""
526 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000527
maruel@chromium.org3410d912009-06-09 20:56:16 +0000528 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
529 """Filters out files that aren't considered "source file".
530
531 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
532 and InputApi.DEFAULT_BLACK_LIST is used respectively.
533
534 The lists will be compiled as regular expression and
535 AffectedFile.LocalPath() needs to pass both list.
536
537 Note: Copy-paste this function to suit your needs or use a lambda function.
538 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000539 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000540 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000541 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000542 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000543 return True
544 return False
545 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
546 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
547
548 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800549 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000550
551 If source_file is None, InputApi.FilterSourceFile() is used.
552 """
553 if not source_file:
554 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800555 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000556
557 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000558 """An iterator over all text lines in "new" version of changed files.
559
560 Only lists lines from new or modified text files in the change that are
561 contained by the directory of the currently executing presubmit script.
562
563 This is useful for doing line-by-line regex checks, like checking for
564 trailing whitespace.
565
566 Yields:
567 a 3 tuple:
568 the AffectedFile instance of the current file;
569 integer line number (1-based); and
570 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000571
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000572 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000573 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000574 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000575 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000576
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000577 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000578 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000579
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000580 Deny reading anything outside the repository.
581 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000582 if isinstance(file_item, AffectedFile):
583 file_item = file_item.AbsoluteLocalPath()
584 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000585 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000586 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000587
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100588 def CreateTemporaryFile(self, **kwargs):
589 """Returns a named temporary file that must be removed with a call to
590 RemoveTemporaryFiles().
591
592 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
593 except for |delete|, which is always set to False.
594
595 Presubmit checks that need to create a temporary file and pass it for
596 reading should use this function instead of NamedTemporaryFile(), as
597 Windows fails to open a file that is already open for writing.
598
599 with input_api.CreateTemporaryFile() as f:
600 f.write('xyz')
601 f.close()
602 input_api.subprocess.check_output(['script-that', '--reads-from',
603 f.name])
604
605
606 Note that callers of CreateTemporaryFile() should not worry about removing
607 any temporary file; this is done transparently by the presubmit handling
608 code.
609 """
610 if 'delete' in kwargs:
611 # Prevent users from passing |delete|; we take care of file deletion
612 # ourselves and this prevents unintuitive error messages when we pass
613 # delete=False and 'delete' is also in kwargs.
614 raise TypeError('CreateTemporaryFile() does not take a "delete" '
615 'argument, file deletion is handled automatically by '
616 'the same presubmit_support code that creates InputApi '
617 'objects.')
618 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
619 self._named_temporary_files.append(temp_file.name)
620 return temp_file
621
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000622 @property
623 def tbr(self):
624 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400625 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000626
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000627 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000628 tests = []
629 msgs = []
630 for t in tests_mix:
631 if isinstance(t, OutputApi.PresubmitResult):
632 msgs.append(t)
633 else:
634 assert issubclass(t.message, _PresubmitResult)
635 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000636 if self.verbose:
637 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000638 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000639 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000640 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000641 else:
642 msgs.extend(map(CallCommand, tests))
643 return [m for m in msgs if m]
644
scottmg86099d72016-09-01 09:16:51 -0700645 def ShutdownPool(self):
646 self._run_tests_pool.close()
647 self._run_tests_pool.join()
648 self._run_tests_pool = None
649
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000650
nick@chromium.orgff526192013-06-10 19:30:26 +0000651class _DiffCache(object):
652 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000653 def __init__(self, upstream=None):
654 """Stores the upstream revision against which all diffs will be computed."""
655 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000656
657 def GetDiff(self, path, local_root):
658 """Get the diff for a particular path."""
659 raise NotImplementedError()
660
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700661 def GetOldContents(self, path, local_root):
662 """Get the old version for a particular path."""
663 raise NotImplementedError()
664
nick@chromium.orgff526192013-06-10 19:30:26 +0000665
nick@chromium.orgff526192013-06-10 19:30:26 +0000666class _GitDiffCache(_DiffCache):
667 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000668 def __init__(self, upstream):
669 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000670 self._diffs_by_file = None
671
672 def GetDiff(self, path, local_root):
673 if not self._diffs_by_file:
674 # Compute a single diff for all files and parse the output; should
675 # with git this is much faster than computing one diff for each file.
676 diffs = {}
677
678 # Don't specify any filenames below, because there are command line length
679 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000680 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
681 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000682
683 # This regex matches the path twice, separated by a space. Note that
684 # filename itself may contain spaces.
685 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
686 current_diff = []
687 keep_line_endings = True
688 for x in unified_diff.splitlines(keep_line_endings):
689 match = file_marker.match(x)
690 if match:
691 # Marks the start of a new per-file section.
692 diffs[match.group('filename')] = current_diff = [x]
693 elif x.startswith('diff --git'):
694 raise PresubmitFailure('Unexpected diff line: %s' % x)
695 else:
696 current_diff.append(x)
697
698 self._diffs_by_file = dict(
699 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
700
701 if path not in self._diffs_by_file:
702 raise PresubmitFailure(
703 'Unified diff did not contain entry for file %s' % path)
704
705 return self._diffs_by_file[path]
706
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700707 def GetOldContents(self, path, local_root):
708 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
709
nick@chromium.orgff526192013-06-10 19:30:26 +0000710
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000711class AffectedFile(object):
712 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000713
714 DIFF_CACHE = _DiffCache
715
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000716 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800717 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000718 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000719 self._path = path
720 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000721 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000722 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000723 self._cached_changed_contents = None
724 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000725 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700726 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000727
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000728 def LocalPath(self):
729 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400730
731 This should be used for error messages but not for accessing files,
732 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
733 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000734 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000735 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000736
737 def AbsoluteLocalPath(self):
738 """Returns the absolute path of this file on the local disk.
739 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000740 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000741
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000742 def Action(self):
743 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000744 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000745
agable0b65e732016-11-22 09:25:46 -0800746 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000747 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000748
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000749 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000750 raise NotImplementedError() # Implement when needed
751
agable0b65e732016-11-22 09:25:46 -0800752 def IsTextFile(self):
753 """An alias to IsTestableFile for backwards compatibility."""
754 return self.IsTestableFile()
755
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700756 def OldContents(self):
757 """Returns an iterator over the lines in the old version of file.
758
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700759 The old version is the file before any modifications in the user's
760 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700761
762 Contents will be empty if the file is a directory or does not exist.
763 Note: The carriage returns (LF or CR) are stripped off.
764 """
765 return self._diff_cache.GetOldContents(self.LocalPath(),
766 self._local_root).splitlines()
767
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000768 def NewContents(self):
769 """Returns an iterator over the lines in the new version of file.
770
771 The new version is the file in the user's workspace, i.e. the "right hand
772 side".
773
774 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000775 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000776 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000777 if self._cached_new_contents is None:
778 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800779 try:
780 self._cached_new_contents = gclient_utils.FileRead(
781 self.AbsoluteLocalPath(), 'rU').splitlines()
782 except IOError:
783 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000784 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000785
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000786 def ChangedContents(self):
787 """Returns a list of tuples (line number, line text) of all new lines.
788
789 This relies on the scm diff output describing each changed code section
790 with a line of the form
791
792 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
793 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000794 if self._cached_changed_contents is not None:
795 return self._cached_changed_contents[:]
796 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000797 line_num = 0
798
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000799 for line in self.GenerateScmDiff().splitlines():
800 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
801 if m:
802 line_num = int(m.groups(1)[0])
803 continue
804 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000805 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000806 if not line.startswith('-'):
807 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000808 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000809
maruel@chromium.org5de13972009-06-10 18:16:06 +0000810 def __str__(self):
811 return self.LocalPath()
812
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000813 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000814 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000815
maruel@chromium.org58407af2011-04-12 23:15:57 +0000816
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000817class GitAffectedFile(AffectedFile):
818 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000819 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800820 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000821
nick@chromium.orgff526192013-06-10 19:30:26 +0000822 DIFF_CACHE = _GitDiffCache
823
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000824 def __init__(self, *args, **kwargs):
825 AffectedFile.__init__(self, *args, **kwargs)
826 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800827 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000828
agable0b65e732016-11-22 09:25:46 -0800829 def IsTestableFile(self):
830 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000831 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800832 # A deleted file is not testable.
833 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000834 else:
agable0b65e732016-11-22 09:25:46 -0800835 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
836 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000837
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000838
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000839class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000840 """Describe a change.
841
842 Used directly by the presubmit scripts to query the current change being
843 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000844
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000845 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000846 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000847 self.KEY: equivalent to tags['KEY']
848 """
849
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000850 _AFFECTED_FILES = AffectedFile
851
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000852 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000853 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000854 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000855 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000856
maruel@chromium.org58407af2011-04-12 23:15:57 +0000857 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000858 self, name, description, local_root, files, issue, patchset, author,
859 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000860 if files is None:
861 files = []
862 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000863 # Convert root into an absolute path.
864 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000865 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000866 self.issue = issue
867 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000868 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000869
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000870 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000872 self._description_without_tags = ''
873 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000874
maruel@chromium.orge085d812011-10-10 19:49:15 +0000875 assert all(
876 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
877
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000878 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000879 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000880 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
881 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000882 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000883
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000884 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000885 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000886 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000887
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000888 def DescriptionText(self):
889 """Returns the user-entered changelist description, minus tags.
890
891 Any line in the user-provided description starting with e.g. "FOO="
892 (whitespace permitted before and around) is considered a tag line. Such
893 lines are stripped out of the description this function returns.
894 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000895 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896
897 def FullDescriptionText(self):
898 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000899 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000900
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000901 def SetDescriptionText(self, description):
902 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000903
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000904 Also updates the list of tags."""
905 self._full_description = description
906
907 # From the description text, build up a dictionary of key/value pairs
908 # plus the description minus all key/value or "tag" lines.
909 description_without_tags = []
910 self.tags = {}
911 for line in self._full_description.splitlines():
912 m = self.TAG_LINE_RE.match(line)
913 if m:
914 self.tags[m.group('key')] = m.group('value')
915 else:
916 description_without_tags.append(line)
917
918 # Change back to text and remove whitespace at end.
919 self._description_without_tags = (
920 '\n'.join(description_without_tags).rstrip())
921
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000922 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000923 """Returns the repository (checkout) root directory for this change,
924 as an absolute path.
925 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000926 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000927
928 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000929 """Return tags directly as attributes on the object."""
930 if not re.match(r"^[A-Z_]*$", attr):
931 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000932 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000933
Aaron Gablefc03e672017-05-15 14:09:42 -0700934 def BugsFromDescription(self):
935 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700936 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
937 footers = git_footers.parse_footers(self._full_description).get('Bug', [])
938 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700939
940 def ReviewersFromDescription(self):
941 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700942 # We don't support a "R:" git-footer for reviewers; that is in metadata.
943 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
944 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -0700945
946 def TBRsFromDescription(self):
947 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700948 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
949 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
950 # determined by self-CR+1s.
951 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
952 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700953
954 # TODO(agable): Delete these once we're sure they're unused.
955 @property
956 def BUG(self):
957 return ','.join(self.BugsFromDescription())
958 @property
959 def R(self):
960 return ','.join(self.ReviewersFromDescription())
961 @property
962 def TBR(self):
963 return ','.join(self.TBRsFromDescription())
964
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000965 def AllFiles(self, root=None):
966 """List all files under source control in the repo."""
967 raise NotImplementedError()
968
agable0b65e732016-11-22 09:25:46 -0800969 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000970 """Returns a list of AffectedFile instances for all files in the change.
971
972 Args:
973 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +0000974 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000975
976 Returns:
977 [AffectedFile(path, action), AffectedFile(path, action)]
978 """
agable0b65e732016-11-22 09:25:46 -0800979 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +0000980
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000981 if include_deletes:
982 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -0700983 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000984
agable0b65e732016-11-22 09:25:46 -0800985 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000986 """Return a list of the existing text files in a change."""
987 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800988 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000989 " is deprecated and ignored" % str(include_deletes),
990 category=DeprecationWarning,
991 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800992 return filter(lambda x: x.IsTestableFile(),
993 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000994
agable0b65e732016-11-22 09:25:46 -0800995 def AffectedTextFiles(self, include_deletes=None):
996 """An alias to AffectedTestableFiles for backwards compatibility."""
997 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000998
agable0b65e732016-11-22 09:25:46 -0800999 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001001 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001002
agable0b65e732016-11-22 09:25:46 -08001003 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001005 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001006
1007 def RightHandSideLines(self):
1008 """An iterator over all text lines in "new" version of changed files.
1009
1010 Lists lines from new or modified text files in the change.
1011
1012 This is useful for doing line-by-line regex checks, like checking for
1013 trailing whitespace.
1014
1015 Yields:
1016 a 3 tuple:
1017 the AffectedFile instance of the current file;
1018 integer line number (1-based); and
1019 the contents of the line as a string.
1020 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001021 return _RightHandSideLinesImpl(
1022 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001023 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001024
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001025 def OriginalOwnersFiles(self):
1026 """A map from path names of affected OWNERS files to their old content."""
1027 def owners_file_filter(f):
1028 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1029 files = self.AffectedFiles(file_filter=owners_file_filter)
1030 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1031
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001032
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001033class GitChange(Change):
1034 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001035 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001036
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001037 def AllFiles(self, root=None):
1038 """List all files under source control in the repo."""
1039 root = root or self.RepositoryRoot()
1040 return subprocess.check_output(
Aaron Gable9219d352017-12-07 13:39:11 -08001041 ['git', '-c', 'core,quotePath=false', 'ls-files', '--', '.'],
1042 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001043
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001044
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001045def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001046 """Finds all presubmit files that apply to a given set of source files.
1047
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001048 If inherit-review-settings-ok is present right under root, looks for
1049 PRESUBMIT.py in directories enclosing root.
1050
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001051 Args:
1052 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001053 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001054
1055 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001056 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001057 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001058 files = [normpath(os.path.join(root, f)) for f in files]
1059
1060 # List all the individual directories containing files.
1061 directories = set([os.path.dirname(f) for f in files])
1062
1063 # Ignore root if inherit-review-settings-ok is present.
1064 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1065 root = None
1066
1067 # Collect all unique directories that may contain PRESUBMIT.py.
1068 candidates = set()
1069 for directory in directories:
1070 while True:
1071 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001072 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001073 candidates.add(directory)
1074 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001075 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001076 parent_dir = os.path.dirname(directory)
1077 if parent_dir == directory:
1078 # We hit the system root directory.
1079 break
1080 directory = parent_dir
1081
1082 # Look for PRESUBMIT.py in all candidate directories.
1083 results = []
1084 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001085 try:
1086 for f in os.listdir(directory):
1087 p = os.path.join(directory, f)
1088 if os.path.isfile(p) and re.match(
1089 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1090 results.append(p)
1091 except OSError:
1092 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001093
tobiasjs2836bcf2016-08-16 04:08:16 -07001094 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001095 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001096
1097
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001098class GetTryMastersExecuter(object):
1099 @staticmethod
1100 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1101 """Executes GetPreferredTryMasters() from a single presubmit script.
1102
1103 Args:
1104 script_text: The text of the presubmit script.
1105 presubmit_path: Project script to run.
1106 project: Project name to pass to presubmit script for bot selection.
1107
1108 Return:
1109 A map of try masters to map of builders to set of tests.
1110 """
1111 context = {}
1112 try:
1113 exec script_text in context
1114 except Exception, e:
1115 raise PresubmitFailure('"%s" had an exception.\n%s'
1116 % (presubmit_path, e))
1117
1118 function_name = 'GetPreferredTryMasters'
1119 if function_name not in context:
1120 return {}
1121 get_preferred_try_masters = context[function_name]
1122 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1123 raise PresubmitFailure(
1124 'Expected function "GetPreferredTryMasters" to take two arguments.')
1125 return get_preferred_try_masters(project, change)
1126
1127
rmistry@google.com5626a922015-02-26 14:03:30 +00001128class GetPostUploadExecuter(object):
1129 @staticmethod
1130 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1131 """Executes PostUploadHook() from a single presubmit script.
1132
1133 Args:
1134 script_text: The text of the presubmit script.
1135 presubmit_path: Project script to run.
1136 cl: The Changelist object.
1137 change: The Change object.
1138
1139 Return:
1140 A list of results objects.
1141 """
1142 context = {}
1143 try:
1144 exec script_text in context
1145 except Exception, e:
1146 raise PresubmitFailure('"%s" had an exception.\n%s'
1147 % (presubmit_path, e))
1148
1149 function_name = 'PostUploadHook'
1150 if function_name not in context:
1151 return {}
1152 post_upload_hook = context[function_name]
1153 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1154 raise PresubmitFailure(
1155 'Expected function "PostUploadHook" to take three arguments.')
1156 return post_upload_hook(cl, change, OutputApi(False))
1157
1158
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001159def _MergeMasters(masters1, masters2):
1160 """Merges two master maps. Merges also the tests of each builder."""
1161 result = {}
1162 for (master, builders) in itertools.chain(masters1.iteritems(),
1163 masters2.iteritems()):
1164 new_builders = result.setdefault(master, {})
1165 for (builder, tests) in builders.iteritems():
1166 new_builders.setdefault(builder, set([])).update(tests)
1167 return result
1168
1169
1170def DoGetTryMasters(change,
1171 changed_files,
1172 repository_root,
1173 default_presubmit,
1174 project,
1175 verbose,
1176 output_stream):
1177 """Get the list of try masters from the presubmit scripts.
1178
1179 Args:
1180 changed_files: List of modified files.
1181 repository_root: The repository root.
1182 default_presubmit: A default presubmit script to execute in any case.
1183 project: Optional name of a project used in selecting trybots.
1184 verbose: Prints debug info.
1185 output_stream: A stream to write debug output to.
1186
1187 Return:
1188 Map of try masters to map of builders to set of tests.
1189 """
1190 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1191 if not presubmit_files and verbose:
1192 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1193 results = {}
1194 executer = GetTryMastersExecuter()
1195
1196 if default_presubmit:
1197 if verbose:
1198 output_stream.write("Running default presubmit script.\n")
1199 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1200 results = _MergeMasters(results, executer.ExecPresubmitScript(
1201 default_presubmit, fake_path, project, change))
1202 for filename in presubmit_files:
1203 filename = os.path.abspath(filename)
1204 if verbose:
1205 output_stream.write("Running %s\n" % filename)
1206 # Accept CRLF presubmit script.
1207 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1208 results = _MergeMasters(results, executer.ExecPresubmitScript(
1209 presubmit_script, filename, project, change))
1210
1211 # Make sets to lists again for later JSON serialization.
1212 for builders in results.itervalues():
1213 for builder in builders:
1214 builders[builder] = list(builders[builder])
1215
1216 if results and verbose:
1217 output_stream.write('%s\n' % str(results))
1218 return results
1219
1220
rmistry@google.com5626a922015-02-26 14:03:30 +00001221def DoPostUploadExecuter(change,
1222 cl,
1223 repository_root,
1224 verbose,
1225 output_stream):
1226 """Execute the post upload hook.
1227
1228 Args:
1229 change: The Change object.
1230 cl: The Changelist object.
1231 repository_root: The repository root.
1232 verbose: Prints debug info.
1233 output_stream: A stream to write debug output to.
1234 """
1235 presubmit_files = ListRelevantPresubmitFiles(
1236 change.LocalPaths(), repository_root)
1237 if not presubmit_files and verbose:
1238 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1239 results = []
1240 executer = GetPostUploadExecuter()
1241 # The root presubmit file should be executed after the ones in subdirectories.
1242 # i.e. the specific post upload hooks should run before the general ones.
1243 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1244 presubmit_files.reverse()
1245
1246 for filename in presubmit_files:
1247 filename = os.path.abspath(filename)
1248 if verbose:
1249 output_stream.write("Running %s\n" % filename)
1250 # Accept CRLF presubmit script.
1251 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1252 results.extend(executer.ExecPresubmitScript(
1253 presubmit_script, filename, cl, change))
1254 output_stream.write('\n')
1255 if results:
1256 output_stream.write('** Post Upload Hook Messages **\n')
1257 for result in results:
1258 result.handle(output_stream)
1259 output_stream.write('\n')
1260
1261 return results
1262
1263
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001264class PresubmitExecuter(object):
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001265 def __init__(self, change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001266 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001267 """
1268 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001269 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001270 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001271 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001272 gerrit_obj: provides basic Gerrit codereview functionality.
1273 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001274 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001275 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001276 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001277 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001278 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001279 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001280 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001281 self.more_cc = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001282
1283 def ExecPresubmitScript(self, script_text, presubmit_path):
1284 """Executes a single presubmit script.
1285
1286 Args:
1287 script_text: The text of the presubmit script.
1288 presubmit_path: The path to the presubmit file (this will be reported via
1289 input_api.PresubmitLocalPath()).
1290
1291 Return:
1292 A list of result objects, empty if no problems.
1293 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001294
chase@chromium.org8e416c82009-10-06 04:30:44 +00001295 # Change to the presubmit file's directory to support local imports.
1296 main_path = os.getcwd()
1297 os.chdir(os.path.dirname(presubmit_path))
1298
1299 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001300 input_api = InputApi(self.change, presubmit_path, self.committing,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001301 self.rietveld, self.verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001302 gerrit_obj=self.gerrit, dry_run=self.dry_run)
Daniel Cheng7227d212017-11-17 08:12:37 -08001303 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001304 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001305 try:
1306 exec script_text in context
1307 except Exception, e:
1308 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001309
1310 # These function names must change if we make substantial changes to
1311 # the presubmit API that are not backwards compatible.
1312 if self.committing:
1313 function_name = 'CheckChangeOnCommit'
1314 else:
1315 function_name = 'CheckChangeOnUpload'
1316 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001317 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001318 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001319 logging.debug('Running %s in %s', function_name, presubmit_path)
1320 result = eval(function_name + '(*__args)', context)
1321 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001322 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001323 finally:
1324 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001325 if not (isinstance(result, types.TupleType) or
1326 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001327 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001328 'Presubmit functions must return a tuple or list')
1329 for item in result:
1330 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001331 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001332 'All presubmit results must be of types derived from '
1333 'output_api.PresubmitResult')
1334 else:
1335 result = () # no error since the script doesn't care about current event.
1336
scottmg86099d72016-09-01 09:16:51 -07001337 input_api.ShutdownPool()
1338
chase@chromium.org8e416c82009-10-06 04:30:44 +00001339 # Return the process to the original working directory.
1340 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001341 return result
1342
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001343def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001344 committing,
1345 verbose,
1346 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001347 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001348 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001349 may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001350 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001351 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001352 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001353 """Runs all presubmit checks that apply to the files in the change.
1354
1355 This finds all PRESUBMIT.py files in directories enclosing the files in the
1356 change (up to the repository root) and calls the relevant entrypoint function
1357 depending on whether the change is being committed or uploaded.
1358
1359 Prints errors, warnings and notifications. Prompts the user for warnings
1360 when needed.
1361
1362 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001363 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001364 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001365 verbose: Prints debug info.
1366 output_stream: A stream to write output from presubmit tests to.
1367 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001368 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001369 may_prompt: Enable (y/n) questions on warning or error. If False,
1370 any questions are answered with yes by default.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001371 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001372 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001373 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001374
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001375 Warning:
1376 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1377 SHOULD be sys.stdin.
1378
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001379 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001380 A PresubmitOutput object. Use output.should_continue() to figure out
1381 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001382 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001383 old_environ = os.environ
1384 try:
1385 # Make sure python subprocesses won't generate .pyc files.
1386 os.environ = os.environ.copy()
1387 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001388
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001389 output = PresubmitOutput(input_stream, output_stream)
1390 if committing:
1391 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001392 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001393 output.write("Running presubmit upload checks ...\n")
1394 start_time = time.time()
1395 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001396 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001397 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001398 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001399 results = []
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001400 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001401 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001402 if default_presubmit:
1403 if verbose:
1404 output.write("Running default presubmit script.\n")
1405 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1406 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1407 for filename in presubmit_files:
1408 filename = os.path.abspath(filename)
1409 if verbose:
1410 output.write("Running %s\n" % filename)
1411 # Accept CRLF presubmit script.
1412 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1413 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001414
Daniel Cheng7227d212017-11-17 08:12:37 -08001415 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001416 errors = []
1417 notifications = []
1418 warnings = []
1419 for result in results:
1420 if result.fatal:
1421 errors.append(result)
1422 elif result.should_prompt:
1423 warnings.append(result)
1424 else:
1425 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001426
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001427 output.write('\n')
1428 for name, items in (('Messages', notifications),
1429 ('Warnings', warnings),
1430 ('ERRORS', errors)):
1431 if items:
1432 output.write('** Presubmit %s **\n' % name)
1433 for item in items:
1434 item.handle(output)
1435 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001436
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001437 total_time = time.time() - start_time
1438 if total_time > 1.0:
1439 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001440
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001441 if errors:
1442 output.fail()
1443 elif warnings:
1444 output.write('There were presubmit warnings. ')
1445 if may_prompt:
1446 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1447 else:
1448 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001449
1450 global _ASKED_FOR_FEEDBACK
1451 # Ask for feedback one time out of 5.
1452 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001453 output.write(
1454 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1455 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1456 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001457 _ASKED_FOR_FEEDBACK = True
1458 return output
1459 finally:
1460 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001461
1462
1463def ScanSubDirs(mask, recursive):
1464 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001465 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001466
1467 results = []
1468 for root, dirs, files in os.walk('.'):
1469 if '.svn' in dirs:
1470 dirs.remove('.svn')
1471 if '.git' in dirs:
1472 dirs.remove('.git')
1473 for name in files:
1474 if fnmatch.fnmatch(name, mask):
1475 results.append(os.path.join(root, name))
1476 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001477
1478
1479def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001480 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001481 files = []
1482 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001483 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001484 return files
1485
1486
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001487def load_files(options, args):
1488 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001489 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001490 if args:
1491 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001492 change_scm = scm.determine_scm(options.root)
1493 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001494 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001495 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001496 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001497 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001498 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001499 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001500 if not files:
1501 return None, None
1502 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001503 return change_class, files
1504
1505
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001506class NonexistantCannedCheckFilter(Exception):
1507 pass
1508
1509
1510@contextlib.contextmanager
1511def canned_check_filter(method_names):
1512 filtered = {}
1513 try:
1514 for method_name in method_names:
1515 if not hasattr(presubmit_canned_checks, method_name):
1516 raise NonexistantCannedCheckFilter(method_name)
1517 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1518 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1519 yield
1520 finally:
1521 for name, method in filtered.iteritems():
1522 setattr(presubmit_canned_checks, name, method)
1523
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001524
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001525def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001526 """Runs an external program, potentially from a child process created by the
1527 multiprocessing module.
1528
1529 multiprocessing needs a top level function with a single argument.
1530 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001531 cmd_data.kwargs['stdout'] = subprocess.PIPE
1532 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1533 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001534 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001535 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001536 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001537 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001538 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001539 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001540 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1541 if code != 0:
1542 return cmd_data.message(
1543 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1544 if cmd_data.info:
1545 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001546
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001547
sbc@chromium.org013731e2015-02-26 18:28:43 +00001548def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001549 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001550 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001551 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001552 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001553 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1554 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001555 parser.add_option("-r", "--recursive", action="store_true",
1556 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001557 parser.add_option("-v", "--verbose", action="count", default=0,
1558 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001559 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001560 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001561 parser.add_option("--description", default='')
1562 parser.add_option("--issue", type='int', default=0)
1563 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001564 parser.add_option("--root", default=os.getcwd(),
1565 help="Search for PRESUBMIT.py up to this directory. "
1566 "If inherit-review-settings-ok is present in this "
1567 "directory, parent directories up to the root file "
1568 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001569 parser.add_option("--upstream",
1570 help="Git only: the base ref or upstream branch against "
1571 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001572 parser.add_option("--default_presubmit")
1573 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001574 parser.add_option("--skip_canned", action='append', default=[],
1575 help="A list of checks to skip which appear in "
1576 "presubmit_canned_checks. Can be provided multiple times "
1577 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001578 parser.add_option("--dry_run", action='store_true',
1579 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001580 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001581 parser.add_option("--gerrit_fetch", action='store_true',
1582 help=optparse.SUPPRESS_HELP)
maruel@chromium.org239f4112011-06-03 20:08:23 +00001583 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1584 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001585 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1586 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001587 # These are for OAuth2 authentication for bots. See also apply_issue.py
1588 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1589 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1590
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001591 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001592 options, args = parser.parse_args(argv)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001593 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001594
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001595 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001596 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001597 elif options.verbose:
1598 logging.basicConfig(level=logging.INFO)
1599 else:
1600 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001601
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001602 if (any((options.rietveld_url, options.rietveld_email_file,
1603 options.rietveld_fetch, options.rietveld_private_key_file))
1604 and any((options.gerrit_url, options.gerrit_fetch))):
1605 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1606 'allowed')
1607
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001608 if options.rietveld_email and options.rietveld_email_file:
1609 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1610 "can be passed to this program.")
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001611 if options.rietveld_email_file:
1612 with open(options.rietveld_email_file, "rb") as f:
1613 options.rietveld_email = f.read().strip()
1614
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001615 change_class, files = load_files(options, args)
1616 if not change_class:
1617 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001618 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001619
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001620 rietveld_obj, gerrit_obj = None, None
1621
maruel@chromium.org239f4112011-06-03 20:08:23 +00001622 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001623 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001624 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001625 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1626 options.rietveld_url,
1627 options.rietveld_email,
1628 options.rietveld_private_key_file)
1629 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001630 rietveld_obj = rietveld.CachingRietveld(
1631 options.rietveld_url,
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001632 auth_config,
1633 options.rietveld_email)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001634 if options.rietveld_fetch:
1635 assert options.issue
1636 props = rietveld_obj.get_issue_properties(options.issue, False)
1637 options.author = props['owner_email']
1638 options.description = props['description']
1639 logging.info('Got author: "%s"', options.author)
1640 logging.info('Got description: """\n%s\n"""', options.description)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001641
1642 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001643 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001644 rietveld_obj = None
1645 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1646 options.author = gerrit_obj.GetChangeOwner(options.issue)
1647 options.description = gerrit_obj.GetChangeDescription(options.issue,
1648 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001649 logging.info('Got author: "%s"', options.author)
1650 logging.info('Got description: """\n%s\n"""', options.description)
1651
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001652 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001653 with canned_check_filter(options.skip_canned):
1654 results = DoPresubmitChecks(
1655 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001656 options.description,
1657 options.root,
1658 files,
1659 options.issue,
1660 options.patchset,
1661 options.author,
1662 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001663 options.commit,
1664 options.verbose,
1665 sys.stdout,
1666 sys.stdin,
1667 options.default_presubmit,
1668 options.may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001669 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001670 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001671 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001672 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001673 except NonexistantCannedCheckFilter, e:
1674 print >> sys.stderr, (
1675 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1676 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001677 except PresubmitFailure, e:
1678 print >> sys.stderr, e
1679 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1680 print >> sys.stderr, 'If all fails, contact maruel@'
1681 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001682
1683
1684if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001685 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001686 try:
1687 sys.exit(main())
1688 except KeyboardInterrupt:
1689 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001690 sys.exit(2)