Avi Drissman | 2497659 | 2022-09-12 15:24:31 | [diff] [blame] | 1 | # Copyright 2014 The Chromium Authors |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
Chris Hall | 59f8d0c7 | 2020-05-01 07:31:19 | [diff] [blame] | 5 | from collections import defaultdict |
Daniel Cheng | 13ca61a88 | 2017-08-25 15:11:25 | [diff] [blame] | 6 | import fnmatch |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 7 | import json |
| 8 | import os |
| 9 | import re |
| 10 | import subprocess |
| 11 | import sys |
| 12 | |
Daniel Cheng | 264a447d | 2017-09-28 22:17:59 | [diff] [blame] | 13 | # TODO(dcheng): It's kind of horrible that this is copy and pasted from |
| 14 | # presubmit_canned_checks.py, but it's far easier than any of the alternatives. |
| 15 | def _ReportErrorFileAndLine(filename, line_num, dummy_line): |
| 16 | """Default error formatter for _FindNewViolationsOfRule.""" |
| 17 | return '%s:%s' % (filename, line_num) |
| 18 | |
| 19 | |
| 20 | class MockCannedChecks(object): |
| 21 | def _FindNewViolationsOfRule(self, callable_rule, input_api, |
| 22 | source_file_filter=None, |
| 23 | error_formatter=_ReportErrorFileAndLine): |
| 24 | """Find all newly introduced violations of a per-line rule (a callable). |
| 25 | |
| 26 | Arguments: |
| 27 | callable_rule: a callable taking a file extension and line of input and |
| 28 | returning True if the rule is satisfied and False if there was a |
| 29 | problem. |
| 30 | input_api: object to enumerate the affected files. |
| 31 | source_file_filter: a filter to be passed to the input api. |
| 32 | error_formatter: a callable taking (filename, line_number, line) and |
| 33 | returning a formatted error string. |
| 34 | |
| 35 | Returns: |
| 36 | A list of the newly-introduced violations reported by the rule. |
| 37 | """ |
| 38 | errors = [] |
| 39 | for f in input_api.AffectedFiles(include_deletes=False, |
| 40 | file_filter=source_file_filter): |
| 41 | # For speed, we do two passes, checking first the full file. Shelling out |
| 42 | # to the SCM to determine the changed region can be quite expensive on |
| 43 | # Win32. Assuming that most files will be kept problem-free, we can |
| 44 | # skip the SCM operations most of the time. |
| 45 | extension = str(f.LocalPath()).rsplit('.', 1)[-1] |
| 46 | if all(callable_rule(extension, line) for line in f.NewContents()): |
| 47 | continue # No violation found in full text: can skip considering diff. |
| 48 | |
| 49 | for line_num, line in f.ChangedContents(): |
| 50 | if not callable_rule(extension, line): |
| 51 | errors.append(error_formatter(f.LocalPath(), line_num, line)) |
| 52 | |
| 53 | return errors |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 54 | |
Zhiling Huang | 45cabf3 | 2018-03-10 00:50:03 | [diff] [blame] | 55 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 56 | class MockInputApi(object): |
| 57 | """Mock class for the InputApi class. |
| 58 | |
| 59 | This class can be used for unittests for presubmit by initializing the files |
| 60 | attribute as the list of changed files. |
| 61 | """ |
| 62 | |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 63 | DEFAULT_FILES_TO_SKIP = () |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 64 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 65 | def __init__(self): |
Daniel Cheng | 264a447d | 2017-09-28 22:17:59 | [diff] [blame] | 66 | self.canned_checks = MockCannedChecks() |
Daniel Cheng | 13ca61a88 | 2017-08-25 15:11:25 | [diff] [blame] | 67 | self.fnmatch = fnmatch |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 68 | self.json = json |
| 69 | self.re = re |
| 70 | self.os_path = os.path |
agrieve | bb9c5b47 | 2016-04-22 15:13:00 | [diff] [blame] | 71 | self.platform = sys.platform |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 72 | self.python_executable = sys.executable |
Takuto Ikuta | dca1022 | 2022-04-13 02:51:21 | [diff] [blame] | 73 | self.python3_executable = sys.executable |
pastarmovj | 89f7ee1 | 2016-09-20 14:58:13 | [diff] [blame] | 74 | self.platform = sys.platform |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 75 | self.subprocess = subprocess |
Dan Beam | 35b10c1 | 2019-11-27 01:17:34 | [diff] [blame] | 76 | self.sys = sys |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 77 | self.files = [] |
| 78 | self.is_committing = False |
gayane | e170266 | 2014-12-13 03:48:09 | [diff] [blame] | 79 | self.change = MockChange([]) |
dpapad | 5c9c24e | 2017-05-31 20:51:34 | [diff] [blame] | 80 | self.presubmit_local_path = os.path.dirname(__file__) |
Bruce Dawson | 3740e073 | 2022-04-07 16:17:22 | [diff] [blame] | 81 | self.is_windows = sys.platform == 'win32' |
Bruce Dawson | 344ab26 | 2022-06-04 11:35:10 | [diff] [blame] | 82 | self.no_diffs = False |
Ian Vollick | 9d42a07 | 2023-02-14 01:21:14 | [diff] [blame] | 83 | # Although this makes assumptions about command line arguments used by test |
| 84 | # scripts that create mocks, it is a convenient way to set up the verbosity |
| 85 | # via the input api. |
| 86 | self.verbose = '--verbose' in sys.argv |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 87 | |
Zhiling Huang | 45cabf3 | 2018-03-10 00:50:03 | [diff] [blame] | 88 | def CreateMockFileInPath(self, f_list): |
| 89 | self.os_path.exists = lambda x: x in f_list |
| 90 | |
Giovanni Ortuño Urquidi | ab84da6 | 2021-12-10 00:53:21 | [diff] [blame] | 91 | def AffectedFiles(self, file_filter=None, include_deletes=True): |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 92 | for file in self.files: |
| 93 | if file_filter and not file_filter(file): |
| 94 | continue |
| 95 | if not include_deletes and file.Action() == 'D': |
| 96 | continue |
| 97 | yield file |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 98 | |
Lukasz Anforowicz | 7016d05e | 2021-11-30 03:56:27 | [diff] [blame] | 99 | def RightHandSideLines(self, source_file_filter=None): |
| 100 | affected_files = self.AffectedSourceFiles(source_file_filter) |
| 101 | for af in affected_files: |
| 102 | lines = af.ChangedContents() |
| 103 | for line in lines: |
| 104 | yield (af, line[0], line[1]) |
| 105 | |
glider | e61efad | 2015-02-18 17:39:43 | [diff] [blame] | 106 | def AffectedSourceFiles(self, file_filter=None): |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 107 | return self.AffectedFiles(file_filter=file_filter) |
| 108 | |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 109 | def FilterSourceFile(self, file, |
Josip Sokcevic | 8b6cc43 | 2020-08-05 17:45:33 | [diff] [blame] | 110 | files_to_check=(), files_to_skip=()): |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 111 | local_path = file.LocalPath() |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 112 | found_in_files_to_check = not files_to_check |
| 113 | if files_to_check: |
| 114 | if type(files_to_check) is str: |
| 115 | raise TypeError('files_to_check should be an iterable of strings') |
| 116 | for pattern in files_to_check: |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 117 | compiled_pattern = re.compile(pattern) |
Henrique Ferreiro | 81d58002 | 2021-11-29 21:27:19 | [diff] [blame] | 118 | if compiled_pattern.match(local_path): |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 119 | found_in_files_to_check = True |
Vaclav Brozek | f01ed50 | 2018-03-16 19:38:24 | [diff] [blame] | 120 | break |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 121 | if files_to_skip: |
| 122 | if type(files_to_skip) is str: |
| 123 | raise TypeError('files_to_skip should be an iterable of strings') |
| 124 | for pattern in files_to_skip: |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 125 | compiled_pattern = re.compile(pattern) |
Henrique Ferreiro | 81d58002 | 2021-11-29 21:27:19 | [diff] [blame] | 126 | if compiled_pattern.match(local_path): |
Sylvain Defresne | a8b73d25 | 2018-02-28 15:45:54 | [diff] [blame] | 127 | return False |
Robert Ma | 0303a3ad | 2020-07-22 18:48:48 | [diff] [blame] | 128 | return found_in_files_to_check |
glider | e61efad | 2015-02-18 17:39:43 | [diff] [blame] | 129 | |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 130 | def LocalPaths(self): |
Alexei Svitkine | 137d4c66 | 2019-07-17 21:28:24 | [diff] [blame] | 131 | return [file.LocalPath() for file in self.files] |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 132 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 133 | def PresubmitLocalPath(self): |
dpapad | 5c9c24e | 2017-05-31 20:51:34 | [diff] [blame] | 134 | return self.presubmit_local_path |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 135 | |
Joanmarie Diggs | 0991fc6 | 2022-08-30 06:00:13 | [diff] [blame] | 136 | def ReadFile(self, filename, mode='r'): |
glider | e61efad | 2015-02-18 17:39:43 | [diff] [blame] | 137 | if hasattr(filename, 'AbsoluteLocalPath'): |
| 138 | filename = filename.AbsoluteLocalPath() |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 139 | for file_ in self.files: |
| 140 | if file_.LocalPath() == filename: |
| 141 | return '\n'.join(file_.NewContents()) |
| 142 | # Otherwise, file is not in our mock API. |
Dirk Pranke | e3c9c62d | 2021-05-18 18:35:59 | [diff] [blame] | 143 | raise IOError("No such file or directory: '%s'" % filename) |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 144 | |
| 145 | |
| 146 | class MockOutputApi(object): |
gayane | 860db5c3 | 2014-12-05 16:16:46 | [diff] [blame] | 147 | """Mock class for the OutputApi class. |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 148 | |
Gao Sheng | a79ebd4 | 2022-08-08 17:25:59 | [diff] [blame] | 149 | An instance of this class can be passed to presubmit unittests for outputting |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 150 | various types of results. |
| 151 | """ |
| 152 | |
| 153 | class PresubmitResult(object): |
| 154 | def __init__(self, message, items=None, long_text=''): |
| 155 | self.message = message |
| 156 | self.items = items |
| 157 | self.long_text = long_text |
| 158 | |
gayane | 940df07 | 2015-02-24 14:28:30 | [diff] [blame] | 159 | def __repr__(self): |
| 160 | return self.message |
| 161 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 162 | class PresubmitError(PresubmitResult): |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 163 | def __init__(self, message, items=None, long_text=''): |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 164 | MockOutputApi.PresubmitResult.__init__(self, message, items, long_text) |
| 165 | self.type = 'error' |
| 166 | |
| 167 | class PresubmitPromptWarning(PresubmitResult): |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 168 | def __init__(self, message, items=None, long_text=''): |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 169 | MockOutputApi.PresubmitResult.__init__(self, message, items, long_text) |
| 170 | self.type = 'warning' |
| 171 | |
| 172 | class PresubmitNotifyResult(PresubmitResult): |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 173 | def __init__(self, message, items=None, long_text=''): |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 174 | MockOutputApi.PresubmitResult.__init__(self, message, items, long_text) |
| 175 | self.type = 'notify' |
| 176 | |
| 177 | class PresubmitPromptOrNotify(PresubmitResult): |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 178 | def __init__(self, message, items=None, long_text=''): |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 179 | MockOutputApi.PresubmitResult.__init__(self, message, items, long_text) |
| 180 | self.type = 'promptOrNotify' |
| 181 | |
Daniel Cheng | 7052cdf | 2017-11-21 19:23:29 | [diff] [blame] | 182 | def __init__(self): |
| 183 | self.more_cc = [] |
| 184 | |
| 185 | def AppendCC(self, more_cc): |
Kevin McNee | 967dd2d2 | 2021-11-15 16:09:29 | [diff] [blame] | 186 | self.more_cc.append(more_cc) |
Daniel Cheng | 7052cdf | 2017-11-21 19:23:29 | [diff] [blame] | 187 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 188 | |
| 189 | class MockFile(object): |
| 190 | """Mock class for the File class. |
| 191 | |
| 192 | This class can be used to form the mock list of changed files in |
| 193 | MockInputApi for presubmit unittests. |
| 194 | """ |
| 195 | |
Dominic Battre | 645d4234 | 2020-12-04 16:14:10 | [diff] [blame] | 196 | def __init__(self, local_path, new_contents, old_contents=None, action='A', |
| 197 | scm_diff=None): |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 198 | self._local_path = local_path |
| 199 | self._new_contents = new_contents |
| 200 | self._changed_contents = [(i + 1, l) for i, l in enumerate(new_contents)] |
agrieve | f32bcc7 | 2016-04-04 14:57:40 | [diff] [blame] | 201 | self._action = action |
Dominic Battre | 645d4234 | 2020-12-04 16:14:10 | [diff] [blame] | 202 | if scm_diff: |
| 203 | self._scm_diff = scm_diff |
| 204 | else: |
| 205 | self._scm_diff = ( |
| 206 | "--- /dev/null\n+++ %s\n@@ -0,0 +1,%d @@\n" % |
| 207 | (local_path, len(new_contents))) |
| 208 | for l in new_contents: |
| 209 | self._scm_diff += "+%s\n" % l |
Yoland Yan | b92fa52 | 2017-08-28 17:37:06 | [diff] [blame] | 210 | self._old_contents = old_contents |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 211 | |
dbeam | 37e8e740 | 2016-02-10 22:58:20 | [diff] [blame] | 212 | def Action(self): |
agrieve | f32bcc7 | 2016-04-04 14:57:40 | [diff] [blame] | 213 | return self._action |
dbeam | 37e8e740 | 2016-02-10 22:58:20 | [diff] [blame] | 214 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 215 | def ChangedContents(self): |
| 216 | return self._changed_contents |
| 217 | |
| 218 | def NewContents(self): |
| 219 | return self._new_contents |
| 220 | |
| 221 | def LocalPath(self): |
| 222 | return self._local_path |
| 223 | |
rdevlin.cronin | 9ab806c | 2016-02-26 23:17:13 | [diff] [blame] | 224 | def AbsoluteLocalPath(self): |
| 225 | return self._local_path |
| 226 | |
jbriance | 9e12f16 | 2016-11-25 07:57:50 | [diff] [blame] | 227 | def GenerateScmDiff(self): |
jbriance | 2c51e821a | 2016-12-12 08:24:31 | [diff] [blame] | 228 | return self._scm_diff |
jbriance | 9e12f16 | 2016-11-25 07:57:50 | [diff] [blame] | 229 | |
Yoland Yan | b92fa52 | 2017-08-28 17:37:06 | [diff] [blame] | 230 | def OldContents(self): |
| 231 | return self._old_contents |
| 232 | |
davileen | e042625 | 2015-03-02 21:10:41 | [diff] [blame] | 233 | def rfind(self, p): |
| 234 | """os.path.basename is called on MockFile so we need an rfind method.""" |
| 235 | return self._local_path.rfind(p) |
| 236 | |
| 237 | def __getitem__(self, i): |
| 238 | """os.path.basename is called on MockFile so we need a get method.""" |
| 239 | return self._local_path[i] |
| 240 | |
pastarmovj | 89f7ee1 | 2016-09-20 14:58:13 | [diff] [blame] | 241 | def __len__(self): |
| 242 | """os.path.basename is called on MockFile so we need a len method.""" |
| 243 | return len(self._local_path) |
| 244 | |
Julian Pastarmov | 4f7af53 | 2019-07-17 19:25:37 | [diff] [blame] | 245 | def replace(self, altsep, sep): |
| 246 | """os.path.basename is called on MockFile so we need a replace method.""" |
| 247 | return self._local_path.replace(altsep, sep) |
| 248 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 249 | |
glider | e61efad | 2015-02-18 17:39:43 | [diff] [blame] | 250 | class MockAffectedFile(MockFile): |
| 251 | def AbsoluteLocalPath(self): |
| 252 | return self._local_path |
| 253 | |
| 254 | |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 255 | class MockChange(object): |
| 256 | """Mock class for Change class. |
| 257 | |
| 258 | This class can be used in presubmit unittests to mock the query of the |
| 259 | current change. |
| 260 | """ |
| 261 | |
| 262 | def __init__(self, changed_files): |
| 263 | self._changed_files = changed_files |
Thorben Troebst | 2d24c706 | 2022-08-10 20:20:16 | [diff] [blame] | 264 | self.author_email = None |
Chris Hall | 59f8d0c7 | 2020-05-01 07:31:19 | [diff] [blame] | 265 | self.footers = defaultdict(list) |
gayane | 3dff8c2 | 2014-12-04 17:09:51 | [diff] [blame] | 266 | |
| 267 | def LocalPaths(self): |
| 268 | return self._changed_files |
rdevlin.cronin | 11366825 | 2016-05-02 17:05:54 | [diff] [blame] | 269 | |
| 270 | def AffectedFiles(self, include_dirs=False, include_deletes=True, |
| 271 | file_filter=None): |
| 272 | return self._changed_files |
Chris Hall | 59f8d0c7 | 2020-05-01 07:31:19 | [diff] [blame] | 273 | |
| 274 | def GitFootersFromDescription(self): |
| 275 | return self.footers |