Debian Codegraph @

benchmarks/gitwildmatch_v1.py

raw
1 """
2 This module implements `.GitWildMatchPattern`, version 1, used in benchmarking,
3 but not included in the released library.
4 """
5
6 import re
7 from typing import (
8 Optional) # Replaced by `X | None` in 3.10.
9 from typing_extensions import (
10 override)
11
12 from pathspec.pattern import (
13 RegexPattern)
14 from pathspec.patterns.gitignore.spec import (
15 _BYTES_ENCODING,
16 _DIR_MARK)
17 from pathspec._typing import (
18 AnyStr) # Removed in 3.18.
19
20
21 class GitWildMatchV1Pattern(RegexPattern):
22 """
23 The :class:`GitWildMatchV1Pattern` class represents a compiled Git wildmatch
24 pattern.
25 """
26
27 # Keep the dict-less class hierarchy.
28 __slots__ = ()
29
30 @override
31 @classmethod
32 def pattern_to_regex(
33 cls,
34 pattern: AnyStr,
35 ) -> tuple[Optional[AnyStr], Optional[bool]]:
36 if isinstance(pattern, str):
37 return_type = str
38 elif isinstance(pattern, bytes):
39 return_type = bytes
40 pattern = pattern.decode(_BYTES_ENCODING)
41 else:
42 raise TypeError(f"pattern:{pattern!r} is not a unicode or byte string.")
43
44 original_pattern = pattern
45
46 if pattern.endswith('\\ '):
47 # EDGE CASE: Spaces can be escaped with backslash. If a pattern that ends
48 # with backslash followed by a space, only strip from left.
49 pattern = pattern.lstrip()
50 else:
51 pattern = pattern.strip()
52
53 if pattern.startswith('#'):
54 # A pattern starting with a hash ('#') serves as a comment (neither
55 # includes nor excludes files). Escape the hash with a back-slash to match
56 # a literal hash (i.e., '\#').
57 regex = None
58 include = None
59
60 elif pattern == '/':
61 # EDGE CASE: According to `git check-ignore` (v2.4.1), a single '/' does
62 # not match any file.
63 regex = None
64 include = None
65
66 elif pattern:
67 if pattern.startswith('!'):
68 # A pattern starting with an exclamation mark ('!') negates the pattern
69 # (exclude instead of include). Escape the exclamation mark with a
70 # back-slash to match a literal exclamation mark (i.e., '\!').
71 include = False
72 # Remove leading exclamation mark.
73 pattern = pattern[1:]
74 else:
75 include = True
76
77 # Allow a regex override for edge cases that cannot be handled through
78 # normalization.
79 override_regex = None
80
81 # Split pattern into segments.
82 pattern_segs = pattern.split('/')
83
84 # Check whether the pattern is specifically a directory pattern before
85 # normalization.
86 is_dir_pattern = not pattern_segs[-1]
87
88 # Normalize pattern to make processing easier.
89
90 # EDGE CASE: Deal with duplicate double-asterisk sequences. Collapse each
91 # sequence down to one double-asterisk. Iterate over the segments in
92 # reverse and remove the duplicate double asterisks as we go.
93 for i in range(len(pattern_segs) - 1, 0, -1):
94 prev = pattern_segs[i-1]
95 seg = pattern_segs[i]
96 if prev == '**' and seg == '**':
97 del pattern_segs[i]
98
99 if len(pattern_segs) == 2 and pattern_segs[0] == '**' and not pattern_segs[1]:
100 # EDGE CASE: The '**/' pattern should match everything except individual
101 # files in the root directory. This case cannot be adequately handled
102 # through normalization. Use the override.
103 override_regex = f'^.+(?P<{_DIR_MARK}>/).*$'
104
105 if not pattern_segs[0]:
106 # A pattern beginning with a slash ('/') will only match paths directly
107 # on the root directory instead of any descendant paths. So, remove
108 # empty first segment to make pattern relative to root.
109 del pattern_segs[0]
110
111 elif len(pattern_segs) == 1 or (len(pattern_segs) == 2 and not pattern_segs[1]):
112 # A single pattern without a beginning slash ('/') will match any
113 # descendant path. This is equivalent to "**/{pattern}". So, prepend
114 # with double-asterisks to make pattern relative to root.
115 # - EDGE CASE: This also holds for a single pattern with a trailing
116 # slash (e.g. dir/).
117 if pattern_segs[0] != '**':
118 pattern_segs.insert(0, '**')
119
120 else:
121 # EDGE CASE: A pattern without a beginning slash ('/') but contains at
122 # least one prepended directory (e.g. "dir/{pattern}") should not match
123 # "**/dir/{pattern}", according to `git check-ignore` (v2.4.1).
124 pass
125
126 if not pattern_segs:
127 # After resolving the edge cases, we end up with no pattern at all. This
128 # must be because the pattern is invalid.
129 raise Exception(f"Invalid git pattern: {original_pattern!r}")
130
131 if not pattern_segs[-1] and len(pattern_segs) > 1:
132 # A pattern ending with a slash ('/') will match all descendant paths if
133 # it is a directory but not if it is a regular file. This is equivalent
134 # to "{pattern}/**". So, set last segment to a double-asterisk to
135 # include all descendants.
136 pattern_segs[-1] = '**'
137
138 if override_regex is None:
139 # Build regular expression from pattern.
140 output = ['^']
141 need_slash = False
142 end = len(pattern_segs) - 1
143 for i, seg in enumerate(pattern_segs):
144 if seg == '**':
145 if i == 0 and i == end:
146 # A pattern consisting solely of double-asterisks ('**') will
147 # match every path.
148 output.append(f'[^/]+(?:/.*)?')
149
150 elif i == 0:
151 # A normalized pattern beginning with double-asterisks
152 # ('**') will match any leading path segments.
153 output.append('(?:.+/)?')
154 need_slash = False
155
156 elif i == end:
157 # A normalized pattern ending with double-asterisks ('**') will
158 # match any trailing path segments.
159 if is_dir_pattern:
160 output.append(f'(?P<{_DIR_MARK}>/).*')
161 else:
162 output.append(f'/.*')
163
164 else:
165 # A pattern with inner double-asterisks ('**') will match multiple
166 # (or zero) inner path segments.
167 output.append('(?:/.+)?')
168 need_slash = True
169
170 elif seg == '*':
171 # Match single path segment.
172 if need_slash:
173 output.append('/')
174
175 output.append('[^/]+')
176
177 if i == end:
178 # A pattern ending without a slash ('/') will match a file or a
179 # directory (with paths underneath it). E.g., "foo" matches "foo",
180 # "foo/bar", "foo/bar/baz", etc.
181 output.append(f'(?:(?P<{_DIR_MARK}>/).*)?')
182
183 need_slash = True
184
185 else:
186 # Match segment glob pattern.
187 if need_slash:
188 output.append('/')
189
190 try:
191 output.append(cls._translate_segment_glob(seg))
192 except ValueError as e:
193 raise Exception(f"Invalid git pattern: {original_pattern!r}") from e
194
195 if i == end:
196 # A pattern ending without a slash ('/') will match a file or a
197 # directory (with paths underneath it). E.g., "foo" matches "foo",
198 # "foo/bar", "foo/bar/baz", etc.
199 output.append(f'(?:(?P<{_DIR_MARK}>/).*)?')
200
201 need_slash = True
202
203 output.append('$')
204 regex = ''.join(output)
205
206 else:
207 # Use regex override.
208 regex = override_regex
209
210 else:
211 # A blank pattern is a null-operation (neither includes nor excludes
212 # files).
213 regex = None
214 include = None
215
216 if regex is not None and return_type is bytes:
217 regex = regex.encode(_BYTES_ENCODING)
218
219 return regex, include
220
221 @staticmethod
222 def _translate_segment_glob(pattern: str) -> str:
223 # NOTE: This is derived from `fnmatch.translate()` and is similar to the
224 # POSIX function `fnmatch()` with the `FNM_PATHNAME` flag set.
225
226 escape = False
227 regex = ''
228 i, end = 0, len(pattern)
229 while i < end:
230 # Get next character.
231 char = pattern[i]
232 i += 1
233
234 if escape:
235 # Escape the character.
236 escape = False
237 regex += re.escape(char)
238
239 elif char == '\\':
240 # Escape character, escape next character.
241 escape = True
242
243 elif char == '*':
244 # Multi-character wildcard. Match any string (except slashes), including
245 # an empty string.
246 regex += '[^/]*'
247
248 elif char == '?':
249 # Single-character wildcard. Match any single character (except a
250 # slash).
251 regex += '[^/]'
252
253 elif char == '[':
254 # Bracket expression wildcard. Except for the beginning exclamation
255 # mark, the whole bracket expression can be used directly as regex, but
256 # we have to find where the expression ends.
257 # - "[][!]" matches ']', '[' and '!'.
258 # - "[]-]" matches ']' and '-'.
259 # - "[!]a-]" matches any character except ']', 'a' and '-'.
260 j = i
261
262 # Pass bracket expression negation.
263 if j < end and (pattern[j] == '!' or pattern[j] == '^'):
264 j += 1
265
266 # Pass first closing bracket if it is at the beginning of the
267 # expression.
268 if j < end and pattern[j] == ']':
269 j += 1
270
271 # Find closing bracket. Stop once we reach the end or find it.
272 while j < end and pattern[j] != ']':
273 j += 1
274
275 if j < end:
276 # Found end of bracket expression. Increment j to be one past the
277 # closing bracket:
278 #
279 # [...]
280 # ^ ^
281 # i j
282 #
283 j += 1
284 expr = '['
285
286 if pattern[i] == '!':
287 # Bracket expression needs to be negated.
288 expr += '^'
289 i += 1
290 elif pattern[i] == '^':
291 # POSIX declares that the regex bracket expression negation "[^...]"
292 # is undefined in a glob pattern. Python's `fnmatch.translate()`
293 # escapes the caret ('^') as a literal. Git supports the using a
294 # caret for negation. Maintain consistency with Git because that is
295 # the expected behavior.
296 expr += '^'
297 i += 1
298
299 # Build regex bracket expression. Escape slashes so they are treated
300 # as literal slashes by regex as defined by POSIX.
301 expr += pattern[i:j].replace('\\', '\\\\')
302
303 # Add regex bracket expression to regex result.
304 regex += expr
305
306 # Set i to one past the closing bracket.
307 i = j
308
309 else:
310 # Failed to find closing bracket, treat opening bracket as a bracket
311 # literal instead of as an expression.
312 regex += '\\['
313
314 else:
315 # Regular character, escape it for regex.
316 regex += re.escape(char)
317
318 if escape:
319 raise ValueError(f"Escape character found with no next character to escape: {pattern!r}")
320
321 return regex
322
323 @staticmethod
324 def escape(s: AnyStr) -> AnyStr:
325 if isinstance(s, str):
326 return_type = str
327 string = s
328 elif isinstance(s, bytes):
329 return_type = bytes
330 string = s.decode(_BYTES_ENCODING)
331 else:
332 raise TypeError(f"s:{s!r} is not a unicode or byte string.")
333
334 # Reference: https://git-scm.com/docs/gitignore#_pattern_format
335 meta_characters = r"[]!*#?"
336
337 out_string = "".join("\\" + x if x in meta_characters else x for x in string)
338
339 if return_type is bytes:
340 return out_string.encode(_BYTES_ENCODING)
341 else:
342 return out_string