maruel@chromium.org | 725f1c3 | 2011-04-01 20:24:54 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
maruel@chromium.org | 3bbf294 | 2012-01-10 16:52:06 +0000 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 3 | # 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.org | f7d31f5 | 2014-01-03 20:14:46 +0000 | [diff] [blame] | 9 | __version__ = '1.8.0' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 10 | |
| 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 Yoshino | 07a6bea | 2017-08-02 02:44:06 +0900 | [diff] [blame] | 15 | import ast # Exposed through the API. |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 16 | import cpplint |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 17 | import cPickle # Exposed through the API. |
| 18 | import cStringIO # Exposed through the API. |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 19 | import contextlib |
dcheng | 091b7db | 2016-06-16 01:27:51 -0700 | [diff] [blame] | 20 | import fnmatch # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 21 | import glob |
asvitkine@chromium.org | 1516995 | 2011-09-27 14:30:53 +0000 | [diff] [blame] | 22 | import inspect |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 23 | import itertools |
maruel@chromium.org | 4f6852c | 2012-04-20 20:39:20 +0000 | [diff] [blame] | 24 | import json # Exposed through the API. |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 25 | import logging |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 26 | import marshal # Exposed through the API. |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 27 | import multiprocessing |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 28 | import optparse |
| 29 | import os # Somewhat exposed through the API. |
| 30 | import pickle # Exposed through the API. |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 31 | import random |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 32 | import re # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 33 | import sys # Parts exposed through API. |
| 34 | import tempfile # Exposed through the API. |
jam@chromium.org | 2a891dc | 2009-08-20 20:33:37 +0000 | [diff] [blame] | 35 | import time |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 36 | import traceback # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 37 | import types |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 38 | import unittest # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 39 | import urllib2 # Exposed through the API. |
tandrii@chromium.org | 015ebae | 2016-04-25 19:37:22 +0000 | [diff] [blame] | 40 | import urlparse |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 41 | from warnings import warn |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 42 | |
| 43 | # Local imports. |
maruel@chromium.org | 35625c7 | 2011-03-23 17:34:02 +0000 | [diff] [blame] | 44 | import fix_encoding |
maruel@chromium.org | 5aeb7dd | 2009-11-17 18:09:01 +0000 | [diff] [blame] | 45 | import gclient_utils |
Aaron Gable | b584c4f | 2017-04-26 16:28:08 -0700 | [diff] [blame] | 46 | import git_footers |
tandrii@chromium.org | 015ebae | 2016-04-25 19:37:22 +0000 | [diff] [blame] | 47 | import gerrit_util |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 48 | import owners |
Jochen Eisinger | 76f5fc6 | 2017-04-07 16:27:46 +0200 | [diff] [blame] | 49 | import owners_finder |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 50 | import presubmit_canned_checks |
maruel@chromium.org | 5aeb7dd | 2009-11-17 18:09:01 +0000 | [diff] [blame] | 51 | import scm |
maruel@chromium.org | 84f4fe3 | 2011-04-06 13:26:45 +0000 | [diff] [blame] | 52 | import subprocess2 as subprocess # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 53 | |
| 54 | |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 55 | # Ask for feedback only once in program lifetime. |
| 56 | _ASKED_FOR_FEEDBACK = False |
| 57 | |
| 58 | |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 59 | class PresubmitFailure(Exception): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 60 | pass |
| 61 | |
| 62 | |
maruel@chromium.org | ffeb2f3 | 2013-12-03 13:55:22 +0000 | [diff] [blame] | 63 | class 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.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 71 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 72 | def 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.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 81 | |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 82 | def _RightHandSideLinesImpl(affected_files): |
| 83 | """Implements RightHandSideLines for InputApi and GclChange.""" |
| 84 | for af in affected_files: |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 85 | lines = af.ChangedContents() |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 86 | for line in lines: |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 87 | yield (af, line[0], line[1]) |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 88 | |
| 89 | |
dpranke@chromium.org | 5ac2101 | 2011-03-16 02:58:25 +0000 | [diff] [blame] | 90 | class 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 = [] |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 95 | self.more_cc = [] |
dpranke@chromium.org | 5ac2101 | 2011-03-16 02:58:25 +0000 | [diff] [blame] | 96 | self.written_output = [] |
| 97 | self.error_count = 0 |
| 98 | |
| 99 | def prompt_yes_no(self, prompt_string): |
| 100 | self.write(prompt_string) |
| 101 | if self.input_stream: |
| 102 | response = self.input_stream.readline().strip().lower() |
| 103 | if response not in ('y', 'yes'): |
| 104 | self.fail() |
| 105 | else: |
| 106 | self.fail() |
| 107 | |
| 108 | def fail(self): |
| 109 | self.error_count += 1 |
| 110 | |
| 111 | def should_continue(self): |
| 112 | return not self.error_count |
| 113 | |
| 114 | def write(self, s): |
| 115 | self.written_output.append(s) |
| 116 | if self.output_stream: |
| 117 | self.output_stream.write(s) |
| 118 | |
| 119 | def getvalue(self): |
| 120 | return ''.join(self.written_output) |
| 121 | |
| 122 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 123 | # Top level object so multiprocessing can pickle |
| 124 | # Public access through OutputApi object. |
| 125 | class _PresubmitResult(object): |
| 126 | """Base class for result objects.""" |
| 127 | fatal = False |
| 128 | should_prompt = False |
| 129 | |
| 130 | def __init__(self, message, items=None, long_text=''): |
| 131 | """ |
| 132 | message: A short one-line message to indicate errors. |
| 133 | items: A list of short strings to indicate where errors occurred. |
| 134 | long_text: multi-line text output, e.g. from another tool |
| 135 | """ |
| 136 | self._message = message |
| 137 | self._items = items or [] |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 138 | self._long_text = long_text.rstrip() |
| 139 | |
| 140 | def handle(self, output): |
| 141 | output.write(self._message) |
| 142 | output.write('\n') |
| 143 | for index, item in enumerate(self._items): |
| 144 | output.write(' ') |
| 145 | # Write separately in case it's unicode. |
| 146 | output.write(str(item)) |
| 147 | if index < len(self._items) - 1: |
| 148 | output.write(' \\') |
| 149 | output.write('\n') |
| 150 | if self._long_text: |
| 151 | output.write('\n***************\n') |
| 152 | # Write separately in case it's unicode. |
| 153 | output.write(self._long_text) |
| 154 | output.write('\n***************\n') |
| 155 | if self.fatal: |
| 156 | output.fail() |
| 157 | |
| 158 | |
| 159 | # Top level object so multiprocessing can pickle |
| 160 | # Public access through OutputApi object. |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 161 | class _PresubmitError(_PresubmitResult): |
| 162 | """A hard presubmit error.""" |
| 163 | fatal = True |
| 164 | |
| 165 | |
| 166 | # Top level object so multiprocessing can pickle |
| 167 | # Public access through OutputApi object. |
| 168 | class _PresubmitPromptWarning(_PresubmitResult): |
| 169 | """An warning that prompts the user if they want to continue.""" |
| 170 | should_prompt = True |
| 171 | |
| 172 | |
| 173 | # Top level object so multiprocessing can pickle |
| 174 | # Public access through OutputApi object. |
| 175 | class _PresubmitNotifyResult(_PresubmitResult): |
| 176 | """Just print something to the screen -- but it's not even a warning.""" |
| 177 | pass |
| 178 | |
| 179 | |
| 180 | # Top level object so multiprocessing can pickle |
| 181 | # Public access through OutputApi object. |
| 182 | class _MailTextResult(_PresubmitResult): |
| 183 | """A warning that should be included in the review request email.""" |
| 184 | def __init__(self, *args, **kwargs): |
| 185 | super(_MailTextResult, self).__init__() |
| 186 | raise NotImplementedError() |
| 187 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 188 | class GerritAccessor(object): |
| 189 | """Limited Gerrit functionality for canned presubmit checks to work. |
| 190 | |
| 191 | To avoid excessive Gerrit calls, caches the results. |
| 192 | """ |
| 193 | |
| 194 | def __init__(self, host): |
| 195 | self.host = host |
| 196 | self.cache = {} |
| 197 | |
| 198 | def _FetchChangeDetail(self, issue): |
| 199 | # Separate function to be easily mocked in tests. |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 200 | try: |
| 201 | return gerrit_util.GetChangeDetail( |
| 202 | self.host, str(issue), |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 203 | ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS']) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 204 | except gerrit_util.GerritError as e: |
| 205 | if e.http_status == 404: |
| 206 | raise Exception('Either Gerrit issue %s doesn\'t exist, or ' |
| 207 | 'no credentials to fetch issue details' % issue) |
| 208 | raise |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 209 | |
| 210 | def GetChangeInfo(self, issue): |
| 211 | """Returns labels and all revisions (patchsets) for this issue. |
| 212 | |
| 213 | The result is a dictionary according to Gerrit REST Api. |
| 214 | https://gerrit-review.googlesource.com/Documentation/rest-api.html |
| 215 | |
| 216 | However, API isn't very clear what's inside, so see tests for example. |
| 217 | """ |
| 218 | assert issue |
| 219 | cache_key = int(issue) |
| 220 | if cache_key not in self.cache: |
| 221 | self.cache[cache_key] = self._FetchChangeDetail(issue) |
| 222 | return self.cache[cache_key] |
| 223 | |
| 224 | def GetChangeDescription(self, issue, patchset=None): |
| 225 | """If patchset is none, fetches current patchset.""" |
| 226 | info = self.GetChangeInfo(issue) |
| 227 | # info is a reference to cache. We'll modify it here adding description to |
| 228 | # it to the right patchset, if it is not yet there. |
| 229 | |
| 230 | # Find revision info for the patchset we want. |
| 231 | if patchset is not None: |
| 232 | for rev, rev_info in info['revisions'].iteritems(): |
| 233 | if str(rev_info['_number']) == str(patchset): |
| 234 | break |
| 235 | else: |
| 236 | raise Exception('patchset %s doesn\'t exist in issue %s' % ( |
| 237 | patchset, issue)) |
| 238 | else: |
| 239 | rev = info['current_revision'] |
| 240 | rev_info = info['revisions'][rev] |
| 241 | |
Andrii Shyshkalov | 9c3a464 | 2017-01-24 17:41:22 +0100 | [diff] [blame] | 242 | return rev_info['commit']['message'] |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 243 | |
Mun Yong Jang | 603d01e | 2017-12-19 16:38:30 -0800 | [diff] [blame] | 244 | def GetDestRef(self, issue): |
| 245 | ref = self.GetChangeInfo(issue)['branch'] |
| 246 | if not ref.startswith('refs/'): |
| 247 | # NOTE: it is possible to create 'refs/x' branch, |
| 248 | # aka 'refs/heads/refs/x'. However, this is ill-advised. |
| 249 | ref = 'refs/heads/%s' % ref |
| 250 | return ref |
| 251 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 252 | def GetChangeOwner(self, issue): |
| 253 | return self.GetChangeInfo(issue)['owner']['email'] |
| 254 | |
| 255 | def GetChangeReviewers(self, issue, approving_only=True): |
Aaron Gable | 8b478f0 | 2017-07-31 15:33:19 -0700 | [diff] [blame] | 256 | changeinfo = self.GetChangeInfo(issue) |
| 257 | if approving_only: |
| 258 | labelinfo = changeinfo.get('labels', {}).get('Code-Review', {}) |
| 259 | values = labelinfo.get('values', {}).keys() |
| 260 | try: |
| 261 | max_value = max(int(v) for v in values) |
| 262 | reviewers = [r for r in labelinfo.get('all', []) |
| 263 | if r.get('value', 0) == max_value] |
| 264 | except ValueError: # values is the empty list |
| 265 | reviewers = [] |
| 266 | else: |
| 267 | reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', []) |
| 268 | return [r.get('email') for r in reviewers] |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 269 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 270 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 271 | class OutputApi(object): |
wez@chromium.org | a6d011e | 2013-03-26 17:31:49 +0000 | [diff] [blame] | 272 | """An instance of OutputApi gets passed to presubmit scripts so that they |
| 273 | can output various types of results. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 274 | """ |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 275 | PresubmitResult = _PresubmitResult |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 276 | PresubmitError = _PresubmitError |
| 277 | PresubmitPromptWarning = _PresubmitPromptWarning |
| 278 | PresubmitNotifyResult = _PresubmitNotifyResult |
| 279 | MailTextResult = _MailTextResult |
| 280 | |
wez@chromium.org | a6d011e | 2013-03-26 17:31:49 +0000 | [diff] [blame] | 281 | def __init__(self, is_committing): |
| 282 | self.is_committing = is_committing |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 283 | self.more_cc = [] |
| 284 | |
| 285 | def AppendCC(self, cc): |
| 286 | """Appends a user to cc for this change.""" |
| 287 | self.more_cc.append(cc) |
wez@chromium.org | a6d011e | 2013-03-26 17:31:49 +0000 | [diff] [blame] | 288 | |
wez@chromium.org | a6d011e | 2013-03-26 17:31:49 +0000 | [diff] [blame] | 289 | def PresubmitPromptOrNotify(self, *args, **kwargs): |
| 290 | """Warn the user when uploading, but only notify if committing.""" |
| 291 | if self.is_committing: |
| 292 | return self.PresubmitNotifyResult(*args, **kwargs) |
| 293 | return self.PresubmitPromptWarning(*args, **kwargs) |
| 294 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 295 | def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message): |
| 296 | """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS. |
| 297 | |
| 298 | Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list, |
| 299 | keeping it alphabetically sorted. Returns the results that should be |
| 300 | returned from the PostUploadHook. |
| 301 | |
| 302 | Args: |
| 303 | cl: The git_cl.Changelist object. |
| 304 | bots_to_include: A list of strings of bots to include, in the form |
| 305 | "master:slave". |
| 306 | message: A message to be printed in the case that |
| 307 | CQ_INCLUDE_TRYBOTS was updated. |
| 308 | """ |
| 309 | description = cl.GetDescription(force=True) |
Aaron Gable | b584c4f | 2017-04-26 16:28:08 -0700 | [diff] [blame] | 310 | include_re = re.compile(r'^CQ_INCLUDE_TRYBOTS=(.*)$', re.M | re.I) |
| 311 | |
| 312 | prior_bots = [] |
| 313 | if cl.IsGerrit(): |
| 314 | trybot_footers = git_footers.parse_footers(description).get( |
| 315 | git_footers.normalize_name('Cq-Include-Trybots'), []) |
| 316 | for f in trybot_footers: |
| 317 | prior_bots += [b.strip() for b in f.split(';') if b.strip()] |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 318 | else: |
Aaron Gable | b584c4f | 2017-04-26 16:28:08 -0700 | [diff] [blame] | 319 | trybot_tags = include_re.finditer(description) |
| 320 | for t in trybot_tags: |
| 321 | prior_bots += [b.strip() for b in t.group(1).split(';') if b.strip()] |
| 322 | |
| 323 | if set(prior_bots) >= set(bots_to_include): |
| 324 | return [] |
| 325 | all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include))) |
| 326 | |
| 327 | if cl.IsGerrit(): |
| 328 | description = git_footers.remove_footer( |
| 329 | description, 'Cq-Include-Trybots') |
| 330 | description = git_footers.add_footer( |
| 331 | description, 'Cq-Include-Trybots', all_bots, |
| 332 | before_keys=['Change-Id']) |
| 333 | else: |
| 334 | new_include_trybots = 'CQ_INCLUDE_TRYBOTS=%s' % all_bots |
| 335 | m = include_re.search(description) |
| 336 | if m: |
| 337 | description = include_re.sub(new_include_trybots, description) |
Kenneth Russell | df6e734 | 2017-04-24 17:07:41 -0700 | [diff] [blame] | 338 | else: |
Aaron Gable | b584c4f | 2017-04-26 16:28:08 -0700 | [diff] [blame] | 339 | description = '%s\n%s\n' % (description, new_include_trybots) |
| 340 | |
| 341 | cl.UpdateDescription(description, force=True) |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 342 | return [self.PresubmitNotifyResult(message)] |
| 343 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 344 | |
| 345 | class InputApi(object): |
| 346 | """An instance of this object is passed to presubmit scripts so they can |
| 347 | know stuff about the change they're looking at. |
| 348 | """ |
maruel@chromium.org | b17b55b | 2010-11-03 14:42:37 +0000 | [diff] [blame] | 349 | # Method could be a function |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 350 | # pylint: disable=no-self-use |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 351 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 352 | # File extensions that are considered source files from a style guide |
| 353 | # perspective. Don't modify this list from a presubmit script! |
maruel@chromium.org | c33455a | 2011-06-24 19:14:18 +0000 | [diff] [blame] | 354 | # |
| 355 | # Files without an extension aren't included in the list. If you want to |
| 356 | # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list. |
| 357 | # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below. |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 358 | DEFAULT_WHITE_LIST = ( |
| 359 | # C++ and friends |
maruel@chromium.org | fe1211a | 2011-05-28 18:54:17 +0000 | [diff] [blame] | 360 | r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$", |
| 361 | r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 362 | # Scripts |
maruel@chromium.org | fe1211a | 2011-05-28 18:54:17 +0000 | [diff] [blame] | 363 | r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 364 | # Other |
estade@chromium.org | ae7af92 | 2012-01-27 14:51:13 +0000 | [diff] [blame] | 365 | r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$" |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 366 | ) |
| 367 | |
| 368 | # Path regexp that should be excluded from being considered containing source |
| 369 | # files. Don't modify this list from a presubmit script! |
| 370 | DEFAULT_BLACK_LIST = ( |
gavinp@chromium.org | 656326d | 2012-08-13 00:43:57 +0000 | [diff] [blame] | 371 | r"testing_support[\\\/]google_appengine[\\\/].*", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 372 | r".*\bexperimental[\\\/].*", |
primiano@chromium.org | b9658c3 | 2015-10-06 10:50:13 +0000 | [diff] [blame] | 373 | # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768). |
| 374 | r".*\bthird_party[\\\/](?!WebKit[\\\/]).*", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 375 | # Output directories (just in case) |
| 376 | r".*\bDebug[\\\/].*", |
| 377 | r".*\bRelease[\\\/].*", |
| 378 | r".*\bxcodebuild[\\\/].*", |
thakis@chromium.org | c1c9635 | 2013-10-09 19:50:27 +0000 | [diff] [blame] | 379 | r".*\bout[\\\/].*", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 380 | # All caps files like README and LICENCE. |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 381 | r".*\b[A-Z0-9_]{2,}$", |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 382 | # SCM (can happen in dual SCM configuration). (Slightly over aggressive) |
maruel@chromium.org | 5d0dc43 | 2011-01-03 02:40:37 +0000 | [diff] [blame] | 383 | r"(|.*[\\\/])\.git[\\\/].*", |
| 384 | r"(|.*[\\\/])\.svn[\\\/].*", |
maruel@chromium.org | 7ccb4bb | 2011-11-07 20:26:20 +0000 | [diff] [blame] | 385 | # There is no point in processing a patch file. |
| 386 | r".+\.diff$", |
| 387 | r".+\.patch$", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 388 | ) |
| 389 | |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 390 | def __init__(self, change, presubmit_path, is_committing, |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 391 | verbose, gerrit_obj, dry_run=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 392 | """Builds an InputApi object. |
| 393 | |
| 394 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 395 | change: A presubmit.Change object. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 396 | presubmit_path: The path to the presubmit script being processed. |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 397 | is_committing: True if the change is about to be committed. |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 398 | gerrit_obj: provides basic Gerrit codereview functionality. |
| 399 | dry_run: if true, some Checks will be skipped. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 400 | """ |
maruel@chromium.org | 9711bba | 2009-05-22 23:51:39 +0000 | [diff] [blame] | 401 | # Version number of the presubmit_support script. |
| 402 | self.version = [int(x) for x in __version__.split('.')] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 403 | self.change = change |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 404 | self.is_committing = is_committing |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 405 | self.gerrit = gerrit_obj |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 406 | self.dry_run = dry_run |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 407 | |
| 408 | # We expose various modules and functions as attributes of the input_api |
| 409 | # so that presubmit scripts don't have to import them. |
Takeshi Yoshino | 07a6bea | 2017-08-02 02:44:06 +0900 | [diff] [blame] | 410 | self.ast = ast |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 411 | self.basename = os.path.basename |
| 412 | self.cPickle = cPickle |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 413 | self.cpplint = cpplint |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 414 | self.cStringIO = cStringIO |
dcheng | 091b7db | 2016-06-16 01:27:51 -0700 | [diff] [blame] | 415 | self.fnmatch = fnmatch |
dpranke@chromium.org | 17cc244 | 2012-10-17 21:12:09 +0000 | [diff] [blame] | 416 | self.glob = glob.glob |
maruel@chromium.org | fb11c7b | 2010-03-18 18:22:14 +0000 | [diff] [blame] | 417 | self.json = json |
maruel@chromium.org | 6fba34d | 2011-06-02 13:45:12 +0000 | [diff] [blame] | 418 | self.logging = logging.getLogger('PRESUBMIT') |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 419 | self.os_listdir = os.listdir |
| 420 | self.os_walk = os.walk |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 421 | self.os_path = os.path |
pgervais@chromium.org | bd0cace | 2014-10-02 23:23:46 +0000 | [diff] [blame] | 422 | self.os_stat = os.stat |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 423 | self.pickle = pickle |
| 424 | self.marshal = marshal |
| 425 | self.re = re |
| 426 | self.subprocess = subprocess |
| 427 | self.tempfile = tempfile |
dpranke@chromium.org | 0d1bdea | 2011-03-24 22:54:38 +0000 | [diff] [blame] | 428 | self.time = time |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 429 | self.traceback = traceback |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 430 | self.unittest = unittest |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 431 | self.urllib2 = urllib2 |
| 432 | |
Robert Iannucci | 5025893 | 2018-03-19 10:30:59 -0700 | [diff] [blame] | 433 | self.is_windows = sys.platform == 'win32' |
| 434 | |
| 435 | # Set python_executable to 'python'. This is interpreted in CallCommand to |
| 436 | # convert to vpython in order to allow scripts in other repos (e.g. src.git) |
| 437 | # to automatically pick up that repo's .vpython file, instead of inheriting |
| 438 | # the one in depot_tools. |
| 439 | self.python_executable = 'python' |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 440 | self.environ = os.environ |
| 441 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 442 | # InputApi.platform is the platform you're currently running on. |
| 443 | self.platform = sys.platform |
| 444 | |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 445 | self.cpu_count = multiprocessing.cpu_count() |
| 446 | |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 447 | # this is done here because in RunTests, the current working directory has |
| 448 | # changed, which causes Pool() to explode fantastically when run on windows |
| 449 | # (because it tries to load the __main__ module, which imports lots of |
| 450 | # things relative to the current working directory). |
| 451 | self._run_tests_pool = multiprocessing.Pool(self.cpu_count) |
| 452 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 453 | # The local path of the currently-being-processed presubmit script. |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 454 | self._current_presubmit_path = os.path.dirname(presubmit_path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 455 | |
| 456 | # We carry the canned checks so presubmit scripts can easily use them. |
| 457 | self.canned_checks = presubmit_canned_checks |
| 458 | |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 18:07:58 +0100 | [diff] [blame] | 459 | # Temporary files we must manually remove at the end of a run. |
| 460 | self._named_temporary_files = [] |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 461 | |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 462 | # TODO(dpranke): figure out a list of all approved owners for a repo |
| 463 | # in order to be able to handle wildcard OWNERS files? |
| 464 | self.owners_db = owners.Database(change.RepositoryRoot(), |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 465 | fopen=file, os_path=self.os_path) |
Jochen Eisinger | 76f5fc6 | 2017-04-07 16:27:46 +0200 | [diff] [blame] | 466 | self.owners_finder = owners_finder.OwnersFinder |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 467 | self.verbose = verbose |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 468 | self.Command = CommandData |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 469 | |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 470 | # Replace <hash_map> and <hash_set> as headers that need to be included |
danakj@chromium.org | 1827852 | 2013-06-11 22:42:32 +0000 | [diff] [blame] | 471 | # with "base/containers/hash_tables.h" instead. |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 472 | # Access to a protected member _XX of a client class |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 473 | # pylint: disable=protected-access |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 474 | self.cpplint._re_pattern_templates = [ |
danakj@chromium.org | 1827852 | 2013-06-11 22:42:32 +0000 | [diff] [blame] | 475 | (a, b, 'base/containers/hash_tables.h') |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 476 | if header in ('<hash_map>', '<hash_set>') else (a, b, header) |
| 477 | for (a, b, header) in cpplint._re_pattern_templates |
| 478 | ] |
| 479 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 480 | def PresubmitLocalPath(self): |
| 481 | """Returns the local path of the presubmit script currently being run. |
| 482 | |
| 483 | This is useful if you don't want to hard-code absolute paths in the |
| 484 | presubmit script. For example, It can be used to find another file |
| 485 | relative to the PRESUBMIT.py script, so the whole tree can be branched and |
| 486 | the presubmit script still works, without editing its content. |
| 487 | """ |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 488 | return self._current_presubmit_path |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 489 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 490 | def AffectedFiles(self, include_deletes=True, file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 491 | """Same as input_api.change.AffectedFiles() except only lists files |
| 492 | (and optionally directories) in the same directory as the current presubmit |
| 493 | script, or subdirectories thereof. |
| 494 | """ |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 495 | dir_with_slash = normpath("%s/" % self.PresubmitLocalPath()) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 496 | if len(dir_with_slash) == 1: |
| 497 | dir_with_slash = '' |
sail@chromium.org | 5538e02 | 2011-05-12 17:53:16 +0000 | [diff] [blame] | 498 | |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 499 | return filter( |
| 500 | lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash), |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 501 | self.change.AffectedFiles(include_deletes, file_filter)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 502 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 503 | def LocalPaths(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 504 | """Returns local paths of input_api.AffectedFiles().""" |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 505 | paths = [af.LocalPath() for af in self.AffectedFiles()] |
pgervais@chromium.org | 2f64f78 | 2014-04-25 00:12:33 +0000 | [diff] [blame] | 506 | logging.debug("LocalPaths: %s", paths) |
| 507 | return paths |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 508 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 509 | def AbsoluteLocalPaths(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 510 | """Returns absolute local paths of input_api.AffectedFiles().""" |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 511 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles()] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 512 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 513 | def AffectedTestableFiles(self, include_deletes=None): |
| 514 | """Same as input_api.change.AffectedTestableFiles() except only lists files |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 515 | in the same directory as the current presubmit script, or subdirectories |
| 516 | thereof. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 517 | """ |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 518 | if include_deletes is not None: |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 519 | warn("AffectedTestableFiles(include_deletes=%s)" |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 520 | " is deprecated and ignored" % str(include_deletes), |
| 521 | category=DeprecationWarning, |
| 522 | stacklevel=2) |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 523 | return filter(lambda x: x.IsTestableFile(), |
| 524 | self.AffectedFiles(include_deletes=False)) |
| 525 | |
| 526 | def AffectedTextFiles(self, include_deletes=None): |
| 527 | """An alias to AffectedTestableFiles for backwards compatibility.""" |
| 528 | return self.AffectedTestableFiles(include_deletes=include_deletes) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 529 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 530 | def FilterSourceFile(self, affected_file, white_list=None, black_list=None): |
| 531 | """Filters out files that aren't considered "source file". |
| 532 | |
| 533 | If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST |
| 534 | and InputApi.DEFAULT_BLACK_LIST is used respectively. |
| 535 | |
| 536 | The lists will be compiled as regular expression and |
| 537 | AffectedFile.LocalPath() needs to pass both list. |
| 538 | |
| 539 | Note: Copy-paste this function to suit your needs or use a lambda function. |
| 540 | """ |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 541 | def Find(affected_file, items): |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 542 | local_path = affected_file.LocalPath() |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 543 | for item in items: |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 544 | if self.re.match(item, local_path): |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 545 | return True |
| 546 | return False |
| 547 | return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and |
| 548 | not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST)) |
| 549 | |
| 550 | def AffectedSourceFiles(self, source_file): |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 551 | """Filter the list of AffectedTestableFiles by the function source_file. |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 552 | |
| 553 | If source_file is None, InputApi.FilterSourceFile() is used. |
| 554 | """ |
| 555 | if not source_file: |
| 556 | source_file = self.FilterSourceFile |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 557 | return filter(source_file, self.AffectedTestableFiles()) |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 558 | |
| 559 | def RightHandSideLines(self, source_file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 560 | """An iterator over all text lines in "new" version of changed files. |
| 561 | |
| 562 | Only lists lines from new or modified text files in the change that are |
| 563 | contained by the directory of the currently executing presubmit script. |
| 564 | |
| 565 | This is useful for doing line-by-line regex checks, like checking for |
| 566 | trailing whitespace. |
| 567 | |
| 568 | Yields: |
| 569 | a 3 tuple: |
| 570 | the AffectedFile instance of the current file; |
| 571 | integer line number (1-based); and |
| 572 | the contents of the line as a string. |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 573 | |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 574 | Note: The carriage return (LF or CR) is stripped off. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 575 | """ |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 576 | files = self.AffectedSourceFiles(source_file_filter) |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 577 | return _RightHandSideLinesImpl(files) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 578 | |
maruel@chromium.org | e3608df | 2009-11-10 20:22:57 +0000 | [diff] [blame] | 579 | def ReadFile(self, file_item, mode='r'): |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 580 | """Reads an arbitrary file. |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 581 | |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 582 | Deny reading anything outside the repository. |
| 583 | """ |
maruel@chromium.org | e3608df | 2009-11-10 20:22:57 +0000 | [diff] [blame] | 584 | if isinstance(file_item, AffectedFile): |
| 585 | file_item = file_item.AbsoluteLocalPath() |
| 586 | if not file_item.startswith(self.change.RepositoryRoot()): |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 587 | raise IOError('Access outside the repository root is denied.') |
maruel@chromium.org | 5aeb7dd | 2009-11-17 18:09:01 +0000 | [diff] [blame] | 588 | return gclient_utils.FileRead(file_item, mode) |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 589 | |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 18:07:58 +0100 | [diff] [blame] | 590 | def CreateTemporaryFile(self, **kwargs): |
| 591 | """Returns a named temporary file that must be removed with a call to |
| 592 | RemoveTemporaryFiles(). |
| 593 | |
| 594 | All keyword arguments are forwarded to tempfile.NamedTemporaryFile(), |
| 595 | except for |delete|, which is always set to False. |
| 596 | |
| 597 | Presubmit checks that need to create a temporary file and pass it for |
| 598 | reading should use this function instead of NamedTemporaryFile(), as |
| 599 | Windows fails to open a file that is already open for writing. |
| 600 | |
| 601 | with input_api.CreateTemporaryFile() as f: |
| 602 | f.write('xyz') |
| 603 | f.close() |
| 604 | input_api.subprocess.check_output(['script-that', '--reads-from', |
| 605 | f.name]) |
| 606 | |
| 607 | |
| 608 | Note that callers of CreateTemporaryFile() should not worry about removing |
| 609 | any temporary file; this is done transparently by the presubmit handling |
| 610 | code. |
| 611 | """ |
| 612 | if 'delete' in kwargs: |
| 613 | # Prevent users from passing |delete|; we take care of file deletion |
| 614 | # ourselves and this prevents unintuitive error messages when we pass |
| 615 | # delete=False and 'delete' is also in kwargs. |
| 616 | raise TypeError('CreateTemporaryFile() does not take a "delete" ' |
| 617 | 'argument, file deletion is handled automatically by ' |
| 618 | 'the same presubmit_support code that creates InputApi ' |
| 619 | 'objects.') |
| 620 | temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs) |
| 621 | self._named_temporary_files.append(temp_file.name) |
| 622 | return temp_file |
| 623 | |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 624 | @property |
| 625 | def tbr(self): |
| 626 | """Returns if a change is TBR'ed.""" |
Jeremy Roman | dce2250 | 2017-06-20 15:37:29 -0400 | [diff] [blame] | 627 | return 'TBR' in self.change.tags or self.change.TBRsFromDescription() |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 628 | |
maruel@chromium.org | ffeb2f3 | 2013-12-03 13:55:22 +0000 | [diff] [blame] | 629 | def RunTests(self, tests_mix, parallel=True): |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 630 | tests = [] |
| 631 | msgs = [] |
| 632 | for t in tests_mix: |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 633 | if isinstance(t, OutputApi.PresubmitResult): |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 634 | msgs.append(t) |
| 635 | else: |
| 636 | assert issubclass(t.message, _PresubmitResult) |
| 637 | tests.append(t) |
maruel@chromium.org | ffeb2f3 | 2013-12-03 13:55:22 +0000 | [diff] [blame] | 638 | if self.verbose: |
| 639 | t.info = _PresubmitNotifyResult |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 640 | if len(tests) > 1 and parallel: |
| 641 | # async recipe works around multiprocessing bug handling Ctrl-C |
| 642 | msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999)) |
| 643 | else: |
| 644 | msgs.extend(map(CallCommand, tests)) |
| 645 | return [m for m in msgs if m] |
| 646 | |
| 647 | def ShutdownPool(self): |
| 648 | self._run_tests_pool.close() |
| 649 | self._run_tests_pool.join() |
| 650 | self._run_tests_pool = None |
scottmg | 86099d7 | 2016-09-01 09:16:51 -0700 | [diff] [blame] | 651 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 652 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 653 | class _DiffCache(object): |
| 654 | """Caches diffs retrieved from a particular SCM.""" |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 655 | def __init__(self, upstream=None): |
| 656 | """Stores the upstream revision against which all diffs will be computed.""" |
| 657 | self._upstream = upstream |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 658 | |
| 659 | def GetDiff(self, path, local_root): |
| 660 | """Get the diff for a particular path.""" |
| 661 | raise NotImplementedError() |
| 662 | |
Daniel Cheng | 7a1f04d | 2017-03-21 19:12:31 -0700 | [diff] [blame] | 663 | def GetOldContents(self, path, local_root): |
| 664 | """Get the old version for a particular path.""" |
| 665 | raise NotImplementedError() |
| 666 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 667 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 668 | class _GitDiffCache(_DiffCache): |
| 669 | """DiffCache implementation for git; gets all file diffs at once.""" |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 670 | def __init__(self, upstream): |
| 671 | super(_GitDiffCache, self).__init__(upstream=upstream) |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 672 | self._diffs_by_file = None |
| 673 | |
| 674 | def GetDiff(self, path, local_root): |
| 675 | if not self._diffs_by_file: |
| 676 | # Compute a single diff for all files and parse the output; should |
| 677 | # with git this is much faster than computing one diff for each file. |
| 678 | diffs = {} |
| 679 | |
| 680 | # Don't specify any filenames below, because there are command line length |
| 681 | # limits on some platforms and GenerateDiff would fail. |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 682 | unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True, |
| 683 | branch=self._upstream) |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 684 | |
| 685 | # This regex matches the path twice, separated by a space. Note that |
| 686 | # filename itself may contain spaces. |
| 687 | file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$') |
| 688 | current_diff = [] |
| 689 | keep_line_endings = True |
| 690 | for x in unified_diff.splitlines(keep_line_endings): |
| 691 | match = file_marker.match(x) |
| 692 | if match: |
| 693 | # Marks the start of a new per-file section. |
| 694 | diffs[match.group('filename')] = current_diff = [x] |
| 695 | elif x.startswith('diff --git'): |
| 696 | raise PresubmitFailure('Unexpected diff line: %s' % x) |
| 697 | else: |
| 698 | current_diff.append(x) |
| 699 | |
| 700 | self._diffs_by_file = dict( |
| 701 | (normpath(path), ''.join(diff)) for path, diff in diffs.items()) |
| 702 | |
| 703 | if path not in self._diffs_by_file: |
| 704 | raise PresubmitFailure( |
| 705 | 'Unified diff did not contain entry for file %s' % path) |
| 706 | |
| 707 | return self._diffs_by_file[path] |
| 708 | |
Daniel Cheng | 7a1f04d | 2017-03-21 19:12:31 -0700 | [diff] [blame] | 709 | def GetOldContents(self, path, local_root): |
| 710 | return scm.GIT.GetOldContents(local_root, path, branch=self._upstream) |
| 711 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 712 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 713 | class AffectedFile(object): |
| 714 | """Representation of a file in a change.""" |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 715 | |
| 716 | DIFF_CACHE = _DiffCache |
| 717 | |
maruel@chromium.org | b17b55b | 2010-11-03 14:42:37 +0000 | [diff] [blame] | 718 | # Method could be a function |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 719 | # pylint: disable=no-self-use |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 720 | def __init__(self, path, action, repository_root, diff_cache): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 721 | self._path = path |
| 722 | self._action = action |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 723 | self._local_root = repository_root |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 724 | self._is_directory = None |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 725 | self._cached_changed_contents = None |
| 726 | self._cached_new_contents = None |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 727 | self._diff_cache = diff_cache |
tobiasjs | 2836bcf | 2016-08-16 04:08:16 -0700 | [diff] [blame] | 728 | logging.debug('%s(%s)', self.__class__.__name__, self._path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 729 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 730 | def LocalPath(self): |
| 731 | """Returns the path of this file on the local disk relative to client root. |
Andrew Grieve | 92b8b99 | 2017-11-02 09:42:24 -0400 | [diff] [blame] | 732 | |
| 733 | This should be used for error messages but not for accessing files, |
| 734 | because presubmit checks are run with CWD=PresubmitLocalPath() (which is |
| 735 | often != client root). |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 736 | """ |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 737 | return normpath(self._path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 738 | |
| 739 | def AbsoluteLocalPath(self): |
| 740 | """Returns the absolute path of this file on the local disk. |
| 741 | """ |
chase@chromium.org | 8e416c8 | 2009-10-06 04:30:44 +0000 | [diff] [blame] | 742 | return os.path.abspath(os.path.join(self._local_root, self.LocalPath())) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 743 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 744 | def Action(self): |
| 745 | """Returns the action on this opened file, e.g. A, M, D, etc.""" |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 746 | return self._action |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 747 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 748 | def IsTestableFile(self): |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 749 | """Returns True if the file is a text file and not a binary file. |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 750 | |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 751 | Deleted files are not text file.""" |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 752 | raise NotImplementedError() # Implement when needed |
| 753 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 754 | def IsTextFile(self): |
| 755 | """An alias to IsTestableFile for backwards compatibility.""" |
| 756 | return self.IsTestableFile() |
| 757 | |
Daniel Cheng | 7a1f04d | 2017-03-21 19:12:31 -0700 | [diff] [blame] | 758 | def OldContents(self): |
| 759 | """Returns an iterator over the lines in the old version of file. |
| 760 | |
Daniel Cheng | 2da34fe | 2017-03-21 20:42:12 -0700 | [diff] [blame] | 761 | The old version is the file before any modifications in the user's |
| 762 | workspace, i.e. the "left hand side". |
Daniel Cheng | 7a1f04d | 2017-03-21 19:12:31 -0700 | [diff] [blame] | 763 | |
| 764 | Contents will be empty if the file is a directory or does not exist. |
| 765 | Note: The carriage returns (LF or CR) are stripped off. |
| 766 | """ |
| 767 | return self._diff_cache.GetOldContents(self.LocalPath(), |
| 768 | self._local_root).splitlines() |
| 769 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 770 | def NewContents(self): |
| 771 | """Returns an iterator over the lines in the new version of file. |
| 772 | |
| 773 | The new version is the file in the user's workspace, i.e. the "right hand |
| 774 | side". |
| 775 | |
| 776 | Contents will be empty if the file is a directory or does not exist. |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 777 | Note: The carriage returns (LF or CR) are stripped off. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 778 | """ |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 779 | if self._cached_new_contents is None: |
| 780 | self._cached_new_contents = [] |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 781 | try: |
| 782 | self._cached_new_contents = gclient_utils.FileRead( |
| 783 | self.AbsoluteLocalPath(), 'rU').splitlines() |
| 784 | except IOError: |
| 785 | pass # File not found? That's fine; maybe it was deleted. |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 786 | return self._cached_new_contents[:] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 787 | |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 788 | def ChangedContents(self): |
| 789 | """Returns a list of tuples (line number, line text) of all new lines. |
| 790 | |
| 791 | This relies on the scm diff output describing each changed code section |
| 792 | with a line of the form |
| 793 | |
| 794 | ^@@ <old line num>,<old size> <new line num>,<new size> @@$ |
| 795 | """ |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 796 | if self._cached_changed_contents is not None: |
| 797 | return self._cached_changed_contents[:] |
| 798 | self._cached_changed_contents = [] |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 799 | line_num = 0 |
| 800 | |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 801 | for line in self.GenerateScmDiff().splitlines(): |
| 802 | m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line) |
| 803 | if m: |
| 804 | line_num = int(m.groups(1)[0]) |
| 805 | continue |
| 806 | if line.startswith('+') and not line.startswith('++'): |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 807 | self._cached_changed_contents.append((line_num, line[1:])) |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 808 | if not line.startswith('-'): |
| 809 | line_num += 1 |
nick@chromium.org | 2a3ab7e | 2011-04-27 22:06:27 +0000 | [diff] [blame] | 810 | return self._cached_changed_contents[:] |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 811 | |
maruel@chromium.org | 5de1397 | 2009-06-10 18:16:06 +0000 | [diff] [blame] | 812 | def __str__(self): |
| 813 | return self.LocalPath() |
| 814 | |
maruel@chromium.org | ab05d58 | 2011-02-09 23:41:22 +0000 | [diff] [blame] | 815 | def GenerateScmDiff(self): |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 816 | return self._diff_cache.GetDiff(self.LocalPath(), self._local_root) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 817 | |
maruel@chromium.org | 58407af | 2011-04-12 23:15:57 +0000 | [diff] [blame] | 818 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 819 | class GitAffectedFile(AffectedFile): |
| 820 | """Representation of a file in a change out of a git checkout.""" |
maruel@chromium.org | b17b55b | 2010-11-03 14:42:37 +0000 | [diff] [blame] | 821 | # Method 'NNN' is abstract in class 'NNN' but is not overridden |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 822 | # pylint: disable=abstract-method |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 823 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 824 | DIFF_CACHE = _GitDiffCache |
| 825 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 826 | def __init__(self, *args, **kwargs): |
| 827 | AffectedFile.__init__(self, *args, **kwargs) |
| 828 | self._server_path = None |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 829 | self._is_testable_file = None |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 830 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 831 | def IsTestableFile(self): |
| 832 | if self._is_testable_file is None: |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 833 | if self.Action() == 'D': |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 834 | # A deleted file is not testable. |
| 835 | self._is_testable_file = False |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 836 | else: |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 837 | self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath()) |
| 838 | return self._is_testable_file |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 839 | |
maruel@chromium.org | c193875 | 2011-04-12 23:11:13 +0000 | [diff] [blame] | 840 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 841 | class Change(object): |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 842 | """Describe a change. |
| 843 | |
| 844 | Used directly by the presubmit scripts to query the current change being |
| 845 | tested. |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 846 | |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 847 | Instance members: |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 848 | tags: Dictionary of KEY=VALUE pairs found in the change description. |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 849 | self.KEY: equivalent to tags['KEY'] |
| 850 | """ |
| 851 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 852 | _AFFECTED_FILES = AffectedFile |
| 853 | |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 854 | # Matches key/value (or "tag") lines in changelist descriptions. |
maruel@chromium.org | 428342a | 2011-11-10 15:46:33 +0000 | [diff] [blame] | 855 | TAG_LINE_RE = re.compile( |
maruel@chromium.org | c6f60e8 | 2013-04-19 17:01:57 +0000 | [diff] [blame] | 856 | '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$') |
maruel@chromium.org | c193875 | 2011-04-12 23:11:13 +0000 | [diff] [blame] | 857 | scm = '' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 858 | |
maruel@chromium.org | 58407af | 2011-04-12 23:15:57 +0000 | [diff] [blame] | 859 | def __init__( |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 860 | self, name, description, local_root, files, issue, patchset, author, |
| 861 | upstream=None): |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 862 | if files is None: |
| 863 | files = [] |
| 864 | self._name = name |
chase@chromium.org | 8e416c8 | 2009-10-06 04:30:44 +0000 | [diff] [blame] | 865 | # Convert root into an absolute path. |
| 866 | self._local_root = os.path.abspath(local_root) |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 867 | self._upstream = upstream |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 868 | self.issue = issue |
| 869 | self.patchset = patchset |
maruel@chromium.org | 58407af | 2011-04-12 23:15:57 +0000 | [diff] [blame] | 870 | self.author_email = author |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 871 | |
isherman@chromium.org | b5cded6 | 2014-03-25 17:47:57 +0000 | [diff] [blame] | 872 | self._full_description = '' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 873 | self.tags = {} |
isherman@chromium.org | b5cded6 | 2014-03-25 17:47:57 +0000 | [diff] [blame] | 874 | self._description_without_tags = '' |
| 875 | self.SetDescriptionText(description) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 876 | |
maruel@chromium.org | e085d81 | 2011-10-10 19:49:15 +0000 | [diff] [blame] | 877 | assert all( |
| 878 | (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files |
| 879 | |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 880 | diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream) |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 881 | self._affected_files = [ |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 882 | self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache) |
| 883 | for action, path in files |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 884 | ] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 885 | |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 886 | def Name(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 887 | """Returns the change name.""" |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 888 | return self._name |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 889 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 890 | def DescriptionText(self): |
| 891 | """Returns the user-entered changelist description, minus tags. |
| 892 | |
| 893 | Any line in the user-provided description starting with e.g. "FOO=" |
| 894 | (whitespace permitted before and around) is considered a tag line. Such |
| 895 | lines are stripped out of the description this function returns. |
| 896 | """ |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 897 | return self._description_without_tags |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 898 | |
| 899 | def FullDescriptionText(self): |
| 900 | """Returns the complete changelist description including tags.""" |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 901 | return self._full_description |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 902 | |
isherman@chromium.org | b5cded6 | 2014-03-25 17:47:57 +0000 | [diff] [blame] | 903 | def SetDescriptionText(self, description): |
| 904 | """Sets the full description text (including tags) to |description|. |
pgervais@chromium.org | 92c3009 | 2014-04-15 00:30:37 +0000 | [diff] [blame] | 905 | |
isherman@chromium.org | b5cded6 | 2014-03-25 17:47:57 +0000 | [diff] [blame] | 906 | Also updates the list of tags.""" |
| 907 | self._full_description = description |
| 908 | |
| 909 | # From the description text, build up a dictionary of key/value pairs |
| 910 | # plus the description minus all key/value or "tag" lines. |
| 911 | description_without_tags = [] |
| 912 | self.tags = {} |
| 913 | for line in self._full_description.splitlines(): |
| 914 | m = self.TAG_LINE_RE.match(line) |
| 915 | if m: |
| 916 | self.tags[m.group('key')] = m.group('value') |
| 917 | else: |
| 918 | description_without_tags.append(line) |
| 919 | |
| 920 | # Change back to text and remove whitespace at end. |
| 921 | self._description_without_tags = ( |
| 922 | '\n'.join(description_without_tags).rstrip()) |
| 923 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 924 | def RepositoryRoot(self): |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 925 | """Returns the repository (checkout) root directory for this change, |
| 926 | as an absolute path. |
| 927 | """ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 928 | return self._local_root |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 929 | |
| 930 | def __getattr__(self, attr): |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 931 | """Return tags directly as attributes on the object.""" |
| 932 | if not re.match(r"^[A-Z_]*$", attr): |
| 933 | raise AttributeError(self, attr) |
maruel@chromium.org | e1a524f | 2009-05-27 14:43:46 +0000 | [diff] [blame] | 934 | return self.tags.get(attr) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 935 | |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 936 | def BugsFromDescription(self): |
| 937 | """Returns all bugs referenced in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 14:29:00 -0700 | [diff] [blame] | 938 | tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()] |
| 939 | footers = git_footers.parse_footers(self._full_description).get('Bug', []) |
| 940 | return sorted(set(tags + footers)) |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 941 | |
| 942 | def ReviewersFromDescription(self): |
| 943 | """Returns all reviewers listed in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 14:29:00 -0700 | [diff] [blame] | 944 | # We don't support a "R:" git-footer for reviewers; that is in metadata. |
| 945 | tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()] |
| 946 | return sorted(set(tags)) |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 947 | |
| 948 | def TBRsFromDescription(self): |
| 949 | """Returns all TBR reviewers listed in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 14:29:00 -0700 | [diff] [blame] | 950 | tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()] |
| 951 | # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically |
| 952 | # determined by self-CR+1s. |
| 953 | footers = git_footers.parse_footers(self._full_description).get('Tbr', []) |
| 954 | return sorted(set(tags + footers)) |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 955 | |
| 956 | # TODO(agable): Delete these once we're sure they're unused. |
| 957 | @property |
| 958 | def BUG(self): |
| 959 | return ','.join(self.BugsFromDescription()) |
| 960 | @property |
| 961 | def R(self): |
| 962 | return ','.join(self.ReviewersFromDescription()) |
| 963 | @property |
| 964 | def TBR(self): |
| 965 | return ','.join(self.TBRsFromDescription()) |
| 966 | |
agable@chromium.org | 40a3d0b | 2014-05-15 01:59:16 +0000 | [diff] [blame] | 967 | def AllFiles(self, root=None): |
| 968 | """List all files under source control in the repo.""" |
| 969 | raise NotImplementedError() |
| 970 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 971 | def AffectedFiles(self, include_deletes=True, file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 972 | """Returns a list of AffectedFile instances for all files in the change. |
| 973 | |
| 974 | Args: |
| 975 | include_deletes: If false, deleted files will be filtered out. |
sail@chromium.org | 5538e02 | 2011-05-12 17:53:16 +0000 | [diff] [blame] | 976 | file_filter: An additional filter to apply. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 977 | |
| 978 | Returns: |
| 979 | [AffectedFile(path, action), AffectedFile(path, action)] |
| 980 | """ |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 981 | affected = filter(file_filter, self._affected_files) |
sail@chromium.org | 5538e02 | 2011-05-12 17:53:16 +0000 | [diff] [blame] | 982 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 983 | if include_deletes: |
| 984 | return affected |
Lei Zhang | 9611c4c | 2017-04-04 01:41:56 -0700 | [diff] [blame] | 985 | return filter(lambda x: x.Action() != 'D', affected) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 986 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 987 | def AffectedTestableFiles(self, include_deletes=None): |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 988 | """Return a list of the existing text files in a change.""" |
| 989 | if include_deletes is not None: |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 990 | warn("AffectedTeestableFiles(include_deletes=%s)" |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 991 | " is deprecated and ignored" % str(include_deletes), |
| 992 | category=DeprecationWarning, |
| 993 | stacklevel=2) |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 994 | return filter(lambda x: x.IsTestableFile(), |
| 995 | self.AffectedFiles(include_deletes=False)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 996 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 997 | def AffectedTextFiles(self, include_deletes=None): |
| 998 | """An alias to AffectedTestableFiles for backwards compatibility.""" |
| 999 | return self.AffectedTestableFiles(include_deletes=include_deletes) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1000 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1001 | def LocalPaths(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1002 | """Convenience function.""" |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1003 | return [af.LocalPath() for af in self.AffectedFiles()] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1004 | |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1005 | def AbsoluteLocalPaths(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1006 | """Convenience function.""" |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1007 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles()] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1008 | |
| 1009 | def RightHandSideLines(self): |
| 1010 | """An iterator over all text lines in "new" version of changed files. |
| 1011 | |
| 1012 | Lists lines from new or modified text files in the change. |
| 1013 | |
| 1014 | This is useful for doing line-by-line regex checks, like checking for |
| 1015 | trailing whitespace. |
| 1016 | |
| 1017 | Yields: |
| 1018 | a 3 tuple: |
| 1019 | the AffectedFile instance of the current file; |
| 1020 | integer line number (1-based); and |
| 1021 | the contents of the line as a string. |
| 1022 | """ |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 1023 | return _RightHandSideLinesImpl( |
| 1024 | x for x in self.AffectedFiles(include_deletes=False) |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1025 | if x.IsTestableFile()) |
agable@chromium.org | 40a3d0b | 2014-05-15 01:59:16 +0000 | [diff] [blame] | 1026 | |
Jochen Eisinger | d0573ec | 2017-04-13 10:55:06 +0200 | [diff] [blame] | 1027 | def OriginalOwnersFiles(self): |
| 1028 | """A map from path names of affected OWNERS files to their old content.""" |
| 1029 | def owners_file_filter(f): |
| 1030 | return 'OWNERS' in os.path.split(f.LocalPath())[1] |
| 1031 | files = self.AffectedFiles(file_filter=owners_file_filter) |
| 1032 | return dict([(f.LocalPath(), f.OldContents()) for f in files]) |
| 1033 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1034 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 1035 | class GitChange(Change): |
| 1036 | _AFFECTED_FILES = GitAffectedFile |
maruel@chromium.org | c193875 | 2011-04-12 23:11:13 +0000 | [diff] [blame] | 1037 | scm = 'git' |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 1038 | |
agable@chromium.org | 40a3d0b | 2014-05-15 01:59:16 +0000 | [diff] [blame] | 1039 | def AllFiles(self, root=None): |
| 1040 | """List all files under source control in the repo.""" |
| 1041 | root = root or self.RepositoryRoot() |
| 1042 | return subprocess.check_output( |
Aaron Gable | 7817f02 | 2017-12-12 09:43:17 -0800 | [diff] [blame] | 1043 | ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'], |
| 1044 | cwd=root).splitlines() |
agable@chromium.org | 40a3d0b | 2014-05-15 01:59:16 +0000 | [diff] [blame] | 1045 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 1046 | |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 1047 | def ListRelevantPresubmitFiles(files, root): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1048 | """Finds all presubmit files that apply to a given set of source files. |
| 1049 | |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1050 | If inherit-review-settings-ok is present right under root, looks for |
| 1051 | PRESUBMIT.py in directories enclosing root. |
| 1052 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1053 | Args: |
| 1054 | files: An iterable container containing file paths. |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 1055 | root: Path where to stop searching. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1056 | |
| 1057 | Return: |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 1058 | List of absolute paths of the existing PRESUBMIT.py scripts. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1059 | """ |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1060 | files = [normpath(os.path.join(root, f)) for f in files] |
| 1061 | |
| 1062 | # List all the individual directories containing files. |
| 1063 | directories = set([os.path.dirname(f) for f in files]) |
| 1064 | |
| 1065 | # Ignore root if inherit-review-settings-ok is present. |
| 1066 | if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')): |
| 1067 | root = None |
| 1068 | |
| 1069 | # Collect all unique directories that may contain PRESUBMIT.py. |
| 1070 | candidates = set() |
| 1071 | for directory in directories: |
| 1072 | while True: |
| 1073 | if directory in candidates: |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1074 | break |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1075 | candidates.add(directory) |
| 1076 | if directory == root: |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 1077 | break |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1078 | parent_dir = os.path.dirname(directory) |
| 1079 | if parent_dir == directory: |
| 1080 | # We hit the system root directory. |
| 1081 | break |
| 1082 | directory = parent_dir |
| 1083 | |
| 1084 | # Look for PRESUBMIT.py in all candidate directories. |
| 1085 | results = [] |
| 1086 | for directory in sorted(list(candidates)): |
tobiasjs | ff061c0 | 2016-08-17 03:23:57 -0700 | [diff] [blame] | 1087 | try: |
| 1088 | for f in os.listdir(directory): |
| 1089 | p = os.path.join(directory, f) |
| 1090 | if os.path.isfile(p) and re.match( |
| 1091 | r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'): |
| 1092 | results.append(p) |
| 1093 | except OSError: |
| 1094 | pass |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1095 | |
tobiasjs | 2836bcf | 2016-08-16 04:08:16 -0700 | [diff] [blame] | 1096 | logging.debug('Presubmit files: %s', ','.join(results)) |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1097 | return results |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1098 | |
| 1099 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 1100 | class GetTryMastersExecuter(object): |
| 1101 | @staticmethod |
| 1102 | def ExecPresubmitScript(script_text, presubmit_path, project, change): |
| 1103 | """Executes GetPreferredTryMasters() from a single presubmit script. |
| 1104 | |
| 1105 | Args: |
| 1106 | script_text: The text of the presubmit script. |
| 1107 | presubmit_path: Project script to run. |
| 1108 | project: Project name to pass to presubmit script for bot selection. |
| 1109 | |
| 1110 | Return: |
| 1111 | A map of try masters to map of builders to set of tests. |
| 1112 | """ |
| 1113 | context = {} |
| 1114 | try: |
| 1115 | exec script_text in context |
| 1116 | except Exception, e: |
| 1117 | raise PresubmitFailure('"%s" had an exception.\n%s' |
| 1118 | % (presubmit_path, e)) |
| 1119 | |
| 1120 | function_name = 'GetPreferredTryMasters' |
| 1121 | if function_name not in context: |
| 1122 | return {} |
| 1123 | get_preferred_try_masters = context[function_name] |
| 1124 | if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2: |
| 1125 | raise PresubmitFailure( |
| 1126 | 'Expected function "GetPreferredTryMasters" to take two arguments.') |
| 1127 | return get_preferred_try_masters(project, change) |
| 1128 | |
| 1129 | |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 1130 | class GetPostUploadExecuter(object): |
| 1131 | @staticmethod |
| 1132 | def ExecPresubmitScript(script_text, presubmit_path, cl, change): |
| 1133 | """Executes PostUploadHook() from a single presubmit script. |
| 1134 | |
| 1135 | Args: |
| 1136 | script_text: The text of the presubmit script. |
| 1137 | presubmit_path: Project script to run. |
| 1138 | cl: The Changelist object. |
| 1139 | change: The Change object. |
| 1140 | |
| 1141 | Return: |
| 1142 | A list of results objects. |
| 1143 | """ |
| 1144 | context = {} |
| 1145 | try: |
| 1146 | exec script_text in context |
| 1147 | except Exception, e: |
| 1148 | raise PresubmitFailure('"%s" had an exception.\n%s' |
| 1149 | % (presubmit_path, e)) |
| 1150 | |
| 1151 | function_name = 'PostUploadHook' |
| 1152 | if function_name not in context: |
| 1153 | return {} |
| 1154 | post_upload_hook = context[function_name] |
| 1155 | if not len(inspect.getargspec(post_upload_hook)[0]) == 3: |
| 1156 | raise PresubmitFailure( |
| 1157 | 'Expected function "PostUploadHook" to take three arguments.') |
| 1158 | return post_upload_hook(cl, change, OutputApi(False)) |
| 1159 | |
| 1160 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 1161 | def _MergeMasters(masters1, masters2): |
| 1162 | """Merges two master maps. Merges also the tests of each builder.""" |
| 1163 | result = {} |
| 1164 | for (master, builders) in itertools.chain(masters1.iteritems(), |
| 1165 | masters2.iteritems()): |
| 1166 | new_builders = result.setdefault(master, {}) |
| 1167 | for (builder, tests) in builders.iteritems(): |
| 1168 | new_builders.setdefault(builder, set([])).update(tests) |
| 1169 | return result |
| 1170 | |
| 1171 | |
| 1172 | def DoGetTryMasters(change, |
| 1173 | changed_files, |
| 1174 | repository_root, |
| 1175 | default_presubmit, |
| 1176 | project, |
| 1177 | verbose, |
| 1178 | output_stream): |
| 1179 | """Get the list of try masters from the presubmit scripts. |
| 1180 | |
| 1181 | Args: |
| 1182 | changed_files: List of modified files. |
| 1183 | repository_root: The repository root. |
| 1184 | default_presubmit: A default presubmit script to execute in any case. |
| 1185 | project: Optional name of a project used in selecting trybots. |
| 1186 | verbose: Prints debug info. |
| 1187 | output_stream: A stream to write debug output to. |
| 1188 | |
| 1189 | Return: |
| 1190 | Map of try masters to map of builders to set of tests. |
| 1191 | """ |
| 1192 | presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root) |
| 1193 | if not presubmit_files and verbose: |
| 1194 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
| 1195 | results = {} |
| 1196 | executer = GetTryMastersExecuter() |
| 1197 | |
| 1198 | if default_presubmit: |
| 1199 | if verbose: |
| 1200 | output_stream.write("Running default presubmit script.\n") |
| 1201 | fake_path = os.path.join(repository_root, 'PRESUBMIT.py') |
| 1202 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1203 | default_presubmit, fake_path, project, change)) |
| 1204 | for filename in presubmit_files: |
| 1205 | filename = os.path.abspath(filename) |
| 1206 | if verbose: |
| 1207 | output_stream.write("Running %s\n" % filename) |
| 1208 | # Accept CRLF presubmit script. |
| 1209 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1210 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1211 | presubmit_script, filename, project, change)) |
| 1212 | |
| 1213 | # Make sets to lists again for later JSON serialization. |
| 1214 | for builders in results.itervalues(): |
| 1215 | for builder in builders: |
| 1216 | builders[builder] = list(builders[builder]) |
| 1217 | |
| 1218 | if results and verbose: |
| 1219 | output_stream.write('%s\n' % str(results)) |
| 1220 | return results |
| 1221 | |
| 1222 | |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 1223 | def DoPostUploadExecuter(change, |
| 1224 | cl, |
| 1225 | repository_root, |
| 1226 | verbose, |
| 1227 | output_stream): |
| 1228 | """Execute the post upload hook. |
| 1229 | |
| 1230 | Args: |
| 1231 | change: The Change object. |
| 1232 | cl: The Changelist object. |
| 1233 | repository_root: The repository root. |
| 1234 | verbose: Prints debug info. |
| 1235 | output_stream: A stream to write debug output to. |
| 1236 | """ |
| 1237 | presubmit_files = ListRelevantPresubmitFiles( |
| 1238 | change.LocalPaths(), repository_root) |
| 1239 | if not presubmit_files and verbose: |
| 1240 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
| 1241 | results = [] |
| 1242 | executer = GetPostUploadExecuter() |
| 1243 | # The root presubmit file should be executed after the ones in subdirectories. |
| 1244 | # i.e. the specific post upload hooks should run before the general ones. |
| 1245 | # Thus, reverse the order provided by ListRelevantPresubmitFiles. |
| 1246 | presubmit_files.reverse() |
| 1247 | |
| 1248 | for filename in presubmit_files: |
| 1249 | filename = os.path.abspath(filename) |
| 1250 | if verbose: |
| 1251 | output_stream.write("Running %s\n" % filename) |
| 1252 | # Accept CRLF presubmit script. |
| 1253 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1254 | results.extend(executer.ExecPresubmitScript( |
| 1255 | presubmit_script, filename, cl, change)) |
| 1256 | output_stream.write('\n') |
| 1257 | if results: |
| 1258 | output_stream.write('** Post Upload Hook Messages **\n') |
| 1259 | for result in results: |
| 1260 | result.handle(output_stream) |
| 1261 | output_stream.write('\n') |
| 1262 | |
| 1263 | return results |
| 1264 | |
| 1265 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1266 | class PresubmitExecuter(object): |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 1267 | def __init__(self, change, committing, verbose, |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 1268 | gerrit_obj, dry_run=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1269 | """ |
| 1270 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1271 | change: The Change object. |
agable | 92bec4f | 2016-08-24 09:27:27 -0700 | [diff] [blame] | 1272 | committing: True if 'git cl land' is running, False if 'git cl upload' is. |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1273 | gerrit_obj: provides basic Gerrit codereview functionality. |
| 1274 | dry_run: if true, some Checks will be skipped. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1275 | """ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1276 | self.change = change |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1277 | self.committing = committing |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1278 | self.gerrit = gerrit_obj |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1279 | self.verbose = verbose |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1280 | self.dry_run = dry_run |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1281 | self.more_cc = [] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1282 | |
| 1283 | def ExecPresubmitScript(self, script_text, presubmit_path): |
| 1284 | """Executes a single presubmit script. |
| 1285 | |
| 1286 | Args: |
| 1287 | script_text: The text of the presubmit script. |
| 1288 | presubmit_path: The path to the presubmit file (this will be reported via |
| 1289 | input_api.PresubmitLocalPath()). |
| 1290 | |
| 1291 | Return: |
| 1292 | A list of result objects, empty if no problems. |
| 1293 | """ |
thakis@chromium.org | c6ef53a | 2014-11-04 00:13:54 +0000 | [diff] [blame] | 1294 | |
chase@chromium.org | 8e416c8 | 2009-10-06 04:30:44 +0000 | [diff] [blame] | 1295 | # Change to the presubmit file's directory to support local imports. |
| 1296 | main_path = os.getcwd() |
| 1297 | os.chdir(os.path.dirname(presubmit_path)) |
| 1298 | |
| 1299 | # Load the presubmit script into context. |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 1300 | input_api = InputApi(self.change, presubmit_path, self.committing, |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 1301 | self.verbose, gerrit_obj=self.gerrit, |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 1302 | dry_run=self.dry_run) |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1303 | output_api = OutputApi(self.committing) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1304 | context = {} |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1305 | try: |
| 1306 | exec script_text in context |
| 1307 | except Exception, e: |
| 1308 | raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1309 | |
| 1310 | # These function names must change if we make substantial changes to |
| 1311 | # the presubmit API that are not backwards compatible. |
| 1312 | if self.committing: |
| 1313 | function_name = 'CheckChangeOnCommit' |
| 1314 | else: |
| 1315 | function_name = 'CheckChangeOnUpload' |
| 1316 | if function_name in context: |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 18:07:58 +0100 | [diff] [blame] | 1317 | try: |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1318 | context['__args'] = (input_api, output_api) |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 18:07:58 +0100 | [diff] [blame] | 1319 | logging.debug('Running %s in %s', function_name, presubmit_path) |
| 1320 | result = eval(function_name + '(*__args)', context) |
| 1321 | logging.debug('Running %s done.', function_name) |
Daniel Cheng | d36fce4 | 2017-11-21 21:52:52 -0800 | [diff] [blame] | 1322 | self.more_cc.extend(output_api.more_cc) |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 18:07:58 +0100 | [diff] [blame] | 1323 | finally: |
| 1324 | map(os.remove, input_api._named_temporary_files) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1325 | if not (isinstance(result, types.TupleType) or |
| 1326 | isinstance(result, types.ListType)): |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1327 | raise PresubmitFailure( |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1328 | 'Presubmit functions must return a tuple or list') |
| 1329 | for item in result: |
| 1330 | if not isinstance(item, OutputApi.PresubmitResult): |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1331 | raise PresubmitFailure( |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1332 | 'All presubmit results must be of types derived from ' |
| 1333 | 'output_api.PresubmitResult') |
| 1334 | else: |
| 1335 | result = () # no error since the script doesn't care about current event. |
| 1336 | |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 1337 | input_api.ShutdownPool() |
| 1338 | |
chase@chromium.org | 8e416c8 | 2009-10-06 04:30:44 +0000 | [diff] [blame] | 1339 | # Return the process to the original working directory. |
| 1340 | os.chdir(main_path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1341 | return result |
| 1342 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1343 | def DoPresubmitChecks(change, |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1344 | committing, |
| 1345 | verbose, |
| 1346 | output_stream, |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 1347 | input_stream, |
maruel@chromium.org | b0dfd35 | 2009-06-10 14:12:54 +0000 | [diff] [blame] | 1348 | default_presubmit, |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 1349 | may_prompt, |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 1350 | gerrit_obj, |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1351 | dry_run=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1352 | """Runs all presubmit checks that apply to the files in the change. |
| 1353 | |
| 1354 | This finds all PRESUBMIT.py files in directories enclosing the files in the |
| 1355 | change (up to the repository root) and calls the relevant entrypoint function |
| 1356 | depending on whether the change is being committed or uploaded. |
| 1357 | |
| 1358 | Prints errors, warnings and notifications. Prompts the user for warnings |
| 1359 | when needed. |
| 1360 | |
| 1361 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1362 | change: The Change object. |
agable | 92bec4f | 2016-08-24 09:27:27 -0700 | [diff] [blame] | 1363 | committing: True if 'git cl land' is running, False if 'git cl upload' is. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1364 | verbose: Prints debug info. |
| 1365 | output_stream: A stream to write output from presubmit tests to. |
| 1366 | input_stream: A stream to read input from the user. |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 1367 | default_presubmit: A default presubmit script to execute in any case. |
Quinten Yearsley | 516fe7f | 2016-12-14 11:50:18 -0800 | [diff] [blame] | 1368 | may_prompt: Enable (y/n) questions on warning or error. If False, |
| 1369 | any questions are answered with yes by default. |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1370 | gerrit_obj: provides basic Gerrit codereview functionality. |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1371 | dry_run: if true, some Checks will be skipped. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1372 | |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 1373 | Warning: |
| 1374 | If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream |
| 1375 | SHOULD be sys.stdin. |
| 1376 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1377 | Return: |
dpranke@chromium.org | 5ac2101 | 2011-03-16 02:58:25 +0000 | [diff] [blame] | 1378 | A PresubmitOutput object. Use output.should_continue() to figure out |
| 1379 | if there were errors or warnings and the caller should abort. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1380 | """ |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1381 | old_environ = os.environ |
| 1382 | try: |
| 1383 | # Make sure python subprocesses won't generate .pyc files. |
| 1384 | os.environ = os.environ.copy() |
| 1385 | os.environ['PYTHONDONTWRITEBYTECODE'] = '1' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1386 | |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1387 | output = PresubmitOutput(input_stream, output_stream) |
| 1388 | if committing: |
| 1389 | output.write("Running presubmit commit checks ...\n") |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1390 | else: |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1391 | output.write("Running presubmit upload checks ...\n") |
| 1392 | start_time = time.time() |
| 1393 | presubmit_files = ListRelevantPresubmitFiles( |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1394 | change.AbsoluteLocalPaths(), change.RepositoryRoot()) |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1395 | if not presubmit_files and verbose: |
maruel@chromium.org | fae707b | 2011-09-15 18:57:58 +0000 | [diff] [blame] | 1396 | output.write("Warning, no PRESUBMIT.py found.\n") |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1397 | results = [] |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 1398 | executer = PresubmitExecuter(change, committing, verbose, |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 1399 | gerrit_obj, dry_run) |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1400 | if default_presubmit: |
| 1401 | if verbose: |
| 1402 | output.write("Running default presubmit script.\n") |
| 1403 | fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py') |
| 1404 | results += executer.ExecPresubmitScript(default_presubmit, fake_path) |
| 1405 | for filename in presubmit_files: |
| 1406 | filename = os.path.abspath(filename) |
| 1407 | if verbose: |
| 1408 | output.write("Running %s\n" % filename) |
| 1409 | # Accept CRLF presubmit script. |
| 1410 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1411 | results += executer.ExecPresubmitScript(presubmit_script, filename) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1412 | |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1413 | output.more_cc.extend(executer.more_cc) |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1414 | errors = [] |
| 1415 | notifications = [] |
| 1416 | warnings = [] |
| 1417 | for result in results: |
| 1418 | if result.fatal: |
| 1419 | errors.append(result) |
| 1420 | elif result.should_prompt: |
| 1421 | warnings.append(result) |
| 1422 | else: |
| 1423 | notifications.append(result) |
pam@chromium.org | ed9a083 | 2009-09-09 22:48:55 +0000 | [diff] [blame] | 1424 | |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1425 | output.write('\n') |
| 1426 | for name, items in (('Messages', notifications), |
| 1427 | ('Warnings', warnings), |
| 1428 | ('ERRORS', errors)): |
| 1429 | if items: |
| 1430 | output.write('** Presubmit %s **\n' % name) |
| 1431 | for item in items: |
| 1432 | item.handle(output) |
| 1433 | output.write('\n') |
pam@chromium.org | ed9a083 | 2009-09-09 22:48:55 +0000 | [diff] [blame] | 1434 | |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1435 | total_time = time.time() - start_time |
| 1436 | if total_time > 1.0: |
| 1437 | output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time) |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 1438 | |
Quinten Yearsley | 516fe7f | 2016-12-14 11:50:18 -0800 | [diff] [blame] | 1439 | if errors: |
| 1440 | output.fail() |
| 1441 | elif warnings: |
| 1442 | output.write('There were presubmit warnings. ') |
| 1443 | if may_prompt: |
| 1444 | output.prompt_yes_no('Are you sure you wish to continue? (y/N): ') |
| 1445 | else: |
| 1446 | output.write('Presubmit checks passed.\n') |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1447 | |
| 1448 | global _ASKED_FOR_FEEDBACK |
| 1449 | # Ask for feedback one time out of 5. |
| 1450 | if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK): |
maruel@chromium.org | 1ce8e66 | 2014-01-14 15:23:00 +0000 | [diff] [blame] | 1451 | output.write( |
| 1452 | 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n' |
| 1453 | 'to figure out which PRESUBMIT.py was run, then run git blame\n' |
| 1454 | 'on the file to figure out who to ask for help.\n') |
maruel@chromium.org | ea7c855 | 2011-04-18 14:12:07 +0000 | [diff] [blame] | 1455 | _ASKED_FOR_FEEDBACK = True |
| 1456 | return output |
| 1457 | finally: |
| 1458 | os.environ = old_environ |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1459 | |
| 1460 | |
| 1461 | def ScanSubDirs(mask, recursive): |
| 1462 | if not recursive: |
pgervais@chromium.org | e57b09d | 2014-05-07 00:58:13 +0000 | [diff] [blame] | 1463 | return [x for x in glob.glob(mask) if x not in ('.svn', '.git')] |
Lei Zhang | 9611c4c | 2017-04-04 01:41:56 -0700 | [diff] [blame] | 1464 | |
| 1465 | results = [] |
| 1466 | for root, dirs, files in os.walk('.'): |
| 1467 | if '.svn' in dirs: |
| 1468 | dirs.remove('.svn') |
| 1469 | if '.git' in dirs: |
| 1470 | dirs.remove('.git') |
| 1471 | for name in files: |
| 1472 | if fnmatch.fnmatch(name, mask): |
| 1473 | results.append(os.path.join(root, name)) |
| 1474 | return results |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1475 | |
| 1476 | |
| 1477 | def ParseFiles(args, recursive): |
tobiasjs | 2836bcf | 2016-08-16 04:08:16 -0700 | [diff] [blame] | 1478 | logging.debug('Searching for %s', args) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1479 | files = [] |
| 1480 | for arg in args: |
maruel@chromium.org | e3608df | 2009-11-10 20:22:57 +0000 | [diff] [blame] | 1481 | files.extend([('M', f) for f in ScanSubDirs(arg, recursive)]) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1482 | return files |
| 1483 | |
| 1484 | |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1485 | def load_files(options, args): |
| 1486 | """Tries to determine the SCM.""" |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1487 | files = [] |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1488 | if args: |
| 1489 | files = ParseFiles(args, options.recursive) |
agable | 0b65e73 | 2016-11-22 09:25:46 -0800 | [diff] [blame] | 1490 | change_scm = scm.determine_scm(options.root) |
| 1491 | if change_scm == 'git': |
maruel@chromium.org | 9b31f16 | 2012-01-26 19:02:31 +0000 | [diff] [blame] | 1492 | change_class = GitChange |
agable@chromium.org | 2da1ade | 2014-04-30 17:40:45 +0000 | [diff] [blame] | 1493 | upstream = options.upstream or None |
maruel@chromium.org | 9b31f16 | 2012-01-26 19:02:31 +0000 | [diff] [blame] | 1494 | if not files: |
agable@chromium.org | 2da1ade | 2014-04-30 17:40:45 +0000 | [diff] [blame] | 1495 | files = scm.GIT.CaptureStatus([], options.root, upstream) |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1496 | else: |
tobiasjs | 2836bcf | 2016-08-16 04:08:16 -0700 | [diff] [blame] | 1497 | logging.info('Doesn\'t seem under source control. Got %d files', len(args)) |
maruel@chromium.org | 9b31f16 | 2012-01-26 19:02:31 +0000 | [diff] [blame] | 1498 | if not files: |
| 1499 | return None, None |
| 1500 | change_class = Change |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1501 | return change_class, files |
| 1502 | |
| 1503 | |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 1504 | @contextlib.contextmanager |
| 1505 | def canned_check_filter(method_names): |
| 1506 | filtered = {} |
| 1507 | try: |
| 1508 | for method_name in method_names: |
| 1509 | if not hasattr(presubmit_canned_checks, method_name): |
Aaron Gable | ecee74c | 2018-04-02 15:13:08 -0700 | [diff] [blame] | 1510 | logging.warn('Skipping unknown "canned" check %s' % method_name) |
| 1511 | continue |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 1512 | filtered[method_name] = getattr(presubmit_canned_checks, method_name) |
| 1513 | setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: []) |
| 1514 | yield |
| 1515 | finally: |
| 1516 | for name, method in filtered.iteritems(): |
| 1517 | setattr(presubmit_canned_checks, name, method) |
| 1518 | |
maruel@chromium.org | ffeb2f3 | 2013-12-03 13:55:22 +0000 | [diff] [blame] | 1519 | |
Edward Lesmes | 1ad681e | 2018-04-03 17:15:57 -0400 | [diff] [blame] | 1520 | def CallCommand(cmd_data): |
| 1521 | """Runs an external program, potentially from a child process created by the |
| 1522 | multiprocessing module. |
| 1523 | |
| 1524 | multiprocessing needs a top level function with a single argument. |
| 1525 | |
| 1526 | This function converts invocation of .py files and invocations of "python" to |
| 1527 | vpython invocations. |
| 1528 | """ |
| 1529 | vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython' |
| 1530 | |
| 1531 | cmd = cmd_data.cmd |
| 1532 | if cmd[0] == 'python': |
| 1533 | cmd = list(cmd) |
| 1534 | cmd[0] = vpython |
| 1535 | elif cmd[0].endswith('.py'): |
| 1536 | cmd = [vpython] + cmd |
| 1537 | |
| 1538 | cmd_data.kwargs['stdout'] = subprocess.PIPE |
| 1539 | cmd_data.kwargs['stderr'] = subprocess.STDOUT |
| 1540 | try: |
| 1541 | start = time.time() |
| 1542 | (out, _), code = subprocess.communicate(cmd, **cmd_data.kwargs) |
| 1543 | duration = time.time() - start |
| 1544 | except OSError as e: |
| 1545 | duration = time.time() - start |
| 1546 | return cmd_data.message( |
| 1547 | '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e)) |
| 1548 | if code != 0: |
| 1549 | return cmd_data.message( |
| 1550 | '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out)) |
| 1551 | if cmd_data.info: |
| 1552 | return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration)) |
| 1553 | |
| 1554 | |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 1555 | def main(argv=None): |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1556 | parser = optparse.OptionParser(usage="%prog [options] <files...>", |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1557 | version="%prog " + str(__version__)) |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 1558 | parser.add_option("-c", "--commit", action="store_true", default=False, |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1559 | help="Use commit instead of upload checks") |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 1560 | parser.add_option("-u", "--upload", action="store_false", dest='commit', |
| 1561 | help="Use upload instead of commit checks") |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1562 | parser.add_option("-r", "--recursive", action="store_true", |
| 1563 | help="Act recursively") |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1564 | parser.add_option("-v", "--verbose", action="count", default=0, |
| 1565 | help="Use 2 times for more debug info") |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1566 | parser.add_option("--name", default='no name') |
maruel@chromium.org | 58407af | 2011-04-12 23:15:57 +0000 | [diff] [blame] | 1567 | parser.add_option("--author") |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 1568 | parser.add_option("--description", default='') |
| 1569 | parser.add_option("--issue", type='int', default=0) |
| 1570 | parser.add_option("--patchset", type='int', default=0) |
maruel@chromium.org | b1901a6 | 2010-06-16 00:18:47 +0000 | [diff] [blame] | 1571 | parser.add_option("--root", default=os.getcwd(), |
| 1572 | help="Search for PRESUBMIT.py up to this directory. " |
| 1573 | "If inherit-review-settings-ok is present in this " |
| 1574 | "directory, parent directories up to the root file " |
| 1575 | "system directories will also be searched.") |
agable@chromium.org | 2da1ade | 2014-04-30 17:40:45 +0000 | [diff] [blame] | 1576 | parser.add_option("--upstream", |
| 1577 | help="Git only: the base ref or upstream branch against " |
| 1578 | "which the diff should be computed.") |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 1579 | parser.add_option("--default_presubmit") |
| 1580 | parser.add_option("--may_prompt", action='store_true', default=False) |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 1581 | parser.add_option("--skip_canned", action='append', default=[], |
| 1582 | help="A list of checks to skip which appear in " |
| 1583 | "presubmit_canned_checks. Can be provided multiple times " |
| 1584 | "to skip multiple canned checks.") |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1585 | parser.add_option("--dry_run", action='store_true', |
| 1586 | help=optparse.SUPPRESS_HELP) |
tandrii@chromium.org | 015ebae | 2016-04-25 19:37:22 +0000 | [diff] [blame] | 1587 | parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP) |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1588 | parser.add_option("--gerrit_fetch", action='store_true', |
| 1589 | help=optparse.SUPPRESS_HELP) |
pgervais@chromium.org | 92c3009 | 2014-04-15 00:30:37 +0000 | [diff] [blame] | 1590 | |
maruel@chromium.org | 82e5f28 | 2011-03-17 14:08:55 +0000 | [diff] [blame] | 1591 | options, args = parser.parse_args(argv) |
pgervais@chromium.org | 92c3009 | 2014-04-15 00:30:37 +0000 | [diff] [blame] | 1592 | |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1593 | if options.verbose >= 2: |
maruel@chromium.org | 7444c50 | 2011-02-09 14:02:11 +0000 | [diff] [blame] | 1594 | logging.basicConfig(level=logging.DEBUG) |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1595 | elif options.verbose: |
| 1596 | logging.basicConfig(level=logging.INFO) |
| 1597 | else: |
| 1598 | logging.basicConfig(level=logging.ERROR) |
pgervais@chromium.org | 92c3009 | 2014-04-15 00:30:37 +0000 | [diff] [blame] | 1599 | |
maruel@chromium.org | 5c8c6de | 2011-03-18 16:20:18 +0000 | [diff] [blame] | 1600 | change_class, files = load_files(options, args) |
| 1601 | if not change_class: |
| 1602 | parser.error('For unversioned directory, <files> is not optional.') |
tobiasjs | 2836bcf | 2016-08-16 04:08:16 -0700 | [diff] [blame] | 1603 | logging.info('Found %d file(s).', len(files)) |
pgervais@chromium.org | 92c3009 | 2014-04-15 00:30:37 +0000 | [diff] [blame] | 1604 | |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 1605 | gerrit_obj = None |
tandrii@chromium.org | 015ebae | 2016-04-25 19:37:22 +0000 | [diff] [blame] | 1606 | if options.gerrit_url and options.gerrit_fetch: |
tandrii@chromium.org | 83b1b23 | 2016-04-29 16:33:19 +0000 | [diff] [blame] | 1607 | assert options.issue and options.patchset |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1608 | gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc) |
| 1609 | options.author = gerrit_obj.GetChangeOwner(options.issue) |
| 1610 | options.description = gerrit_obj.GetChangeDescription(options.issue, |
| 1611 | options.patchset) |
tandrii@chromium.org | 015ebae | 2016-04-25 19:37:22 +0000 | [diff] [blame] | 1612 | logging.info('Got author: "%s"', options.author) |
| 1613 | logging.info('Got description: """\n%s\n"""', options.description) |
| 1614 | |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1615 | try: |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 1616 | with canned_check_filter(options.skip_canned): |
| 1617 | results = DoPresubmitChecks( |
| 1618 | change_class(options.name, |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1619 | options.description, |
| 1620 | options.root, |
| 1621 | files, |
| 1622 | options.issue, |
| 1623 | options.patchset, |
| 1624 | options.author, |
| 1625 | upstream=options.upstream), |
iannucci@chromium.org | 8a4a2bc | 2013-03-08 08:13:20 +0000 | [diff] [blame] | 1626 | options.commit, |
| 1627 | options.verbose, |
| 1628 | sys.stdout, |
| 1629 | sys.stdin, |
| 1630 | options.default_presubmit, |
| 1631 | options.may_prompt, |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1632 | gerrit_obj, |
tandrii@chromium.org | 57bafac | 2016-04-28 05:09:03 +0000 | [diff] [blame] | 1633 | options.dry_run) |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1634 | return not results.should_continue() |
| 1635 | except PresubmitFailure, e: |
| 1636 | print >> sys.stderr, e |
| 1637 | print >> sys.stderr, 'Maybe your depot_tools is out of date?' |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 1638 | return 2 |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1639 | |
| 1640 | |
| 1641 | if __name__ == '__main__': |
maruel@chromium.org | 35625c7 | 2011-03-23 17:34:02 +0000 | [diff] [blame] | 1642 | fix_encoding.fix_encoding() |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 1643 | try: |
| 1644 | sys.exit(main()) |
| 1645 | except KeyboardInterrupt: |
| 1646 | sys.stderr.write('interrupted\n') |
sergiyb | f8a3b38 | 2016-07-05 11:21:30 -0700 | [diff] [blame] | 1647 | sys.exit(2) |