blob: ab43d97f691d16724864546fbc7cb8458eb606f5 [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
enne@chromium.orge72c5f52013-04-16 00:36:40 +000015import cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000016import cPickle # Exposed through the API.
17import cStringIO # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000018import contextlib
dcheng091b7db2016-06-16 01:27:51 -070019import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000020import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000021import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000022import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000023import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000024import logging
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000025import marshal # Exposed through the API.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000026import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000027import optparse
28import os # Somewhat exposed through the API.
29import pickle # Exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000030import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000031import re # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000032import sys # Parts exposed through API.
33import tempfile # Exposed through the API.
jam@chromium.org2a891dc2009-08-20 20:33:37 +000034import time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000035import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000036import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000037import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000038import urllib2 # Exposed through the API.
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000039import urlparse
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000040from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000041
42# Local imports.
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +000043import auth
maruel@chromium.org35625c72011-03-23 17:34:02 +000044import fix_encoding
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000045import gclient_utils
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000046import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000047import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020048import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000049import presubmit_canned_checks
maruel@chromium.org239f4112011-06-03 20:08:23 +000050import rietveld
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000051import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000052import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000053
54
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000055# Ask for feedback only once in program lifetime.
56_ASKED_FOR_FEEDBACK = False
57
58
maruel@chromium.org899e1c12011-04-07 17:03:18 +000059class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000060 pass
61
62
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000063class CommandData(object):
64 def __init__(self, name, cmd, kwargs, message):
65 self.name = name
66 self.cmd = cmd
67 self.kwargs = kwargs
68 self.message = message
69 self.info = None
70
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000071
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000072def normpath(path):
73 '''Version of os.path.normpath that also changes backward slashes to
74 forward slashes when not running on Windows.
75 '''
76 # This is safe to always do because the Windows version of os.path.normpath
77 # will replace forward slashes with backward slashes.
78 path = path.replace(os.sep, '/')
79 return os.path.normpath(path)
80
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000081
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000082def _RightHandSideLinesImpl(affected_files):
83 """Implements RightHandSideLines for InputApi and GclChange."""
84 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000085 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000086 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000087 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000088
89
dpranke@chromium.org5ac21012011-03-16 02:58:25 +000090class PresubmitOutput(object):
91 def __init__(self, input_stream=None, output_stream=None):
92 self.input_stream = input_stream
93 self.output_stream = output_stream
94 self.reviewers = []
95 self.written_output = []
96 self.error_count = 0
97
98 def prompt_yes_no(self, prompt_string):
99 self.write(prompt_string)
100 if self.input_stream:
101 response = self.input_stream.readline().strip().lower()
102 if response not in ('y', 'yes'):
103 self.fail()
104 else:
105 self.fail()
106
107 def fail(self):
108 self.error_count += 1
109
110 def should_continue(self):
111 return not self.error_count
112
113 def write(self, s):
114 self.written_output.append(s)
115 if self.output_stream:
116 self.output_stream.write(s)
117
118 def getvalue(self):
119 return ''.join(self.written_output)
120
121
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000122# Top level object so multiprocessing can pickle
123# Public access through OutputApi object.
124class _PresubmitResult(object):
125 """Base class for result objects."""
126 fatal = False
127 should_prompt = False
128
129 def __init__(self, message, items=None, long_text=''):
130 """
131 message: A short one-line message to indicate errors.
132 items: A list of short strings to indicate where errors occurred.
133 long_text: multi-line text output, e.g. from another tool
134 """
135 self._message = message
136 self._items = items or []
137 if items:
138 self._items = items
139 self._long_text = long_text.rstrip()
140
141 def handle(self, output):
142 output.write(self._message)
143 output.write('\n')
144 for index, item in enumerate(self._items):
145 output.write(' ')
146 # Write separately in case it's unicode.
147 output.write(str(item))
148 if index < len(self._items) - 1:
149 output.write(' \\')
150 output.write('\n')
151 if self._long_text:
152 output.write('\n***************\n')
153 # Write separately in case it's unicode.
154 output.write(self._long_text)
155 output.write('\n***************\n')
156 if self.fatal:
157 output.fail()
158
159
160# Top level object so multiprocessing can pickle
161# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000162class _PresubmitError(_PresubmitResult):
163 """A hard presubmit error."""
164 fatal = True
165
166
167# Top level object so multiprocessing can pickle
168# Public access through OutputApi object.
169class _PresubmitPromptWarning(_PresubmitResult):
170 """An warning that prompts the user if they want to continue."""
171 should_prompt = True
172
173
174# Top level object so multiprocessing can pickle
175# Public access through OutputApi object.
176class _PresubmitNotifyResult(_PresubmitResult):
177 """Just print something to the screen -- but it's not even a warning."""
178 pass
179
180
181# Top level object so multiprocessing can pickle
182# Public access through OutputApi object.
183class _MailTextResult(_PresubmitResult):
184 """A warning that should be included in the review request email."""
185 def __init__(self, *args, **kwargs):
186 super(_MailTextResult, self).__init__()
187 raise NotImplementedError()
188
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000189class GerritAccessor(object):
190 """Limited Gerrit functionality for canned presubmit checks to work.
191
192 To avoid excessive Gerrit calls, caches the results.
193 """
194
195 def __init__(self, host):
196 self.host = host
197 self.cache = {}
198
199 def _FetchChangeDetail(self, issue):
200 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100201 try:
202 return gerrit_util.GetChangeDetail(
203 self.host, str(issue),
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100204 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'],
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100205 ignore_404=False)
206 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
246 def GetChangeOwner(self, issue):
247 return self.GetChangeInfo(issue)['owner']['email']
248
249 def GetChangeReviewers(self, issue, approving_only=True):
agable565adb52016-07-22 14:48:07 -0700250 cr = self.GetChangeInfo(issue)['labels']['Code-Review']
251 max_value = max(int(k) for k in cr['values'].keys())
Aaron Gablef5644a92016-12-02 15:31:58 -0800252 return [r.get('email') for r in cr.get('all', [])
agable565adb52016-07-22 14:48:07 -0700253 if not approving_only or r.get('value', 0) == max_value]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000254
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000255
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000256class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000257 """An instance of OutputApi gets passed to presubmit scripts so that they
258 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000259 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000260 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000261 PresubmitError = _PresubmitError
262 PresubmitPromptWarning = _PresubmitPromptWarning
263 PresubmitNotifyResult = _PresubmitNotifyResult
264 MailTextResult = _MailTextResult
265
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000266 def __init__(self, is_committing):
267 self.is_committing = is_committing
268
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000269 def PresubmitPromptOrNotify(self, *args, **kwargs):
270 """Warn the user when uploading, but only notify if committing."""
271 if self.is_committing:
272 return self.PresubmitNotifyResult(*args, **kwargs)
273 return self.PresubmitPromptWarning(*args, **kwargs)
274
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800275 def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message):
276 """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS.
277
278 Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list,
279 keeping it alphabetically sorted. Returns the results that should be
280 returned from the PostUploadHook.
281
282 Args:
283 cl: The git_cl.Changelist object.
284 bots_to_include: A list of strings of bots to include, in the form
285 "master:slave".
286 message: A message to be printed in the case that
287 CQ_INCLUDE_TRYBOTS was updated.
288 """
289 description = cl.GetDescription(force=True)
290 all_bots = []
291 include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)', re.M | re.I)
292 m = include_re.search(description)
293 if m:
294 all_bots = [i.strip() for i in m.group(1).split(';') if i.strip()]
295 if set(all_bots) >= set(bots_to_include):
296 return []
297 # Sort the bots to keep them in some consistent order -- not required.
298 all_bots = sorted(set(all_bots) | set(bots_to_include))
299 new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % ';'.join(all_bots)
300 if m:
301 new_description = include_re.sub(new_include_trybots, description)
302 else:
303 new_description = description + '\n' + new_include_trybots + '\n'
304 cl.UpdateDescription(new_description, force=True)
305 return [self.PresubmitNotifyResult(message)]
306
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000307
308class InputApi(object):
309 """An instance of this object is passed to presubmit scripts so they can
310 know stuff about the change they're looking at.
311 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000312 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800313 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000314
maruel@chromium.org3410d912009-06-09 20:56:16 +0000315 # File extensions that are considered source files from a style guide
316 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000317 #
318 # Files without an extension aren't included in the list. If you want to
319 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
320 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000321 DEFAULT_WHITE_LIST = (
322 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000323 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
324 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000325 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000326 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000327 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000328 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000329 )
330
331 # Path regexp that should be excluded from being considered containing source
332 # files. Don't modify this list from a presubmit script!
333 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000334 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000335 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000336 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
337 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000338 # Output directories (just in case)
339 r".*\bDebug[\\\/].*",
340 r".*\bRelease[\\\/].*",
341 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000342 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000343 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000344 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000345 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000346 r"(|.*[\\\/])\.git[\\\/].*",
347 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000348 # There is no point in processing a patch file.
349 r".+\.diff$",
350 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000351 )
352
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000353 def __init__(self, change, presubmit_path, is_committing,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000354 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000355 """Builds an InputApi object.
356
357 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000358 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000359 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000360 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000361 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000362 gerrit_obj: provides basic Gerrit codereview functionality.
363 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000364 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000365 # Version number of the presubmit_support script.
366 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000367 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000368 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000369 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000370 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000371 self.dry_run = dry_run
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000372 # TBD
373 self.host_url = 'http://codereview.chromium.org'
374 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000375 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000376
377 # We expose various modules and functions as attributes of the input_api
378 # so that presubmit scripts don't have to import them.
379 self.basename = os.path.basename
380 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000381 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000382 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700383 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000384 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000385 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000386 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000387 self.os_listdir = os.listdir
388 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000389 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000390 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000391 self.pickle = pickle
392 self.marshal = marshal
393 self.re = re
394 self.subprocess = subprocess
395 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000396 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000397 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000398 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000399 self.urllib2 = urllib2
400
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000401 # To easily fork python.
402 self.python_executable = sys.executable
403 self.environ = os.environ
404
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000405 # InputApi.platform is the platform you're currently running on.
406 self.platform = sys.platform
407
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000408 self.cpu_count = multiprocessing.cpu_count()
409
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000410 # this is done here because in RunTests, the current working directory has
411 # changed, which causes Pool() to explode fantastically when run on windows
412 # (because it tries to load the __main__ module, which imports lots of
413 # things relative to the current working directory).
414 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
415
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000416 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000417 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000418
419 # We carry the canned checks so presubmit scripts can easily use them.
420 self.canned_checks = presubmit_canned_checks
421
Jochen Eisinger72606f82017-04-04 10:44:18 +0200422
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000423 # TODO(dpranke): figure out a list of all approved owners for a repo
424 # in order to be able to handle wildcard OWNERS files?
425 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200426 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200427 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000428 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000429 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000430
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000431 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000432 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000433 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800434 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000435 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000436 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000437 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
438 for (a, b, header) in cpplint._re_pattern_templates
439 ]
440
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000441 def PresubmitLocalPath(self):
442 """Returns the local path of the presubmit script currently being run.
443
444 This is useful if you don't want to hard-code absolute paths in the
445 presubmit script. For example, It can be used to find another file
446 relative to the PRESUBMIT.py script, so the whole tree can be branched and
447 the presubmit script still works, without editing its content.
448 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000449 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000450
agable0b65e732016-11-22 09:25:46 -0800451 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000452 """Same as input_api.change.AffectedFiles() except only lists files
453 (and optionally directories) in the same directory as the current presubmit
454 script, or subdirectories thereof.
455 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000456 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000457 if len(dir_with_slash) == 1:
458 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000459
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000460 return filter(
461 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800462 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000463
agable0b65e732016-11-22 09:25:46 -0800464 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000465 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800466 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000467 logging.debug("LocalPaths: %s", paths)
468 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000469
agable0b65e732016-11-22 09:25:46 -0800470 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000471 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800472 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000473
agable0b65e732016-11-22 09:25:46 -0800474 def AffectedTestableFiles(self, include_deletes=None):
475 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000476 in the same directory as the current presubmit script, or subdirectories
477 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000478 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000479 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800480 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000481 " is deprecated and ignored" % str(include_deletes),
482 category=DeprecationWarning,
483 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800484 return filter(lambda x: x.IsTestableFile(),
485 self.AffectedFiles(include_deletes=False))
486
487 def AffectedTextFiles(self, include_deletes=None):
488 """An alias to AffectedTestableFiles for backwards compatibility."""
489 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000490
maruel@chromium.org3410d912009-06-09 20:56:16 +0000491 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
492 """Filters out files that aren't considered "source file".
493
494 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
495 and InputApi.DEFAULT_BLACK_LIST is used respectively.
496
497 The lists will be compiled as regular expression and
498 AffectedFile.LocalPath() needs to pass both list.
499
500 Note: Copy-paste this function to suit your needs or use a lambda function.
501 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000502 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000503 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000504 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000505 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000506 return True
507 return False
508 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
509 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
510
511 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800512 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000513
514 If source_file is None, InputApi.FilterSourceFile() is used.
515 """
516 if not source_file:
517 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800518 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000519
520 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000521 """An iterator over all text lines in "new" version of changed files.
522
523 Only lists lines from new or modified text files in the change that are
524 contained by the directory of the currently executing presubmit script.
525
526 This is useful for doing line-by-line regex checks, like checking for
527 trailing whitespace.
528
529 Yields:
530 a 3 tuple:
531 the AffectedFile instance of the current file;
532 integer line number (1-based); and
533 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000534
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000535 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000536 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000537 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000538 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000539
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000540 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000541 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000542
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000543 Deny reading anything outside the repository.
544 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000545 if isinstance(file_item, AffectedFile):
546 file_item = file_item.AbsoluteLocalPath()
547 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000548 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000549 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000550
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000551 @property
552 def tbr(self):
553 """Returns if a change is TBR'ed."""
554 return 'TBR' in self.change.tags
555
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000556 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000557 tests = []
558 msgs = []
559 for t in tests_mix:
560 if isinstance(t, OutputApi.PresubmitResult):
561 msgs.append(t)
562 else:
563 assert issubclass(t.message, _PresubmitResult)
564 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000565 if self.verbose:
566 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000567 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000568 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000569 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000570 else:
571 msgs.extend(map(CallCommand, tests))
572 return [m for m in msgs if m]
573
scottmg86099d72016-09-01 09:16:51 -0700574 def ShutdownPool(self):
575 self._run_tests_pool.close()
576 self._run_tests_pool.join()
577 self._run_tests_pool = None
578
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000579
nick@chromium.orgff526192013-06-10 19:30:26 +0000580class _DiffCache(object):
581 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000582 def __init__(self, upstream=None):
583 """Stores the upstream revision against which all diffs will be computed."""
584 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000585
586 def GetDiff(self, path, local_root):
587 """Get the diff for a particular path."""
588 raise NotImplementedError()
589
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700590 def GetOldContents(self, path, local_root):
591 """Get the old version for a particular path."""
592 raise NotImplementedError()
593
nick@chromium.orgff526192013-06-10 19:30:26 +0000594
nick@chromium.orgff526192013-06-10 19:30:26 +0000595class _GitDiffCache(_DiffCache):
596 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000597 def __init__(self, upstream):
598 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000599 self._diffs_by_file = None
600
601 def GetDiff(self, path, local_root):
602 if not self._diffs_by_file:
603 # Compute a single diff for all files and parse the output; should
604 # with git this is much faster than computing one diff for each file.
605 diffs = {}
606
607 # Don't specify any filenames below, because there are command line length
608 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000609 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
610 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000611
612 # This regex matches the path twice, separated by a space. Note that
613 # filename itself may contain spaces.
614 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
615 current_diff = []
616 keep_line_endings = True
617 for x in unified_diff.splitlines(keep_line_endings):
618 match = file_marker.match(x)
619 if match:
620 # Marks the start of a new per-file section.
621 diffs[match.group('filename')] = current_diff = [x]
622 elif x.startswith('diff --git'):
623 raise PresubmitFailure('Unexpected diff line: %s' % x)
624 else:
625 current_diff.append(x)
626
627 self._diffs_by_file = dict(
628 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
629
630 if path not in self._diffs_by_file:
631 raise PresubmitFailure(
632 'Unified diff did not contain entry for file %s' % path)
633
634 return self._diffs_by_file[path]
635
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700636 def GetOldContents(self, path, local_root):
637 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
638
nick@chromium.orgff526192013-06-10 19:30:26 +0000639
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000640class AffectedFile(object):
641 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000642
643 DIFF_CACHE = _DiffCache
644
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000645 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800646 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000647 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000648 self._path = path
649 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000650 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000651 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000652 self._cached_changed_contents = None
653 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000654 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700655 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000656
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000657 def LocalPath(self):
658 """Returns the path of this file on the local disk relative to client root.
659 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000660 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000661
662 def AbsoluteLocalPath(self):
663 """Returns the absolute path of this file on the local disk.
664 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000665 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000666
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000667 def Action(self):
668 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000669 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000670
agable0b65e732016-11-22 09:25:46 -0800671 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000672 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000673
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000674 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000675 raise NotImplementedError() # Implement when needed
676
agable0b65e732016-11-22 09:25:46 -0800677 def IsTextFile(self):
678 """An alias to IsTestableFile for backwards compatibility."""
679 return self.IsTestableFile()
680
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700681 def OldContents(self):
682 """Returns an iterator over the lines in the old version of file.
683
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700684 The old version is the file before any modifications in the user's
685 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700686
687 Contents will be empty if the file is a directory or does not exist.
688 Note: The carriage returns (LF or CR) are stripped off.
689 """
690 return self._diff_cache.GetOldContents(self.LocalPath(),
691 self._local_root).splitlines()
692
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000693 def NewContents(self):
694 """Returns an iterator over the lines in the new version of file.
695
696 The new version is the file in the user's workspace, i.e. the "right hand
697 side".
698
699 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000700 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000701 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000702 if self._cached_new_contents is None:
703 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800704 try:
705 self._cached_new_contents = gclient_utils.FileRead(
706 self.AbsoluteLocalPath(), 'rU').splitlines()
707 except IOError:
708 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000709 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000710
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000711 def ChangedContents(self):
712 """Returns a list of tuples (line number, line text) of all new lines.
713
714 This relies on the scm diff output describing each changed code section
715 with a line of the form
716
717 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
718 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000719 if self._cached_changed_contents is not None:
720 return self._cached_changed_contents[:]
721 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000722 line_num = 0
723
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000724 for line in self.GenerateScmDiff().splitlines():
725 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
726 if m:
727 line_num = int(m.groups(1)[0])
728 continue
729 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000730 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000731 if not line.startswith('-'):
732 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000733 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000734
maruel@chromium.org5de13972009-06-10 18:16:06 +0000735 def __str__(self):
736 return self.LocalPath()
737
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000738 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000739 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000740
maruel@chromium.org58407af2011-04-12 23:15:57 +0000741
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000742class GitAffectedFile(AffectedFile):
743 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000744 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800745 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000746
nick@chromium.orgff526192013-06-10 19:30:26 +0000747 DIFF_CACHE = _GitDiffCache
748
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000749 def __init__(self, *args, **kwargs):
750 AffectedFile.__init__(self, *args, **kwargs)
751 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800752 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000753
agable0b65e732016-11-22 09:25:46 -0800754 def IsTestableFile(self):
755 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000756 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800757 # A deleted file is not testable.
758 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000759 else:
agable0b65e732016-11-22 09:25:46 -0800760 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
761 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000762
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000763
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000764class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000765 """Describe a change.
766
767 Used directly by the presubmit scripts to query the current change being
768 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000769
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000770 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000771 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000772 self.KEY: equivalent to tags['KEY']
773 """
774
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000775 _AFFECTED_FILES = AffectedFile
776
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000777 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000778 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000779 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000780 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000781
maruel@chromium.org58407af2011-04-12 23:15:57 +0000782 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000783 self, name, description, local_root, files, issue, patchset, author,
784 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000785 if files is None:
786 files = []
787 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000788 # Convert root into an absolute path.
789 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000790 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000791 self.issue = issue
792 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000793 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000794
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000795 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000796 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000797 self._description_without_tags = ''
798 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000799
maruel@chromium.orge085d812011-10-10 19:49:15 +0000800 assert all(
801 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
802
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000803 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000804 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000805 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
806 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000807 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000808
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000809 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000810 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000811 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000812
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000813 def DescriptionText(self):
814 """Returns the user-entered changelist description, minus tags.
815
816 Any line in the user-provided description starting with e.g. "FOO="
817 (whitespace permitted before and around) is considered a tag line. Such
818 lines are stripped out of the description this function returns.
819 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000820 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000821
822 def FullDescriptionText(self):
823 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000824 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000825
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000826 def SetDescriptionText(self, description):
827 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000828
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000829 Also updates the list of tags."""
830 self._full_description = description
831
832 # From the description text, build up a dictionary of key/value pairs
833 # plus the description minus all key/value or "tag" lines.
834 description_without_tags = []
835 self.tags = {}
836 for line in self._full_description.splitlines():
837 m = self.TAG_LINE_RE.match(line)
838 if m:
839 self.tags[m.group('key')] = m.group('value')
840 else:
841 description_without_tags.append(line)
842
843 # Change back to text and remove whitespace at end.
844 self._description_without_tags = (
845 '\n'.join(description_without_tags).rstrip())
846
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000847 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000848 """Returns the repository (checkout) root directory for this change,
849 as an absolute path.
850 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000851 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000852
853 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000854 """Return tags directly as attributes on the object."""
855 if not re.match(r"^[A-Z_]*$", attr):
856 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000857 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000859 def AllFiles(self, root=None):
860 """List all files under source control in the repo."""
861 raise NotImplementedError()
862
agable0b65e732016-11-22 09:25:46 -0800863 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000864 """Returns a list of AffectedFile instances for all files in the change.
865
866 Args:
867 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +0000868 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000869
870 Returns:
871 [AffectedFile(path, action), AffectedFile(path, action)]
872 """
agable0b65e732016-11-22 09:25:46 -0800873 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +0000874
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000875 if include_deletes:
876 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -0700877 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000878
agable0b65e732016-11-22 09:25:46 -0800879 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000880 """Return a list of the existing text files in a change."""
881 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800882 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000883 " is deprecated and ignored" % str(include_deletes),
884 category=DeprecationWarning,
885 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800886 return filter(lambda x: x.IsTestableFile(),
887 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000888
agable0b65e732016-11-22 09:25:46 -0800889 def AffectedTextFiles(self, include_deletes=None):
890 """An alias to AffectedTestableFiles for backwards compatibility."""
891 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000892
agable0b65e732016-11-22 09:25:46 -0800893 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000894 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800895 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896
agable0b65e732016-11-22 09:25:46 -0800897 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800899 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000900
901 def RightHandSideLines(self):
902 """An iterator over all text lines in "new" version of changed files.
903
904 Lists lines from new or modified text files in the change.
905
906 This is useful for doing line-by-line regex checks, like checking for
907 trailing whitespace.
908
909 Yields:
910 a 3 tuple:
911 the AffectedFile instance of the current file;
912 integer line number (1-based); and
913 the contents of the line as a string.
914 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000915 return _RightHandSideLinesImpl(
916 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -0800917 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000918
Jochen Eisingerd0573ec2017-04-13 10:55:06 +0200919 def OriginalOwnersFiles(self):
920 """A map from path names of affected OWNERS files to their old content."""
921 def owners_file_filter(f):
922 return 'OWNERS' in os.path.split(f.LocalPath())[1]
923 files = self.AffectedFiles(file_filter=owners_file_filter)
924 return dict([(f.LocalPath(), f.OldContents()) for f in files])
925
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000926
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000927class GitChange(Change):
928 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000929 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000930
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000931 def AllFiles(self, root=None):
932 """List all files under source control in the repo."""
933 root = root or self.RepositoryRoot()
934 return subprocess.check_output(
935 ['git', 'ls-files', '--', '.'], cwd=root).splitlines()
936
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000937
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000938def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000939 """Finds all presubmit files that apply to a given set of source files.
940
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000941 If inherit-review-settings-ok is present right under root, looks for
942 PRESUBMIT.py in directories enclosing root.
943
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000944 Args:
945 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000946 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000947
948 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000949 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000950 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000951 files = [normpath(os.path.join(root, f)) for f in files]
952
953 # List all the individual directories containing files.
954 directories = set([os.path.dirname(f) for f in files])
955
956 # Ignore root if inherit-review-settings-ok is present.
957 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
958 root = None
959
960 # Collect all unique directories that may contain PRESUBMIT.py.
961 candidates = set()
962 for directory in directories:
963 while True:
964 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000965 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000966 candidates.add(directory)
967 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000968 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000969 parent_dir = os.path.dirname(directory)
970 if parent_dir == directory:
971 # We hit the system root directory.
972 break
973 directory = parent_dir
974
975 # Look for PRESUBMIT.py in all candidate directories.
976 results = []
977 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -0700978 try:
979 for f in os.listdir(directory):
980 p = os.path.join(directory, f)
981 if os.path.isfile(p) and re.match(
982 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
983 results.append(p)
984 except OSError:
985 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000986
tobiasjs2836bcf2016-08-16 04:08:16 -0700987 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000988 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000989
990
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +0000991class GetTryMastersExecuter(object):
992 @staticmethod
993 def ExecPresubmitScript(script_text, presubmit_path, project, change):
994 """Executes GetPreferredTryMasters() from a single presubmit script.
995
996 Args:
997 script_text: The text of the presubmit script.
998 presubmit_path: Project script to run.
999 project: Project name to pass to presubmit script for bot selection.
1000
1001 Return:
1002 A map of try masters to map of builders to set of tests.
1003 """
1004 context = {}
1005 try:
1006 exec script_text in context
1007 except Exception, e:
1008 raise PresubmitFailure('"%s" had an exception.\n%s'
1009 % (presubmit_path, e))
1010
1011 function_name = 'GetPreferredTryMasters'
1012 if function_name not in context:
1013 return {}
1014 get_preferred_try_masters = context[function_name]
1015 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1016 raise PresubmitFailure(
1017 'Expected function "GetPreferredTryMasters" to take two arguments.')
1018 return get_preferred_try_masters(project, change)
1019
1020
rmistry@google.com5626a922015-02-26 14:03:30 +00001021class GetPostUploadExecuter(object):
1022 @staticmethod
1023 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1024 """Executes PostUploadHook() from a single presubmit script.
1025
1026 Args:
1027 script_text: The text of the presubmit script.
1028 presubmit_path: Project script to run.
1029 cl: The Changelist object.
1030 change: The Change object.
1031
1032 Return:
1033 A list of results objects.
1034 """
1035 context = {}
1036 try:
1037 exec script_text in context
1038 except Exception, e:
1039 raise PresubmitFailure('"%s" had an exception.\n%s'
1040 % (presubmit_path, e))
1041
1042 function_name = 'PostUploadHook'
1043 if function_name not in context:
1044 return {}
1045 post_upload_hook = context[function_name]
1046 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1047 raise PresubmitFailure(
1048 'Expected function "PostUploadHook" to take three arguments.')
1049 return post_upload_hook(cl, change, OutputApi(False))
1050
1051
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001052def _MergeMasters(masters1, masters2):
1053 """Merges two master maps. Merges also the tests of each builder."""
1054 result = {}
1055 for (master, builders) in itertools.chain(masters1.iteritems(),
1056 masters2.iteritems()):
1057 new_builders = result.setdefault(master, {})
1058 for (builder, tests) in builders.iteritems():
1059 new_builders.setdefault(builder, set([])).update(tests)
1060 return result
1061
1062
1063def DoGetTryMasters(change,
1064 changed_files,
1065 repository_root,
1066 default_presubmit,
1067 project,
1068 verbose,
1069 output_stream):
1070 """Get the list of try masters from the presubmit scripts.
1071
1072 Args:
1073 changed_files: List of modified files.
1074 repository_root: The repository root.
1075 default_presubmit: A default presubmit script to execute in any case.
1076 project: Optional name of a project used in selecting trybots.
1077 verbose: Prints debug info.
1078 output_stream: A stream to write debug output to.
1079
1080 Return:
1081 Map of try masters to map of builders to set of tests.
1082 """
1083 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1084 if not presubmit_files and verbose:
1085 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1086 results = {}
1087 executer = GetTryMastersExecuter()
1088
1089 if default_presubmit:
1090 if verbose:
1091 output_stream.write("Running default presubmit script.\n")
1092 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1093 results = _MergeMasters(results, executer.ExecPresubmitScript(
1094 default_presubmit, fake_path, project, change))
1095 for filename in presubmit_files:
1096 filename = os.path.abspath(filename)
1097 if verbose:
1098 output_stream.write("Running %s\n" % filename)
1099 # Accept CRLF presubmit script.
1100 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1101 results = _MergeMasters(results, executer.ExecPresubmitScript(
1102 presubmit_script, filename, project, change))
1103
1104 # Make sets to lists again for later JSON serialization.
1105 for builders in results.itervalues():
1106 for builder in builders:
1107 builders[builder] = list(builders[builder])
1108
1109 if results and verbose:
1110 output_stream.write('%s\n' % str(results))
1111 return results
1112
1113
rmistry@google.com5626a922015-02-26 14:03:30 +00001114def DoPostUploadExecuter(change,
1115 cl,
1116 repository_root,
1117 verbose,
1118 output_stream):
1119 """Execute the post upload hook.
1120
1121 Args:
1122 change: The Change object.
1123 cl: The Changelist object.
1124 repository_root: The repository root.
1125 verbose: Prints debug info.
1126 output_stream: A stream to write debug output to.
1127 """
1128 presubmit_files = ListRelevantPresubmitFiles(
1129 change.LocalPaths(), repository_root)
1130 if not presubmit_files and verbose:
1131 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1132 results = []
1133 executer = GetPostUploadExecuter()
1134 # The root presubmit file should be executed after the ones in subdirectories.
1135 # i.e. the specific post upload hooks should run before the general ones.
1136 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1137 presubmit_files.reverse()
1138
1139 for filename in presubmit_files:
1140 filename = os.path.abspath(filename)
1141 if verbose:
1142 output_stream.write("Running %s\n" % filename)
1143 # Accept CRLF presubmit script.
1144 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1145 results.extend(executer.ExecPresubmitScript(
1146 presubmit_script, filename, cl, change))
1147 output_stream.write('\n')
1148 if results:
1149 output_stream.write('** Post Upload Hook Messages **\n')
1150 for result in results:
1151 result.handle(output_stream)
1152 output_stream.write('\n')
1153
1154 return results
1155
1156
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001157class PresubmitExecuter(object):
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001158 def __init__(self, change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001159 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001160 """
1161 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001162 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001163 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001164 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001165 gerrit_obj: provides basic Gerrit codereview functionality.
1166 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001167 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001168 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001169 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001170 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001171 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001172 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001173 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001174
1175 def ExecPresubmitScript(self, script_text, presubmit_path):
1176 """Executes a single presubmit script.
1177
1178 Args:
1179 script_text: The text of the presubmit script.
1180 presubmit_path: The path to the presubmit file (this will be reported via
1181 input_api.PresubmitLocalPath()).
1182
1183 Return:
1184 A list of result objects, empty if no problems.
1185 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001186
chase@chromium.org8e416c82009-10-06 04:30:44 +00001187 # Change to the presubmit file's directory to support local imports.
1188 main_path = os.getcwd()
1189 os.chdir(os.path.dirname(presubmit_path))
1190
1191 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001192 input_api = InputApi(self.change, presubmit_path, self.committing,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001193 self.rietveld, self.verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001194 gerrit_obj=self.gerrit, dry_run=self.dry_run)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001195 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001196 try:
1197 exec script_text in context
1198 except Exception, e:
1199 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001200
1201 # These function names must change if we make substantial changes to
1202 # the presubmit API that are not backwards compatible.
1203 if self.committing:
1204 function_name = 'CheckChangeOnCommit'
1205 else:
1206 function_name = 'CheckChangeOnUpload'
1207 if function_name in context:
wez@chromium.orga6d011e2013-03-26 17:31:49 +00001208 context['__args'] = (input_api, OutputApi(self.committing))
tobiasjs2836bcf2016-08-16 04:08:16 -07001209 logging.debug('Running %s in %s', function_name, presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001210 result = eval(function_name + '(*__args)', context)
tobiasjs2836bcf2016-08-16 04:08:16 -07001211 logging.debug('Running %s done.', function_name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001212 if not (isinstance(result, types.TupleType) or
1213 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001214 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001215 'Presubmit functions must return a tuple or list')
1216 for item in result:
1217 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001218 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001219 'All presubmit results must be of types derived from '
1220 'output_api.PresubmitResult')
1221 else:
1222 result = () # no error since the script doesn't care about current event.
1223
scottmg86099d72016-09-01 09:16:51 -07001224 input_api.ShutdownPool()
1225
chase@chromium.org8e416c82009-10-06 04:30:44 +00001226 # Return the process to the original working directory.
1227 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001228 return result
1229
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001230def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001231 committing,
1232 verbose,
1233 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001234 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001235 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001236 may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001237 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001238 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001239 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001240 """Runs all presubmit checks that apply to the files in the change.
1241
1242 This finds all PRESUBMIT.py files in directories enclosing the files in the
1243 change (up to the repository root) and calls the relevant entrypoint function
1244 depending on whether the change is being committed or uploaded.
1245
1246 Prints errors, warnings and notifications. Prompts the user for warnings
1247 when needed.
1248
1249 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001250 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001251 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001252 verbose: Prints debug info.
1253 output_stream: A stream to write output from presubmit tests to.
1254 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001255 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001256 may_prompt: Enable (y/n) questions on warning or error. If False,
1257 any questions are answered with yes by default.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001258 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001259 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001260 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001261
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001262 Warning:
1263 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1264 SHOULD be sys.stdin.
1265
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001266 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001267 A PresubmitOutput object. Use output.should_continue() to figure out
1268 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001269 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001270 old_environ = os.environ
1271 try:
1272 # Make sure python subprocesses won't generate .pyc files.
1273 os.environ = os.environ.copy()
1274 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001275
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001276 output = PresubmitOutput(input_stream, output_stream)
1277 if committing:
1278 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001279 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001280 output.write("Running presubmit upload checks ...\n")
1281 start_time = time.time()
1282 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001283 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001284 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001285 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001286 results = []
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001287 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001288 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001289 if default_presubmit:
1290 if verbose:
1291 output.write("Running default presubmit script.\n")
1292 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1293 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1294 for filename in presubmit_files:
1295 filename = os.path.abspath(filename)
1296 if verbose:
1297 output.write("Running %s\n" % filename)
1298 # Accept CRLF presubmit script.
1299 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1300 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001301
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001302 errors = []
1303 notifications = []
1304 warnings = []
1305 for result in results:
1306 if result.fatal:
1307 errors.append(result)
1308 elif result.should_prompt:
1309 warnings.append(result)
1310 else:
1311 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001312
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001313 output.write('\n')
1314 for name, items in (('Messages', notifications),
1315 ('Warnings', warnings),
1316 ('ERRORS', errors)):
1317 if items:
1318 output.write('** Presubmit %s **\n' % name)
1319 for item in items:
1320 item.handle(output)
1321 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001322
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001323 total_time = time.time() - start_time
1324 if total_time > 1.0:
1325 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001326
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001327 if errors:
1328 output.fail()
1329 elif warnings:
1330 output.write('There were presubmit warnings. ')
1331 if may_prompt:
1332 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1333 else:
1334 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001335
1336 global _ASKED_FOR_FEEDBACK
1337 # Ask for feedback one time out of 5.
1338 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001339 output.write(
1340 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1341 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1342 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001343 _ASKED_FOR_FEEDBACK = True
1344 return output
1345 finally:
1346 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001347
1348
1349def ScanSubDirs(mask, recursive):
1350 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001351 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001352
1353 results = []
1354 for root, dirs, files in os.walk('.'):
1355 if '.svn' in dirs:
1356 dirs.remove('.svn')
1357 if '.git' in dirs:
1358 dirs.remove('.git')
1359 for name in files:
1360 if fnmatch.fnmatch(name, mask):
1361 results.append(os.path.join(root, name))
1362 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001363
1364
1365def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001366 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001367 files = []
1368 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001369 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001370 return files
1371
1372
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001373def load_files(options, args):
1374 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001375 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001376 if args:
1377 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001378 change_scm = scm.determine_scm(options.root)
1379 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001380 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001381 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001382 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001383 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001384 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001385 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001386 if not files:
1387 return None, None
1388 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001389 return change_class, files
1390
1391
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001392class NonexistantCannedCheckFilter(Exception):
1393 pass
1394
1395
1396@contextlib.contextmanager
1397def canned_check_filter(method_names):
1398 filtered = {}
1399 try:
1400 for method_name in method_names:
1401 if not hasattr(presubmit_canned_checks, method_name):
1402 raise NonexistantCannedCheckFilter(method_name)
1403 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1404 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1405 yield
1406 finally:
1407 for name, method in filtered.iteritems():
1408 setattr(presubmit_canned_checks, name, method)
1409
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001410
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001411def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001412 """Runs an external program, potentially from a child process created by the
1413 multiprocessing module.
1414
1415 multiprocessing needs a top level function with a single argument.
1416 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001417 cmd_data.kwargs['stdout'] = subprocess.PIPE
1418 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1419 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001420 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001421 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001422 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001423 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001424 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001425 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001426 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1427 if code != 0:
1428 return cmd_data.message(
1429 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1430 if cmd_data.info:
1431 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001432
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001433
sbc@chromium.org013731e2015-02-26 18:28:43 +00001434def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001435 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001436 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001437 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001438 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001439 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1440 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001441 parser.add_option("-r", "--recursive", action="store_true",
1442 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001443 parser.add_option("-v", "--verbose", action="count", default=0,
1444 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001445 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001446 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001447 parser.add_option("--description", default='')
1448 parser.add_option("--issue", type='int', default=0)
1449 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001450 parser.add_option("--root", default=os.getcwd(),
1451 help="Search for PRESUBMIT.py up to this directory. "
1452 "If inherit-review-settings-ok is present in this "
1453 "directory, parent directories up to the root file "
1454 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001455 parser.add_option("--upstream",
1456 help="Git only: the base ref or upstream branch against "
1457 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001458 parser.add_option("--default_presubmit")
1459 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001460 parser.add_option("--skip_canned", action='append', default=[],
1461 help="A list of checks to skip which appear in "
1462 "presubmit_canned_checks. Can be provided multiple times "
1463 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001464 parser.add_option("--dry_run", action='store_true',
1465 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001466 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001467 parser.add_option("--gerrit_fetch", action='store_true',
1468 help=optparse.SUPPRESS_HELP)
maruel@chromium.org239f4112011-06-03 20:08:23 +00001469 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1470 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001471 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1472 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001473 # These are for OAuth2 authentication for bots. See also apply_issue.py
1474 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1475 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1476
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001477 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001478 options, args = parser.parse_args(argv)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001479 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001480
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001481 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001482 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001483 elif options.verbose:
1484 logging.basicConfig(level=logging.INFO)
1485 else:
1486 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001487
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001488 if (any((options.rietveld_url, options.rietveld_email_file,
1489 options.rietveld_fetch, options.rietveld_private_key_file))
1490 and any((options.gerrit_url, options.gerrit_fetch))):
1491 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1492 'allowed')
1493
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001494 if options.rietveld_email and options.rietveld_email_file:
1495 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1496 "can be passed to this program.")
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001497 if options.rietveld_email_file:
1498 with open(options.rietveld_email_file, "rb") as f:
1499 options.rietveld_email = f.read().strip()
1500
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001501 change_class, files = load_files(options, args)
1502 if not change_class:
1503 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001504 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001505
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001506 rietveld_obj, gerrit_obj = None, None
1507
maruel@chromium.org239f4112011-06-03 20:08:23 +00001508 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001509 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001510 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001511 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1512 options.rietveld_url,
1513 options.rietveld_email,
1514 options.rietveld_private_key_file)
1515 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001516 rietveld_obj = rietveld.CachingRietveld(
1517 options.rietveld_url,
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001518 auth_config,
1519 options.rietveld_email)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001520 if options.rietveld_fetch:
1521 assert options.issue
1522 props = rietveld_obj.get_issue_properties(options.issue, False)
1523 options.author = props['owner_email']
1524 options.description = props['description']
1525 logging.info('Got author: "%s"', options.author)
1526 logging.info('Got description: """\n%s\n"""', options.description)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001527
1528 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001529 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001530 rietveld_obj = None
1531 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1532 options.author = gerrit_obj.GetChangeOwner(options.issue)
1533 options.description = gerrit_obj.GetChangeDescription(options.issue,
1534 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001535 logging.info('Got author: "%s"', options.author)
1536 logging.info('Got description: """\n%s\n"""', options.description)
1537
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001538 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001539 with canned_check_filter(options.skip_canned):
1540 results = DoPresubmitChecks(
1541 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001542 options.description,
1543 options.root,
1544 files,
1545 options.issue,
1546 options.patchset,
1547 options.author,
1548 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001549 options.commit,
1550 options.verbose,
1551 sys.stdout,
1552 sys.stdin,
1553 options.default_presubmit,
1554 options.may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001555 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001556 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001557 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001558 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001559 except NonexistantCannedCheckFilter, e:
1560 print >> sys.stderr, (
1561 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1562 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001563 except PresubmitFailure, e:
1564 print >> sys.stderr, e
1565 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1566 print >> sys.stderr, 'If all fails, contact maruel@'
1567 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001568
1569
1570if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001571 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001572 try:
1573 sys.exit(main())
1574 except KeyboardInterrupt:
1575 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001576 sys.exit(2)