blob: baca10648edcb06f9b7458929255db1244c7227e [file] [log] [blame]
Avi Drissman24976592022-09-12 15:24:311# Copyright 2014 The Chromium Authors
gayane3dff8c22014-12-04 17:09:512# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Chris Hall59f8d0c72020-05-01 07:31:195from collections import defaultdict
Daniel Cheng13ca61a882017-08-25 15:11:256import fnmatch
gayane3dff8c22014-12-04 17:09:517import json
8import os
9import re
10import subprocess
11import sys
12
Andrew Grieve713b89b2024-10-15 20:20:0813
14_REPO_ROOT = os.path.abspath(os.path.dirname(__file__))
15
Daniel Cheng264a447d2017-09-28 22:17:5916# TODO(dcheng): It's kind of horrible that this is copy and pasted from
17# presubmit_canned_checks.py, but it's far easier than any of the alternatives.
18def _ReportErrorFileAndLine(filename, line_num, dummy_line):
Andrew Grieve66a2bc42024-10-04 21:20:2019 """Default error formatter for _FindNewViolationsOfRule."""
20 return '%s:%s' % (filename, line_num)
Daniel Cheng264a447d2017-09-28 22:17:5921
22
23class MockCannedChecks(object):
Andrew Grieve66a2bc42024-10-04 21:20:2024 def _FindNewViolationsOfRule(self, callable_rule, input_api,
25 source_file_filter=None,
26 error_formatter=_ReportErrorFileAndLine):
27 """Find all newly introduced violations of a per-line rule (a callable).
Daniel Cheng264a447d2017-09-28 22:17:5928
29 Arguments:
30 callable_rule: a callable taking a file extension and line of input and
31 returning True if the rule is satisfied and False if there was a
32 problem.
33 input_api: object to enumerate the affected files.
34 source_file_filter: a filter to be passed to the input api.
35 error_formatter: a callable taking (filename, line_number, line) and
36 returning a formatted error string.
37
38 Returns:
39 A list of the newly-introduced violations reported by the rule.
40 """
Andrew Grieve66a2bc42024-10-04 21:20:2041 errors = []
42 for f in input_api.AffectedFiles(include_deletes=False,
43 file_filter=source_file_filter):
44 # For speed, we do two passes, checking first the full file.
45 # Shelling out to the SCM to determine the changed region can be
46 # quite expensive on Win32. Assuming that most files will be kept
47 # problem-free, we can skip the SCM operations most of the time.
Anton Bershanskyi4253349482025-02-11 21:01:2748 extension = str(f.UnixLocalPath()).rsplit('.', 1)[-1]
Andrew Grieve66a2bc42024-10-04 21:20:2049 if all(callable_rule(extension, line) for line in f.NewContents()):
50 # No violation found in full text: can skip considering diff.
51 continue
Daniel Cheng264a447d2017-09-28 22:17:5952
Andrew Grieve66a2bc42024-10-04 21:20:2053 for line_num, line in f.ChangedContents():
54 if not callable_rule(extension, line):
55 errors.append(
56 error_formatter(f.LocalPath(), line_num, line))
Daniel Cheng264a447d2017-09-28 22:17:5957
Andrew Grieve66a2bc42024-10-04 21:20:2058 return errors
gayane3dff8c22014-12-04 17:09:5159
Zhiling Huang45cabf32018-03-10 00:50:0360
gayane3dff8c22014-12-04 17:09:5161class MockInputApi(object):
Andrew Grieve66a2bc42024-10-04 21:20:2062 """Mock class for the InputApi class.
gayane3dff8c22014-12-04 17:09:5163
64 This class can be used for unittests for presubmit by initializing the files
65 attribute as the list of changed files.
66 """
67
Andrew Grieve66a2bc42024-10-04 21:20:2068 DEFAULT_FILES_TO_SKIP = ()
Sylvain Defresnea8b73d252018-02-28 15:45:5469
Andrew Grieve66a2bc42024-10-04 21:20:2070 def __init__(self):
71 self.basename = os.path.basename
72 self.canned_checks = MockCannedChecks()
73 self.fnmatch = fnmatch
74 self.json = json
75 self.re = re
Joanna Wang130e7bdd2024-12-10 17:39:0376
77 # We want os_path.exists() and os_path.isfile() to work for files
78 # that are both in the filesystem and mock files we have added
79 # via InitFiles().
80 # By setting os_path to a copy of os.path rather than directly we
81 # can not only have os_path.exists() be a combined output for fake
82 # files and real files in the filesystem.
83 import importlib.util
84 SPEC_OS_PATH = importlib.util.find_spec('os.path')
85 os_path1 = importlib.util.module_from_spec(SPEC_OS_PATH)
86 SPEC_OS_PATH.loader.exec_module(os_path1)
87 sys.modules['os_path1'] = os_path1
88 self.os_path = os_path1
89
Andrew Grieve66a2bc42024-10-04 21:20:2090 self.platform = sys.platform
91 self.python_executable = sys.executable
92 self.python3_executable = sys.executable
93 self.platform = sys.platform
94 self.subprocess = subprocess
95 self.sys = sys
96 self.files = []
97 self.is_committing = False
98 self.change = MockChange([])
Andrew Grieve713b89b2024-10-15 20:20:0899 self.presubmit_local_path = os.path.dirname(
100 os.path.abspath(sys.argv[0]))
Andrew Grieve66a2bc42024-10-04 21:20:20101 self.is_windows = sys.platform == 'win32'
102 self.no_diffs = False
103 # Although this makes assumptions about command line arguments used by
104 # test scripts that create mocks, it is a convenient way to set up the
105 # verbosity via the input api.
106 self.verbose = '--verbose' in sys.argv
gayane3dff8c22014-12-04 17:09:51107
Andrew Grieve713b89b2024-10-15 20:20:08108 def InitFiles(self, files):
109 # Actual presubmit calls normpath, but too many tests break to do this
110 # right in MockFile().
111 for f in files:
112 f._local_path = os.path.normpath(f._local_path)
113 self.files = files
114 files_that_exist = {
115 p.AbsoluteLocalPath()
116 for p in files if p.Action() != 'D'
117 }
118
119 def mock_exists(path):
120 if not os.path.isabs(path):
121 path = os.path.join(self.presubmit_local_path, path)
Andrew Grieveb77ac762024-11-29 15:01:48122 path = os.path.normpath(path)
Joanna Wang130e7bdd2024-12-10 17:39:03123 return path in files_that_exist or any(
124 f.startswith(path)
125 for f in files_that_exist) or os.path.exists(path)
126
127 def mock_isfile(path):
128 if not os.path.isabs(path):
129 path = os.path.join(self.presubmit_local_path, path)
130 path = os.path.normpath(path)
131 return path in files_that_exist or os.path.isfile(path)
Andrew Grieve713b89b2024-10-15 20:20:08132
133 def mock_glob(pattern, *args, **kwargs):
Joanna Wang130e7bdd2024-12-10 17:39:03134 return fnmatch.filter(files_that_exist, pattern)
Andrew Grieve713b89b2024-10-15 20:20:08135
136 # Do not stub these in the constructor to not break existing tests.
137 self.os_path.exists = mock_exists
Joanna Wang130e7bdd2024-12-10 17:39:03138 self.os_path.isfile = mock_isfile
Andrew Grieve713b89b2024-10-15 20:20:08139 self.glob = mock_glob
Zhiling Huang45cabf32018-03-10 00:50:03140
Andrew Grieve66a2bc42024-10-04 21:20:20141 def AffectedFiles(self, file_filter=None, include_deletes=True):
142 for file in self.files:
143 if file_filter and not file_filter(file):
144 continue
145 if not include_deletes and file.Action() == 'D':
146 continue
147 yield file
gayane3dff8c22014-12-04 17:09:51148
Andrew Grieve66a2bc42024-10-04 21:20:20149 def RightHandSideLines(self, source_file_filter=None):
150 affected_files = self.AffectedSourceFiles(source_file_filter)
151 for af in affected_files:
152 lines = af.ChangedContents()
153 for line in lines:
154 yield (af, line[0], line[1])
Lukasz Anforowicz7016d05e2021-11-30 03:56:27155
Andrew Grieve66a2bc42024-10-04 21:20:20156 def AffectedSourceFiles(self, file_filter=None):
157 return self.AffectedFiles(file_filter=file_filter,
158 include_deletes=False)
Sylvain Defresnea8b73d252018-02-28 15:45:54159
Andrew Grieve66a2bc42024-10-04 21:20:20160 def AffectedTestableFiles(self, file_filter=None):
161 return self.AffectedFiles(file_filter=file_filter,
162 include_deletes=False)
Georg Neis9080e0602024-08-23 01:50:29163
Andrew Grieve66a2bc42024-10-04 21:20:20164 def FilterSourceFile(self, file, files_to_check=(), files_to_skip=()):
Anton Bershanskyi4253349482025-02-11 21:01:27165 local_path = file.UnixLocalPath()
Andrew Grieve66a2bc42024-10-04 21:20:20166 found_in_files_to_check = not files_to_check
167 if files_to_check:
168 if type(files_to_check) is str:
169 raise TypeError(
170 'files_to_check should be an iterable of strings')
171 for pattern in files_to_check:
172 compiled_pattern = re.compile(pattern)
173 if compiled_pattern.match(local_path):
174 found_in_files_to_check = True
175 break
176 if files_to_skip:
177 if type(files_to_skip) is str:
178 raise TypeError(
179 'files_to_skip should be an iterable of strings')
180 for pattern in files_to_skip:
181 compiled_pattern = re.compile(pattern)
182 if compiled_pattern.match(local_path):
183 return False
184 return found_in_files_to_check
glidere61efad2015-02-18 17:39:43185
Andrew Grieve66a2bc42024-10-04 21:20:20186 def LocalPaths(self):
187 return [file.LocalPath() for file in self.files]
davileene0426252015-03-02 21:10:41188
Andrew Grieve66a2bc42024-10-04 21:20:20189 def PresubmitLocalPath(self):
190 return self.presubmit_local_path
gayane3dff8c22014-12-04 17:09:51191
Andrew Grieve66a2bc42024-10-04 21:20:20192 def ReadFile(self, filename, mode='r'):
193 if hasattr(filename, 'AbsoluteLocalPath'):
194 filename = filename.AbsoluteLocalPath()
Andrew Grieveb77ac762024-11-29 15:01:48195 norm_filename = os.path.normpath(filename)
Andrew Grieve66a2bc42024-10-04 21:20:20196 for file_ in self.files:
Andrew Grieveb77ac762024-11-29 15:01:48197 to_check = (file_.LocalPath(), file_.AbsoluteLocalPath())
198 if filename in to_check or norm_filename in to_check:
Andrew Grieve66a2bc42024-10-04 21:20:20199 return '\n'.join(file_.NewContents())
200 # Otherwise, file is not in our mock API.
201 raise IOError("No such file or directory: '%s'" % filename)
gayane3dff8c22014-12-04 17:09:51202
203
204class MockOutputApi(object):
Andrew Grieve66a2bc42024-10-04 21:20:20205 """Mock class for the OutputApi class.
gayane3dff8c22014-12-04 17:09:51206
Gao Shenga79ebd42022-08-08 17:25:59207 An instance of this class can be passed to presubmit unittests for outputting
gayane3dff8c22014-12-04 17:09:51208 various types of results.
209 """
210
Andrew Grieve66a2bc42024-10-04 21:20:20211 class PresubmitResult(object):
gayane3dff8c22014-12-04 17:09:51212
Ben Pastenee79d66112025-04-23 19:46:15213 def __init__(self, message, items=None, long_text='', locations=[]):
Andrew Grieve66a2bc42024-10-04 21:20:20214 self.message = message
215 self.items = items
216 self.long_text = long_text
Ben Pastenee79d66112025-04-23 19:46:15217 self.locations = locations
gayane940df072015-02-24 14:28:30218
Andrew Grieve66a2bc42024-10-04 21:20:20219 def __repr__(self):
220 return self.message
gayane3dff8c22014-12-04 17:09:51221
Andrew Grieve66a2bc42024-10-04 21:20:20222 class PresubmitError(PresubmitResult):
gayane3dff8c22014-12-04 17:09:51223
Ben Pastenee79d66112025-04-23 19:46:15224 def __init__(self, *args, **kwargs):
225 MockOutputApi.PresubmitResult.__init__(self, *args, **kwargs)
Andrew Grieve66a2bc42024-10-04 21:20:20226 self.type = 'error'
gayane3dff8c22014-12-04 17:09:51227
Andrew Grieve66a2bc42024-10-04 21:20:20228 class PresubmitPromptWarning(PresubmitResult):
gayane3dff8c22014-12-04 17:09:51229
Ben Pastenee79d66112025-04-23 19:46:15230 def __init__(self, *args, **kwargs):
231 MockOutputApi.PresubmitResult.__init__(self, *args, **kwargs)
Andrew Grieve66a2bc42024-10-04 21:20:20232 self.type = 'warning'
Daniel Cheng7052cdf2017-11-21 19:23:29233
Andrew Grieve66a2bc42024-10-04 21:20:20234 class PresubmitNotifyResult(PresubmitResult):
235
Ben Pastenee79d66112025-04-23 19:46:15236 def __init__(self, *args, **kwargs):
237 MockOutputApi.PresubmitResult.__init__(self, *args, **kwargs)
Andrew Grieve66a2bc42024-10-04 21:20:20238 self.type = 'notify'
239
240 class PresubmitPromptOrNotify(PresubmitResult):
241
Ben Pastenee79d66112025-04-23 19:46:15242 def __init__(self, *args, **kwargs):
243 MockOutputApi.PresubmitResult.__init__(self, *args, **kwargs)
Andrew Grieve66a2bc42024-10-04 21:20:20244 self.type = 'promptOrNotify'
245
Ben Pastenee79d66112025-04-23 19:46:15246 class PresubmitResultLocation(object):
247
248 def __init__(self, file_path, start_line, end_line):
249 self.file_path = file_path
250 self.start_line = start_line
251 self.end_line = end_line
252
Andrew Grieve66a2bc42024-10-04 21:20:20253 def __init__(self):
254 self.more_cc = []
255
256 def AppendCC(self, more_cc):
257 self.more_cc.append(more_cc)
Daniel Cheng7052cdf2017-11-21 19:23:29258
gayane3dff8c22014-12-04 17:09:51259
260class MockFile(object):
Andrew Grieve66a2bc42024-10-04 21:20:20261 """Mock class for the File class.
gayane3dff8c22014-12-04 17:09:51262
263 This class can be used to form the mock list of changed files in
264 MockInputApi for presubmit unittests.
265 """
266
Andrew Grieve66a2bc42024-10-04 21:20:20267 def __init__(self,
268 local_path,
269 new_contents,
270 old_contents=None,
271 action='A',
272 scm_diff=None):
273 self._local_path = local_path
274 self._new_contents = new_contents
275 self._changed_contents = [(i + 1, l)
276 for i, l in enumerate(new_contents)]
277 self._action = action
278 if scm_diff:
279 self._scm_diff = scm_diff
280 else:
281 self._scm_diff = ("--- /dev/null\n+++ %s\n@@ -0,0 +1,%d @@\n" %
282 (local_path, len(new_contents)))
283 for l in new_contents:
284 self._scm_diff += "+%s\n" % l
285 self._old_contents = old_contents or []
gayane3dff8c22014-12-04 17:09:51286
Andrew Grieve66a2bc42024-10-04 21:20:20287 def __str__(self):
288 return self._local_path
Luciano Pacheco23d752b02023-10-25 22:49:36289
Andrew Grieve66a2bc42024-10-04 21:20:20290 def Action(self):
291 return self._action
dbeam37e8e7402016-02-10 22:58:20292
Andrew Grieve66a2bc42024-10-04 21:20:20293 def ChangedContents(self):
294 return self._changed_contents
gayane3dff8c22014-12-04 17:09:51295
Andrew Grieve66a2bc42024-10-04 21:20:20296 def NewContents(self):
297 return self._new_contents
gayane3dff8c22014-12-04 17:09:51298
Andrew Grieve66a2bc42024-10-04 21:20:20299 def LocalPath(self):
300 return self._local_path
gayane3dff8c22014-12-04 17:09:51301
Andrew Grieve66a2bc42024-10-04 21:20:20302 def AbsoluteLocalPath(self):
Andrew Grieve713b89b2024-10-15 20:20:08303 return os.path.join(_REPO_ROOT, self._local_path)
rdevlin.cronin9ab806c2016-02-26 23:17:13304
Anton Bershanskyi4253349482025-02-11 21:01:27305 # This method must be functionally identical to
306 # AffectedFile.UnixLocalPath(), but must normalize Windows-style
307 # paths even on non-Windows platforms because tests contain them
308 def UnixLocalPath(self):
309 return self._local_path.replace('\\', '/')
310
Andrew Grieve66a2bc42024-10-04 21:20:20311 def GenerateScmDiff(self):
312 return self._scm_diff
jbriance9e12f162016-11-25 07:57:50313
Andrew Grieve66a2bc42024-10-04 21:20:20314 def OldContents(self):
315 return self._old_contents
Yoland Yanb92fa522017-08-28 17:37:06316
Andrew Grieve66a2bc42024-10-04 21:20:20317 def rfind(self, p):
318 """Required when os.path.basename() is called on MockFile."""
319 return self._local_path.rfind(p)
davileene0426252015-03-02 21:10:41320
Andrew Grieve66a2bc42024-10-04 21:20:20321 def __getitem__(self, i):
322 """Required when os.path.basename() is called on MockFile."""
323 return self._local_path[i]
davileene0426252015-03-02 21:10:41324
Andrew Grieve66a2bc42024-10-04 21:20:20325 def __len__(self):
326 """Required when os.path.basename() is called on MockFile."""
327 return len(self._local_path)
pastarmovj89f7ee12016-09-20 14:58:13328
Andrew Grieve66a2bc42024-10-04 21:20:20329 def replace(self, altsep, sep):
330 """Required when os.path.basename() is called on MockFile."""
331 return self._local_path.replace(altsep, sep)
Julian Pastarmov4f7af532019-07-17 19:25:37332
gayane3dff8c22014-12-04 17:09:51333
glidere61efad2015-02-18 17:39:43334class MockAffectedFile(MockFile):
Andrew Grieve713b89b2024-10-15 20:20:08335 pass
glidere61efad2015-02-18 17:39:43336
337
gayane3dff8c22014-12-04 17:09:51338class MockChange(object):
Andrew Grieve66a2bc42024-10-04 21:20:20339 """Mock class for Change class.
gayane3dff8c22014-12-04 17:09:51340
341 This class can be used in presubmit unittests to mock the query of the
342 current change.
343 """
344
Andrew Grieve66a2bc42024-10-04 21:20:20345 def __init__(self, changed_files):
346 self._changed_files = changed_files
347 self.author_email = None
348 self.footers = defaultdict(list)
gayane3dff8c22014-12-04 17:09:51349
Andrew Grieve66a2bc42024-10-04 21:20:20350 def LocalPaths(self):
351 return self._changed_files
rdevlin.cronin113668252016-05-02 17:05:54352
Andrew Grieve66a2bc42024-10-04 21:20:20353 def AffectedFiles(self,
354 include_dirs=False,
355 include_deletes=True,
356 file_filter=None):
357 return self._changed_files
Chris Hall59f8d0c72020-05-01 07:31:19358
Andrew Grieve66a2bc42024-10-04 21:20:20359 def GitFootersFromDescription(self):
360 return self.footers
Andrew Grieve713b89b2024-10-15 20:20:08361
362 def RepositoryRoot(self):
363 return _REPO_ROOT