blob: 5b89a335d8fa6263bd211826f530c2a54af97acf [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.
Aaron Gableaa6ddc62018-04-02 14:54:30 -070044import 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
Aaron Gableaa6ddc62018-04-02 14:54:30 -070052import 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 []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000140 self._long_text = long_text.rstrip()
141
142 def handle(self, output):
143 output.write(self._message)
144 output.write('\n')
145 for index, item in enumerate(self._items):
146 output.write(' ')
147 # Write separately in case it's unicode.
148 output.write(str(item))
149 if index < len(self._items) - 1:
150 output.write(' \\')
151 output.write('\n')
152 if self._long_text:
153 output.write('\n***************\n')
154 # Write separately in case it's unicode.
155 output.write(self._long_text)
156 output.write('\n***************\n')
157 if self.fatal:
158 output.fail()
159
160
161# Top level object so multiprocessing can pickle
162# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000163class _PresubmitError(_PresubmitResult):
164 """A hard presubmit error."""
165 fatal = True
166
167
168# Top level object so multiprocessing can pickle
169# Public access through OutputApi object.
170class _PresubmitPromptWarning(_PresubmitResult):
171 """An warning that prompts the user if they want to continue."""
172 should_prompt = True
173
174
175# Top level object so multiprocessing can pickle
176# Public access through OutputApi object.
177class _PresubmitNotifyResult(_PresubmitResult):
178 """Just print something to the screen -- but it's not even a warning."""
179 pass
180
181
182# Top level object so multiprocessing can pickle
183# Public access through OutputApi object.
184class _MailTextResult(_PresubmitResult):
185 """A warning that should be included in the review request email."""
186 def __init__(self, *args, **kwargs):
187 super(_MailTextResult, self).__init__()
188 raise NotImplementedError()
189
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000190class GerritAccessor(object):
191 """Limited Gerrit functionality for canned presubmit checks to work.
192
193 To avoid excessive Gerrit calls, caches the results.
194 """
195
196 def __init__(self, host):
197 self.host = host
198 self.cache = {}
199
200 def _FetchChangeDetail(self, issue):
201 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100202 try:
203 return gerrit_util.GetChangeDetail(
204 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700205 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100206 except gerrit_util.GerritError as e:
207 if e.http_status == 404:
208 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
209 'no credentials to fetch issue details' % issue)
210 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000211
212 def GetChangeInfo(self, issue):
213 """Returns labels and all revisions (patchsets) for this issue.
214
215 The result is a dictionary according to Gerrit REST Api.
216 https://gerrit-review.googlesource.com/Documentation/rest-api.html
217
218 However, API isn't very clear what's inside, so see tests for example.
219 """
220 assert issue
221 cache_key = int(issue)
222 if cache_key not in self.cache:
223 self.cache[cache_key] = self._FetchChangeDetail(issue)
224 return self.cache[cache_key]
225
226 def GetChangeDescription(self, issue, patchset=None):
227 """If patchset is none, fetches current patchset."""
228 info = self.GetChangeInfo(issue)
229 # info is a reference to cache. We'll modify it here adding description to
230 # it to the right patchset, if it is not yet there.
231
232 # Find revision info for the patchset we want.
233 if patchset is not None:
234 for rev, rev_info in info['revisions'].iteritems():
235 if str(rev_info['_number']) == str(patchset):
236 break
237 else:
238 raise Exception('patchset %s doesn\'t exist in issue %s' % (
239 patchset, issue))
240 else:
241 rev = info['current_revision']
242 rev_info = info['revisions'][rev]
243
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100244 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000245
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800246 def GetDestRef(self, issue):
247 ref = self.GetChangeInfo(issue)['branch']
248 if not ref.startswith('refs/'):
249 # NOTE: it is possible to create 'refs/x' branch,
250 # aka 'refs/heads/refs/x'. However, this is ill-advised.
251 ref = 'refs/heads/%s' % ref
252 return ref
253
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000254 def GetChangeOwner(self, issue):
255 return self.GetChangeInfo(issue)['owner']['email']
256
257 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700258 changeinfo = self.GetChangeInfo(issue)
259 if approving_only:
260 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
261 values = labelinfo.get('values', {}).keys()
262 try:
263 max_value = max(int(v) for v in values)
264 reviewers = [r for r in labelinfo.get('all', [])
265 if r.get('value', 0) == max_value]
266 except ValueError: # values is the empty list
267 reviewers = []
268 else:
269 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
270 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000271
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000272
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000273class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000274 """An instance of OutputApi gets passed to presubmit scripts so that they
275 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000276 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000277 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000278 PresubmitError = _PresubmitError
279 PresubmitPromptWarning = _PresubmitPromptWarning
280 PresubmitNotifyResult = _PresubmitNotifyResult
281 MailTextResult = _MailTextResult
282
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000283 def __init__(self, is_committing):
284 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800285 self.more_cc = []
286
287 def AppendCC(self, cc):
288 """Appends a user to cc for this change."""
289 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000290
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000291 def PresubmitPromptOrNotify(self, *args, **kwargs):
292 """Warn the user when uploading, but only notify if committing."""
293 if self.is_committing:
294 return self.PresubmitNotifyResult(*args, **kwargs)
295 return self.PresubmitPromptWarning(*args, **kwargs)
296
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800297 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
298 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
299
300 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
301 keeping it alphabetically sorted. Returns the results that should be
302 returned from the PostUploadHook.
303
304 Args:
305 cl: The git_cl.Changelist object.
306 bots_to_include: A list of strings of bots to include, in the form
307 "master:slave".
308 message: A message to be printed in the case that
309 CQ_INCLUDE_TRYBOTS was updated.
310 """
311 description = cl.GetDescription(force=True)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700312 include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)$', re.M | re.I)
313
314 prior_bots = []
315 if cl.IsGerrit():
316 trybot_footers = git_footers.parse_footers(description).get(
317 git_footers.normalize_name('Cq-Include-Trybots'), [])
318 for f in trybot_footers:
319 prior_bots += [b.strip() for b in f.split(';') if b.strip()]
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800320 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700321 trybot_tags = include_re.finditer(description)
322 for t in trybot_tags:
323 prior_bots += [b.strip() for b in t.group(1).split(';') if b.strip()]
324
325 if set(prior_bots) >= set(bots_to_include):
326 return []
327 all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include)))
328
329 if cl.IsGerrit():
330 description = git_footers.remove_footer(
331 description, 'Cq-Include-Trybots')
332 description = git_footers.add_footer(
333 description, 'Cq-Include-Trybots', all_bots,
334 before_keys=['Change-Id'])
335 else:
336 new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % all_bots
337 m = include_re.search(description)
338 if m:
339 description = include_re.sub(new_include_trybots, description)
Kenneth Russelldf6e7342017-04-24 17:07:41 -0700340 else:
Aaron Gableb584c4f2017-04-26 16:28:08 -0700341 description = '%s\n%s\n' % (description, new_include_trybots)
342
343 cl.UpdateDescription(description, force=True)
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800344 return [self.PresubmitNotifyResult(message)]
345
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000346
347class InputApi(object):
348 """An instance of this object is passed to presubmit scripts so they can
349 know stuff about the change they're looking at.
350 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000351 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800352 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000353
maruel@chromium.org3410d912009-06-09 20:56:16 +0000354 # File extensions that are considered source files from a style guide
355 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000356 #
357 # Files without an extension aren't included in the list. If you want to
358 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
359 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000360 DEFAULT_WHITE_LIST = (
361 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000362 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
363 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000364 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000365 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000366 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000367 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000368 )
369
370 # Path regexp that should be excluded from being considered containing source
371 # files. Don't modify this list from a presubmit script!
372 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000373 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000374 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000375 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
376 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000377 # Output directories (just in case)
378 r".*\bDebug[\\\/].*",
379 r".*\bRelease[\\\/].*",
380 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000381 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000382 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000383 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000384 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000385 r"(|.*[\\\/])\.git[\\\/].*",
386 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000387 # There is no point in processing a patch file.
388 r".+\.diff$",
389 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000390 )
391
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000392 def __init__(self, change, presubmit_path, is_committing,
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700393 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000394 """Builds an InputApi object.
395
396 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000397 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000398 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000399 is_committing: True if the change is about to be committed.
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700400 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000401 gerrit_obj: provides basic Gerrit codereview functionality.
402 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000403 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000404 # Version number of the presubmit_support script.
405 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000406 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000407 self.is_committing = is_committing
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700408 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000409 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000410 self.dry_run = dry_run
Aaron Gableaa6ddc62018-04-02 14:54:30 -0700411 # TBD
412 self.host_url = 'http://codereview.chromium.org'
413 if self.rietveld:
414 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000415
416 # We expose various modules and functions as attributes of the input_api
417 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900418 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 self.basename = os.path.basename
420 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000421 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000422 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700423 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000424 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000425 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000426 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000427 self.os_listdir = os.listdir
428 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000429 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000430 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000431 self.pickle = pickle
432 self.marshal = marshal
433 self.re = re
434 self.subprocess = subprocess
435 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000436 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000437 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000438 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000439 self.urllib2 = urllib2
440
Robert Iannucci50258932018-03-19 10:30:59 -0700441 self.is_windows = sys.platform == 'win32'
442
443 # Set python_executable to 'python'. This is interpreted in CallCommand to
444 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
445 # to automatically pick up that repo's .vpython file, instead of inheriting
446 # the one in depot_tools.
447 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000448 self.environ = os.environ
449
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000450 # InputApi.platform is the platform you're currently running on.
451 self.platform = sys.platform
452
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000453 self.cpu_count = multiprocessing.cpu_count()
454
Aaron Gable5254da12017-09-06 21:05:39 +0000455 # this is done here because in RunTests, the current working directory has
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000456 # changed, which causes Pool() to explode fantastically when run on windows
457 # (because it tries to load the __main__ module, which imports lots of
458 # things relative to the current working directory).
Aaron Gable5254da12017-09-06 21:05:39 +0000459 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000460
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000461 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000462 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000463
464 # We carry the canned checks so presubmit scripts can easily use them.
465 self.canned_checks = presubmit_canned_checks
466
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100467 # Temporary files we must manually remove at the end of a run.
468 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200469
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000470 # TODO(dpranke): figure out a list of all approved owners for a repo
471 # in order to be able to handle wildcard OWNERS files?
472 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200473 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200474 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000475 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000476 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000477
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000478 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000479 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000480 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800481 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000482 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000483 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000484 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
485 for (a, b, header) in cpplint._re_pattern_templates
486 ]
487
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000488 def PresubmitLocalPath(self):
489 """Returns the local path of the presubmit script currently being run.
490
491 This is useful if you don't want to hard-code absolute paths in the
492 presubmit script. For example, It can be used to find another file
493 relative to the PRESUBMIT.py script, so the whole tree can be branched and
494 the presubmit script still works, without editing its content.
495 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000496 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000497
agable0b65e732016-11-22 09:25:46 -0800498 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000499 """Same as input_api.change.AffectedFiles() except only lists files
500 (and optionally directories) in the same directory as the current presubmit
501 script, or subdirectories thereof.
502 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000503 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000504 if len(dir_with_slash) == 1:
505 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000506
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000507 return filter(
508 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800509 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000510
agable0b65e732016-11-22 09:25:46 -0800511 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000512 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800513 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000514 logging.debug("LocalPaths: %s", paths)
515 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000516
agable0b65e732016-11-22 09:25:46 -0800517 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000518 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800519 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000520
agable0b65e732016-11-22 09:25:46 -0800521 def AffectedTestableFiles(self, include_deletes=None):
522 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000523 in the same directory as the current presubmit script, or subdirectories
524 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000525 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000526 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800527 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000528 " is deprecated and ignored" % str(include_deletes),
529 category=DeprecationWarning,
530 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800531 return filter(lambda x: x.IsTestableFile(),
532 self.AffectedFiles(include_deletes=False))
533
534 def AffectedTextFiles(self, include_deletes=None):
535 """An alias to AffectedTestableFiles for backwards compatibility."""
536 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000537
maruel@chromium.org3410d912009-06-09 20:56:16 +0000538 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
539 """Filters out files that aren't considered "source file".
540
541 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
542 and InputApi.DEFAULT_BLACK_LIST is used respectively.
543
544 The lists will be compiled as regular expression and
545 AffectedFile.LocalPath() needs to pass both list.
546
547 Note: Copy-paste this function to suit your needs or use a lambda function.
548 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000549 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000550 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000551 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000552 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000553 return True
554 return False
555 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
556 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
557
558 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800559 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000560
561 If source_file is None, InputApi.FilterSourceFile() is used.
562 """
563 if not source_file:
564 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800565 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000566
567 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000568 """An iterator over all text lines in "new" version of changed files.
569
570 Only lists lines from new or modified text files in the change that are
571 contained by the directory of the currently executing presubmit script.
572
573 This is useful for doing line-by-line regex checks, like checking for
574 trailing whitespace.
575
576 Yields:
577 a 3 tuple:
578 the AffectedFile instance of the current file;
579 integer line number (1-based); and
580 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000581
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000582 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000583 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000584 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000585 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000586
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000587 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000588 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000589
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000590 Deny reading anything outside the repository.
591 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000592 if isinstance(file_item, AffectedFile):
593 file_item = file_item.AbsoluteLocalPath()
594 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000595 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000596 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000597
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100598 def CreateTemporaryFile(self, **kwargs):
599 """Returns a named temporary file that must be removed with a call to
600 RemoveTemporaryFiles().
601
602 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
603 except for |delete|, which is always set to False.
604
605 Presubmit checks that need to create a temporary file and pass it for
606 reading should use this function instead of NamedTemporaryFile(), as
607 Windows fails to open a file that is already open for writing.
608
609 with input_api.CreateTemporaryFile() as f:
610 f.write('xyz')
611 f.close()
612 input_api.subprocess.check_output(['script-that', '--reads-from',
613 f.name])
614
615
616 Note that callers of CreateTemporaryFile() should not worry about removing
617 any temporary file; this is done transparently by the presubmit handling
618 code.
619 """
620 if 'delete' in kwargs:
621 # Prevent users from passing |delete|; we take care of file deletion
622 # ourselves and this prevents unintuitive error messages when we pass
623 # delete=False and 'delete' is also in kwargs.
624 raise TypeError('CreateTemporaryFile() does not take a "delete" '
625 'argument, file deletion is handled automatically by '
626 'the same presubmit_support code that creates InputApi '
627 'objects.')
628 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
629 self._named_temporary_files.append(temp_file.name)
630 return temp_file
631
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000632 @property
633 def tbr(self):
634 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400635 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000636
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000637 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000638 tests = []
639 msgs = []
640 for t in tests_mix:
641 if isinstance(t, OutputApi.PresubmitResult):
642 msgs.append(t)
643 else:
644 assert issubclass(t.message, _PresubmitResult)
645 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000646 if self.verbose:
647 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000648 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000649 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000650 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000651 else:
652 msgs.extend(map(CallCommand, tests))
653 return [m for m in msgs if m]
654
scottmg86099d72016-09-01 09:16:51 -0700655 def ShutdownPool(self):
656 self._run_tests_pool.close()
657 self._run_tests_pool.join()
658 self._run_tests_pool = None
659
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000660
nick@chromium.orgff526192013-06-10 19:30:26 +0000661class _DiffCache(object):
662 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000663 def __init__(self, upstream=None):
664 """Stores the upstream revision against which all diffs will be computed."""
665 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000666
667 def GetDiff(self, path, local_root):
668 """Get the diff for a particular path."""
669 raise NotImplementedError()
670
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700671 def GetOldContents(self, path, local_root):
672 """Get the old version for a particular path."""
673 raise NotImplementedError()
674
nick@chromium.orgff526192013-06-10 19:30:26 +0000675
nick@chromium.orgff526192013-06-10 19:30:26 +0000676class _GitDiffCache(_DiffCache):
677 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000678 def __init__(self, upstream):
679 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000680 self._diffs_by_file = None
681
682 def GetDiff(self, path, local_root):
683 if not self._diffs_by_file:
684 # Compute a single diff for all files and parse the output; should
685 # with git this is much faster than computing one diff for each file.
686 diffs = {}
687
688 # Don't specify any filenames below, because there are command line length
689 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000690 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
691 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000692
693 # This regex matches the path twice, separated by a space. Note that
694 # filename itself may contain spaces.
695 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
696 current_diff = []
697 keep_line_endings = True
698 for x in unified_diff.splitlines(keep_line_endings):
699 match = file_marker.match(x)
700 if match:
701 # Marks the start of a new per-file section.
702 diffs[match.group('filename')] = current_diff = [x]
703 elif x.startswith('diff --git'):
704 raise PresubmitFailure('Unexpected diff line: %s' % x)
705 else:
706 current_diff.append(x)
707
708 self._diffs_by_file = dict(
709 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
710
711 if path not in self._diffs_by_file:
712 raise PresubmitFailure(
713 'Unified diff did not contain entry for file %s' % path)
714
715 return self._diffs_by_file[path]
716
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700717 def GetOldContents(self, path, local_root):
718 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
719
nick@chromium.orgff526192013-06-10 19:30:26 +0000720
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000721class AffectedFile(object):
722 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000723
724 DIFF_CACHE = _DiffCache
725
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000726 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800727 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000728 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000729 self._path = path
730 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000731 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000732 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000733 self._cached_changed_contents = None
734 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000735 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700736 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000737
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000738 def LocalPath(self):
739 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400740
741 This should be used for error messages but not for accessing files,
742 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
743 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000744 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000745 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000746
747 def AbsoluteLocalPath(self):
748 """Returns the absolute path of this file on the local disk.
749 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000750 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000751
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000752 def Action(self):
753 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000754 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000755
agable0b65e732016-11-22 09:25:46 -0800756 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000757 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000758
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000759 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000760 raise NotImplementedError() # Implement when needed
761
agable0b65e732016-11-22 09:25:46 -0800762 def IsTextFile(self):
763 """An alias to IsTestableFile for backwards compatibility."""
764 return self.IsTestableFile()
765
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700766 def OldContents(self):
767 """Returns an iterator over the lines in the old version of file.
768
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700769 The old version is the file before any modifications in the user's
770 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700771
772 Contents will be empty if the file is a directory or does not exist.
773 Note: The carriage returns (LF or CR) are stripped off.
774 """
775 return self._diff_cache.GetOldContents(self.LocalPath(),
776 self._local_root).splitlines()
777
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000778 def NewContents(self):
779 """Returns an iterator over the lines in the new version of file.
780
781 The new version is the file in the user's workspace, i.e. the "right hand
782 side".
783
784 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000785 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000786 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000787 if self._cached_new_contents is None:
788 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800789 try:
790 self._cached_new_contents = gclient_utils.FileRead(
791 self.AbsoluteLocalPath(), 'rU').splitlines()
792 except IOError:
793 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000794 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000795
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000796 def ChangedContents(self):
797 """Returns a list of tuples (line number, line text) of all new lines.
798
799 This relies on the scm diff output describing each changed code section
800 with a line of the form
801
802 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
803 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000804 if self._cached_changed_contents is not None:
805 return self._cached_changed_contents[:]
806 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000807 line_num = 0
808
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000809 for line in self.GenerateScmDiff().splitlines():
810 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
811 if m:
812 line_num = int(m.groups(1)[0])
813 continue
814 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000815 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000816 if not line.startswith('-'):
817 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000818 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000819
maruel@chromium.org5de13972009-06-10 18:16:06 +0000820 def __str__(self):
821 return self.LocalPath()
822
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000823 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000824 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000825
maruel@chromium.org58407af2011-04-12 23:15:57 +0000826
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000827class GitAffectedFile(AffectedFile):
828 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000829 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800830 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000831
nick@chromium.orgff526192013-06-10 19:30:26 +0000832 DIFF_CACHE = _GitDiffCache
833
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000834 def __init__(self, *args, **kwargs):
835 AffectedFile.__init__(self, *args, **kwargs)
836 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800837 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000838
agable0b65e732016-11-22 09:25:46 -0800839 def IsTestableFile(self):
840 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000841 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800842 # A deleted file is not testable.
843 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000844 else:
agable0b65e732016-11-22 09:25:46 -0800845 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
846 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000847
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000848
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000849class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000850 """Describe a change.
851
852 Used directly by the presubmit scripts to query the current change being
853 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000854
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000855 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000856 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000857 self.KEY: equivalent to tags['KEY']
858 """
859
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000860 _AFFECTED_FILES = AffectedFile
861
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000862 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000863 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000864 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000865 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000866
maruel@chromium.org58407af2011-04-12 23:15:57 +0000867 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000868 self, name, description, local_root, files, issue, patchset, author,
869 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000870 if files is None:
871 files = []
872 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000873 # Convert root into an absolute path.
874 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000875 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000876 self.issue = issue
877 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000878 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000879
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000880 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000881 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000882 self._description_without_tags = ''
883 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000884
maruel@chromium.orge085d812011-10-10 19:49:15 +0000885 assert all(
886 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
887
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000888 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000889 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000890 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
891 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000892 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000893
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000894 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000895 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000896 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000897
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 def DescriptionText(self):
899 """Returns the user-entered changelist description, minus tags.
900
901 Any line in the user-provided description starting with e.g. "FOO="
902 (whitespace permitted before and around) is considered a tag line. Such
903 lines are stripped out of the description this function returns.
904 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000905 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000906
907 def FullDescriptionText(self):
908 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000909 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000910
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000911 def SetDescriptionText(self, description):
912 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000913
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000914 Also updates the list of tags."""
915 self._full_description = description
916
917 # From the description text, build up a dictionary of key/value pairs
918 # plus the description minus all key/value or "tag" lines.
919 description_without_tags = []
920 self.tags = {}
921 for line in self._full_description.splitlines():
922 m = self.TAG_LINE_RE.match(line)
923 if m:
924 self.tags[m.group('key')] = m.group('value')
925 else:
926 description_without_tags.append(line)
927
928 # Change back to text and remove whitespace at end.
929 self._description_without_tags = (
930 '\n'.join(description_without_tags).rstrip())
931
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000932 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000933 """Returns the repository (checkout) root directory for this change,
934 as an absolute path.
935 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000936 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000937
938 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000939 """Return tags directly as attributes on the object."""
940 if not re.match(r"^[A-Z_]*$", attr):
941 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000942 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000943
Aaron Gablefc03e672017-05-15 14:09:42 -0700944 def BugsFromDescription(self):
945 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700946 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
947 footers = git_footers.parse_footers(self._full_description).get('Bug', [])
948 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700949
950 def ReviewersFromDescription(self):
951 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700952 # We don't support a "R:" git-footer for reviewers; that is in metadata.
953 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
954 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -0700955
956 def TBRsFromDescription(self):
957 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -0700958 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
959 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
960 # determined by self-CR+1s.
961 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
962 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -0700963
964 # TODO(agable): Delete these once we're sure they're unused.
965 @property
966 def BUG(self):
967 return ','.join(self.BugsFromDescription())
968 @property
969 def R(self):
970 return ','.join(self.ReviewersFromDescription())
971 @property
972 def TBR(self):
973 return ','.join(self.TBRsFromDescription())
974
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000975 def AllFiles(self, root=None):
976 """List all files under source control in the repo."""
977 raise NotImplementedError()
978
agable0b65e732016-11-22 09:25:46 -0800979 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000980 """Returns a list of AffectedFile instances for all files in the change.
981
982 Args:
983 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +0000984 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000985
986 Returns:
987 [AffectedFile(path, action), AffectedFile(path, action)]
988 """
agable0b65e732016-11-22 09:25:46 -0800989 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +0000990
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000991 if include_deletes:
992 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -0700993 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000994
agable0b65e732016-11-22 09:25:46 -0800995 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000996 """Return a list of the existing text files in a change."""
997 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800998 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000999 " is deprecated and ignored" % str(include_deletes),
1000 category=DeprecationWarning,
1001 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -08001002 return filter(lambda x: x.IsTestableFile(),
1003 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004
agable0b65e732016-11-22 09:25:46 -08001005 def AffectedTextFiles(self, include_deletes=None):
1006 """An alias to AffectedTestableFiles for backwards compatibility."""
1007 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001008
agable0b65e732016-11-22 09:25:46 -08001009 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001010 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001011 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001012
agable0b65e732016-11-22 09:25:46 -08001013 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001014 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001015 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001016
1017 def RightHandSideLines(self):
1018 """An iterator over all text lines in "new" version of changed files.
1019
1020 Lists lines from new or modified text files in the change.
1021
1022 This is useful for doing line-by-line regex checks, like checking for
1023 trailing whitespace.
1024
1025 Yields:
1026 a 3 tuple:
1027 the AffectedFile instance of the current file;
1028 integer line number (1-based); and
1029 the contents of the line as a string.
1030 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001031 return _RightHandSideLinesImpl(
1032 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001033 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001034
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001035 def OriginalOwnersFiles(self):
1036 """A map from path names of affected OWNERS files to their old content."""
1037 def owners_file_filter(f):
1038 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1039 files = self.AffectedFiles(file_filter=owners_file_filter)
1040 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1041
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001042
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001043class GitChange(Change):
1044 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001045 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001046
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001047 def AllFiles(self, root=None):
1048 """List all files under source control in the repo."""
1049 root = root or self.RepositoryRoot()
1050 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001051 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1052 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001053
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001054
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001055def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001056 """Finds all presubmit files that apply to a given set of source files.
1057
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001058 If inherit-review-settings-ok is present right under root, looks for
1059 PRESUBMIT.py in directories enclosing root.
1060
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001061 Args:
1062 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001063 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001064
1065 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001066 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001067 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001068 files = [normpath(os.path.join(root, f)) for f in files]
1069
1070 # List all the individual directories containing files.
1071 directories = set([os.path.dirname(f) for f in files])
1072
1073 # Ignore root if inherit-review-settings-ok is present.
1074 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1075 root = None
1076
1077 # Collect all unique directories that may contain PRESUBMIT.py.
1078 candidates = set()
1079 for directory in directories:
1080 while True:
1081 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001082 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001083 candidates.add(directory)
1084 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001085 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001086 parent_dir = os.path.dirname(directory)
1087 if parent_dir == directory:
1088 # We hit the system root directory.
1089 break
1090 directory = parent_dir
1091
1092 # Look for PRESUBMIT.py in all candidate directories.
1093 results = []
1094 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001095 try:
1096 for f in os.listdir(directory):
1097 p = os.path.join(directory, f)
1098 if os.path.isfile(p) and re.match(
1099 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1100 results.append(p)
1101 except OSError:
1102 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001103
tobiasjs2836bcf2016-08-16 04:08:16 -07001104 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001105 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001106
1107
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001108class GetTryMastersExecuter(object):
1109 @staticmethod
1110 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1111 """Executes GetPreferredTryMasters() from a single presubmit script.
1112
1113 Args:
1114 script_text: The text of the presubmit script.
1115 presubmit_path: Project script to run.
1116 project: Project name to pass to presubmit script for bot selection.
1117
1118 Return:
1119 A map of try masters to map of builders to set of tests.
1120 """
1121 context = {}
1122 try:
1123 exec script_text in context
1124 except Exception, e:
1125 raise PresubmitFailure('"%s" had an exception.\n%s'
1126 % (presubmit_path, e))
1127
1128 function_name = 'GetPreferredTryMasters'
1129 if function_name not in context:
1130 return {}
1131 get_preferred_try_masters = context[function_name]
1132 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1133 raise PresubmitFailure(
1134 'Expected function "GetPreferredTryMasters" to take two arguments.')
1135 return get_preferred_try_masters(project, change)
1136
1137
rmistry@google.com5626a922015-02-26 14:03:30 +00001138class GetPostUploadExecuter(object):
1139 @staticmethod
1140 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1141 """Executes PostUploadHook() from a single presubmit script.
1142
1143 Args:
1144 script_text: The text of the presubmit script.
1145 presubmit_path: Project script to run.
1146 cl: The Changelist object.
1147 change: The Change object.
1148
1149 Return:
1150 A list of results objects.
1151 """
1152 context = {}
1153 try:
1154 exec script_text in context
1155 except Exception, e:
1156 raise PresubmitFailure('"%s" had an exception.\n%s'
1157 % (presubmit_path, e))
1158
1159 function_name = 'PostUploadHook'
1160 if function_name not in context:
1161 return {}
1162 post_upload_hook = context[function_name]
1163 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1164 raise PresubmitFailure(
1165 'Expected function "PostUploadHook" to take three arguments.')
1166 return post_upload_hook(cl, change, OutputApi(False))
1167
1168
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001169def _MergeMasters(masters1, masters2):
1170 """Merges two master maps. Merges also the tests of each builder."""
1171 result = {}
1172 for (master, builders) in itertools.chain(masters1.iteritems(),
1173 masters2.iteritems()):
1174 new_builders = result.setdefault(master, {})
1175 for (builder, tests) in builders.iteritems():
1176 new_builders.setdefault(builder, set([])).update(tests)
1177 return result
1178
1179
1180def DoGetTryMasters(change,
1181 changed_files,
1182 repository_root,
1183 default_presubmit,
1184 project,
1185 verbose,
1186 output_stream):
1187 """Get the list of try masters from the presubmit scripts.
1188
1189 Args:
1190 changed_files: List of modified files.
1191 repository_root: The repository root.
1192 default_presubmit: A default presubmit script to execute in any case.
1193 project: Optional name of a project used in selecting trybots.
1194 verbose: Prints debug info.
1195 output_stream: A stream to write debug output to.
1196
1197 Return:
1198 Map of try masters to map of builders to set of tests.
1199 """
1200 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1201 if not presubmit_files and verbose:
1202 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1203 results = {}
1204 executer = GetTryMastersExecuter()
1205
1206 if default_presubmit:
1207 if verbose:
1208 output_stream.write("Running default presubmit script.\n")
1209 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1210 results = _MergeMasters(results, executer.ExecPresubmitScript(
1211 default_presubmit, fake_path, project, change))
1212 for filename in presubmit_files:
1213 filename = os.path.abspath(filename)
1214 if verbose:
1215 output_stream.write("Running %s\n" % filename)
1216 # Accept CRLF presubmit script.
1217 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1218 results = _MergeMasters(results, executer.ExecPresubmitScript(
1219 presubmit_script, filename, project, change))
1220
1221 # Make sets to lists again for later JSON serialization.
1222 for builders in results.itervalues():
1223 for builder in builders:
1224 builders[builder] = list(builders[builder])
1225
1226 if results and verbose:
1227 output_stream.write('%s\n' % str(results))
1228 return results
1229
1230
rmistry@google.com5626a922015-02-26 14:03:30 +00001231def DoPostUploadExecuter(change,
1232 cl,
1233 repository_root,
1234 verbose,
1235 output_stream):
1236 """Execute the post upload hook.
1237
1238 Args:
1239 change: The Change object.
1240 cl: The Changelist object.
1241 repository_root: The repository root.
1242 verbose: Prints debug info.
1243 output_stream: A stream to write debug output to.
1244 """
1245 presubmit_files = ListRelevantPresubmitFiles(
1246 change.LocalPaths(), repository_root)
1247 if not presubmit_files and verbose:
1248 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1249 results = []
1250 executer = GetPostUploadExecuter()
1251 # The root presubmit file should be executed after the ones in subdirectories.
1252 # i.e. the specific post upload hooks should run before the general ones.
1253 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1254 presubmit_files.reverse()
1255
1256 for filename in presubmit_files:
1257 filename = os.path.abspath(filename)
1258 if verbose:
1259 output_stream.write("Running %s\n" % filename)
1260 # Accept CRLF presubmit script.
1261 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1262 results.extend(executer.ExecPresubmitScript(
1263 presubmit_script, filename, cl, change))
1264 output_stream.write('\n')
1265 if results:
1266 output_stream.write('** Post Upload Hook Messages **\n')
1267 for result in results:
1268 result.handle(output_stream)
1269 output_stream.write('\n')
1270
1271 return results
1272
1273
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001274class PresubmitExecuter(object):
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001275 def __init__(self, change, committing, rietveld_obj, verbose,
1276 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001277 """
1278 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001279 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001280 committing: True if 'git cl land' is running, False if 'git cl upload' is.
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001281 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001282 gerrit_obj: provides basic Gerrit codereview functionality.
1283 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001284 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001285 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001286 self.committing = committing
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001287 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001288 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001289 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001290 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001291 self.more_cc = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001292
1293 def ExecPresubmitScript(self, script_text, presubmit_path):
1294 """Executes a single presubmit script.
1295
1296 Args:
1297 script_text: The text of the presubmit script.
1298 presubmit_path: The path to the presubmit file (this will be reported via
1299 input_api.PresubmitLocalPath()).
1300
1301 Return:
1302 A list of result objects, empty if no problems.
1303 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001304
chase@chromium.org8e416c82009-10-06 04:30:44 +00001305 # Change to the presubmit file's directory to support local imports.
1306 main_path = os.getcwd()
1307 os.chdir(os.path.dirname(presubmit_path))
1308
1309 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001310 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001311 self.rietveld, self.verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001312 gerrit_obj=self.gerrit, dry_run=self.dry_run)
Daniel Cheng7227d212017-11-17 08:12:37 -08001313 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001314 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001315 try:
1316 exec script_text in context
1317 except Exception, e:
1318 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001319
1320 # These function names must change if we make substantial changes to
1321 # the presubmit API that are not backwards compatible.
1322 if self.committing:
1323 function_name = 'CheckChangeOnCommit'
1324 else:
1325 function_name = 'CheckChangeOnUpload'
1326 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001327 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001328 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001329 logging.debug('Running %s in %s', function_name, presubmit_path)
1330 result = eval(function_name + '(*__args)', context)
1331 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001332 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001333 finally:
1334 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001335 if not (isinstance(result, types.TupleType) or
1336 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001337 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001338 'Presubmit functions must return a tuple or list')
1339 for item in result:
1340 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001341 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001342 'All presubmit results must be of types derived from '
1343 'output_api.PresubmitResult')
1344 else:
1345 result = () # no error since the script doesn't care about current event.
1346
scottmg86099d72016-09-01 09:16:51 -07001347 input_api.ShutdownPool()
1348
chase@chromium.org8e416c82009-10-06 04:30:44 +00001349 # Return the process to the original working directory.
1350 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001351 return result
1352
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001353def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001354 committing,
1355 verbose,
1356 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001357 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001358 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001359 may_prompt,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001360 rietveld_obj,
1361 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001362 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001363 """Runs all presubmit checks that apply to the files in the change.
1364
1365 This finds all PRESUBMIT.py files in directories enclosing the files in the
1366 change (up to the repository root) and calls the relevant entrypoint function
1367 depending on whether the change is being committed or uploaded.
1368
1369 Prints errors, warnings and notifications. Prompts the user for warnings
1370 when needed.
1371
1372 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001373 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001374 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001375 verbose: Prints debug info.
1376 output_stream: A stream to write output from presubmit tests to.
1377 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001378 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001379 may_prompt: Enable (y/n) questions on warning or error. If False,
1380 any questions are answered with yes by default.
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001381 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001382 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001383 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001384
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001385 Warning:
1386 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1387 SHOULD be sys.stdin.
1388
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001389 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001390 A PresubmitOutput object. Use output.should_continue() to figure out
1391 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001392 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001393 old_environ = os.environ
1394 try:
1395 # Make sure python subprocesses won't generate .pyc files.
1396 os.environ = os.environ.copy()
1397 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001398
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001399 output = PresubmitOutput(input_stream, output_stream)
1400 if committing:
1401 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001402 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001403 output.write("Running presubmit upload checks ...\n")
1404 start_time = time.time()
1405 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001406 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001407 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001408 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001409 results = []
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001410 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001411 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001412 if default_presubmit:
1413 if verbose:
1414 output.write("Running default presubmit script.\n")
1415 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1416 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1417 for filename in presubmit_files:
1418 filename = os.path.abspath(filename)
1419 if verbose:
1420 output.write("Running %s\n" % filename)
1421 # Accept CRLF presubmit script.
1422 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1423 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001424
Daniel Cheng7227d212017-11-17 08:12:37 -08001425 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001426 errors = []
1427 notifications = []
1428 warnings = []
1429 for result in results:
1430 if result.fatal:
1431 errors.append(result)
1432 elif result.should_prompt:
1433 warnings.append(result)
1434 else:
1435 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001436
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001437 output.write('\n')
1438 for name, items in (('Messages', notifications),
1439 ('Warnings', warnings),
1440 ('ERRORS', errors)):
1441 if items:
1442 output.write('** Presubmit %s **\n' % name)
1443 for item in items:
1444 item.handle(output)
1445 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001446
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001447 total_time = time.time() - start_time
1448 if total_time > 1.0:
1449 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001450
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001451 if errors:
1452 output.fail()
1453 elif warnings:
1454 output.write('There were presubmit warnings. ')
1455 if may_prompt:
1456 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1457 else:
1458 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001459
1460 global _ASKED_FOR_FEEDBACK
1461 # Ask for feedback one time out of 5.
1462 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001463 output.write(
1464 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1465 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1466 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001467 _ASKED_FOR_FEEDBACK = True
1468 return output
1469 finally:
1470 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001471
1472
1473def ScanSubDirs(mask, recursive):
1474 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001475 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001476
1477 results = []
1478 for root, dirs, files in os.walk('.'):
1479 if '.svn' in dirs:
1480 dirs.remove('.svn')
1481 if '.git' in dirs:
1482 dirs.remove('.git')
1483 for name in files:
1484 if fnmatch.fnmatch(name, mask):
1485 results.append(os.path.join(root, name))
1486 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001487
1488
1489def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001490 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001491 files = []
1492 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001493 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001494 return files
1495
1496
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001497def load_files(options, args):
1498 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001499 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001500 if args:
1501 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001502 change_scm = scm.determine_scm(options.root)
1503 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001504 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001505 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001506 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001507 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001508 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001509 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001510 if not files:
1511 return None, None
1512 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001513 return change_class, files
1514
1515
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001516class NonexistantCannedCheckFilter(Exception):
1517 pass
1518
1519
1520@contextlib.contextmanager
1521def canned_check_filter(method_names):
1522 filtered = {}
1523 try:
1524 for method_name in method_names:
1525 if not hasattr(presubmit_canned_checks, method_name):
1526 raise NonexistantCannedCheckFilter(method_name)
1527 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1528 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1529 yield
1530 finally:
1531 for name, method in filtered.iteritems():
1532 setattr(presubmit_canned_checks, name, method)
1533
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001534
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001535def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001536 """Runs an external program, potentially from a child process created by the
1537 multiprocessing module.
1538
1539 multiprocessing needs a top level function with a single argument.
Robert Iannucci50258932018-03-19 10:30:59 -07001540
1541 This function converts invocation of .py files and invocations of "python" to
1542 vpython invocations.
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001543 """
Robert Iannucci50258932018-03-19 10:30:59 -07001544 vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython'
1545
1546 cmd = cmd_data.cmd
1547 if cmd[0] == 'python':
1548 cmd = list(cmd)
1549 cmd[0] = vpython
1550 elif cmd[0].endswith('.py'):
1551 cmd = [vpython] + cmd
1552
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001553 cmd_data.kwargs['stdout'] = subprocess.PIPE
1554 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1555 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001556 start = time.time()
Robert Iannucci50258932018-03-19 10:30:59 -07001557 (out, _), code = subprocess.communicate(cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001558 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001559 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001560 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001561 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001562 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1563 if code != 0:
1564 return cmd_data.message(
1565 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1566 if cmd_data.info:
1567 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001568
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001569
sbc@chromium.org013731e2015-02-26 18:28:43 +00001570def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001571 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001572 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001573 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001574 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001575 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1576 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001577 parser.add_option("-r", "--recursive", action="store_true",
1578 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001579 parser.add_option("-v", "--verbose", action="count", default=0,
1580 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001581 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001582 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001583 parser.add_option("--description", default='')
1584 parser.add_option("--issue", type='int', default=0)
1585 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001586 parser.add_option("--root", default=os.getcwd(),
1587 help="Search for PRESUBMIT.py up to this directory. "
1588 "If inherit-review-settings-ok is present in this "
1589 "directory, parent directories up to the root file "
1590 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001591 parser.add_option("--upstream",
1592 help="Git only: the base ref or upstream branch against "
1593 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001594 parser.add_option("--default_presubmit")
1595 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001596 parser.add_option("--skip_canned", action='append', default=[],
1597 help="A list of checks to skip which appear in "
1598 "presubmit_canned_checks. Can be provided multiple times "
1599 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001600 parser.add_option("--dry_run", action='store_true',
1601 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001602 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001603 parser.add_option("--gerrit_fetch", action='store_true',
1604 help=optparse.SUPPRESS_HELP)
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001605 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1606 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
1607 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1608 help=optparse.SUPPRESS_HELP)
1609 # These are for OAuth2 authentication for bots. See also apply_issue.py
1610 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1611 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001612
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001613 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001614 options, args = parser.parse_args(argv)
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001615 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001616
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001617 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001618 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001619 elif options.verbose:
1620 logging.basicConfig(level=logging.INFO)
1621 else:
1622 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001623
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001624 if (any((options.rietveld_url, options.rietveld_email_file,
1625 options.rietveld_fetch, options.rietveld_private_key_file))
1626 and any((options.gerrit_url, options.gerrit_fetch))):
1627 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1628 'allowed')
1629
1630 if options.rietveld_email and options.rietveld_email_file:
1631 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1632 "can be passed to this program.")
1633 if options.rietveld_email_file:
1634 with open(options.rietveld_email_file, "rb") as f:
1635 options.rietveld_email = f.read().strip()
1636
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001637 change_class, files = load_files(options, args)
1638 if not change_class:
1639 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001640 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001641
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001642 rietveld_obj, gerrit_obj = None, None
1643
1644 if options.rietveld_url:
1645 # The empty password is permitted: '' is not None.
1646 if options.rietveld_private_key_file:
1647 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1648 options.rietveld_url,
1649 options.rietveld_email,
1650 options.rietveld_private_key_file)
1651 else:
1652 rietveld_obj = rietveld.CachingRietveld(
1653 options.rietveld_url,
1654 auth_config,
1655 options.rietveld_email)
1656 if options.rietveld_fetch:
1657 assert options.issue
1658 props = rietveld_obj.get_issue_properties(options.issue, False)
1659 options.author = props['owner_email']
1660 options.description = props['description']
1661 logging.info('Got author: "%s"', options.author)
1662 logging.info('Got description: """\n%s\n"""', options.description)
1663
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001664 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001665 assert options.issue and options.patchset
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001666 rietveld_obj = None
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001667 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1668 options.author = gerrit_obj.GetChangeOwner(options.issue)
1669 options.description = gerrit_obj.GetChangeDescription(options.issue,
1670 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001671 logging.info('Got author: "%s"', options.author)
1672 logging.info('Got description: """\n%s\n"""', options.description)
1673
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001674 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001675 with canned_check_filter(options.skip_canned):
1676 results = DoPresubmitChecks(
1677 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001678 options.description,
1679 options.root,
1680 files,
1681 options.issue,
1682 options.patchset,
1683 options.author,
1684 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001685 options.commit,
1686 options.verbose,
1687 sys.stdout,
1688 sys.stdin,
1689 options.default_presubmit,
1690 options.may_prompt,
Aaron Gableaa6ddc62018-04-02 14:54:30 -07001691 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001692 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001693 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001694 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001695 except NonexistantCannedCheckFilter, e:
1696 print >> sys.stderr, (
1697 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1698 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001699 except PresubmitFailure, e:
1700 print >> sys.stderr, e
1701 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001702 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001703
1704
1705if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001706 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001707 try:
1708 sys.exit(main())
1709 except KeyboardInterrupt:
1710 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001711 sys.exit(2)