Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pathspec/pattern.py: 64%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2This module provides the base definition for patterns.
3"""
4from __future__ import annotations
6import re
7from collections.abc import (
8 Iterable,
9 Iterator)
10from dataclasses import (
11 dataclass)
12from typing import (
13 Any,
14 Optional, # Replaced by `X | None` in 3.10.
15 TypeVar,
16 Union) # Replaced by `X | Y` in 3.10.
18from ._typing import (
19 AnyStr, # Removed in 3.18.
20 deprecated, # Added in 3.13.
21 override) # Added in 3.12.
23RegexPatternSelf = TypeVar("RegexPatternSelf", bound='RegexPattern')
24"""
25:class:`.RegexPattern` self type hint to support Python v<3.11 using PEP 673
26recommendation.
27"""
29class Pattern(object):
30 """
31 The :class:`Pattern` class is the abstract definition of a pattern.
32 """
34 # Make the class dict-less.
35 __slots__ = (
36 'include',
37 )
39 def __init__(self, include: Optional[bool]) -> None:
40 """
41 Initializes the :class:`Pattern` instance.
43 *include* (:class:`bool` or :data:`None`) is whether the matched files
44 should be included (:data:`True`), excluded (:data:`False`), or is a
45 null-operation (:data:`None`).
46 """
48 self.include = include
49 """
50 *include* (:class:`bool` or :data:`None`) is whether the matched files
51 should be included (:data:`True`), excluded (:data:`False`), or is a
52 null-operation (:data:`None`).
53 """
55 @deprecated((
56 "Pattern.match() is deprecated. Use Pattern.match_file() with a loop for "
57 "similar results."
58 ))
59 def match(self, files: Iterable[str]) -> Iterator[str]:
60 """
61 .. version-deprecated:: 0.10.0
62 This method is no longer used. Use the :meth:`self.match_file <.Pattern.match_file>`
63 method with a loop for similar results.
65 Matches this pattern against the specified files.
67 *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each
68 file relative to the root directory.
70 Returns an :class:`~collections.abc.Iterable` yielding each matched file
71 path (:class:`str`).
72 """
73 for file in files:
74 if self.match_file(file) is not None:
75 yield file
77 def match_file(self, file: str) -> Optional[Any]:
78 """
79 Matches this pattern against the specified file.
81 *file* (:class:`str`) is the normalized file path to match against.
83 Returns the match result if *file* matched; otherwise, :data:`None`.
84 """
85 raise NotImplementedError((
86 "{cls.__module__}.{cls.__qualname__} must override match_file()."
87 ).format(cls=self.__class__))
90class RegexPattern(Pattern):
91 """
92 The :class:`RegexPattern` class is an implementation of a pattern using
93 regular expressions.
94 """
96 # Keep the class dict-less.
97 __slots__ = (
98 'pattern',
99 'regex',
100 )
102 def __init__(
103 self,
104 pattern: Union[AnyStr, re.Pattern, None],
105 include: Optional[bool] = None,
106 ) -> None:
107 """
108 Initializes the :class:`RegexPattern` instance.
110 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
111 :data:`None`) is the pattern to compile into a regular expression.
113 *include* (:class:`bool` or :data:`None`) must be :data:`None` unless
114 *pattern* is a precompiled regular expression (:class:`re.Pattern`) in which
115 case it is whether matched files should be included (:data:`True`), excluded
116 (:data:`False`), or is a null operation (:data:`None`).
118 .. note:: Subclasses do not need to support the *include* parameter.
119 """
121 if isinstance(pattern, (str, bytes)):
122 assert include is None, (
123 f"include:{include!r} must be null when pattern:{pattern!r} is a string."
124 )
125 regex, include = self.pattern_to_regex(pattern)
126 # NOTE: Make sure to allow a null regular expression to be
127 # returned for a null-operation.
128 if include is not None:
129 regex = re.compile(regex)
131 elif pattern is not None and hasattr(pattern, 'match'):
132 # Assume pattern is a precompiled regular expression.
133 # - NOTE: Used specified *include*.
134 regex = pattern
136 elif pattern is None:
137 # NOTE: Make sure to allow a null pattern to be passed for a
138 # null-operation.
139 assert include is None, (
140 f"include:{include!r} must be null when pattern:{pattern!r} is null."
141 )
142 regex = None
144 else:
145 raise TypeError(f"pattern:{pattern!r} is not a string, re.Pattern, or None.")
147 super(RegexPattern, self).__init__(include)
149 self.pattern: Union[AnyStr, re.Pattern, None] = pattern
150 """
151 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
152 :data:`None`) is the uncompiled, input pattern. This is for reference.
153 """
155 self.regex: Optional[re.Pattern] = regex
156 """
157 *regex* (:class:`re.Pattern` or :data:`None`) is the compiled regular
158 expression for the pattern.
159 """
161 def __repr__(self) -> str:
162 """
163 Returns a debug representation of this regex pattern.
164 """
165 return f"{self.__class__.__name__}(pattern={self.pattern!r}, include={self.include!r})"
167 def __str__(self) -> str:
168 """
169 Returns a string representation of this regex pattern. Equivalent to uncompiled pattern.
171 The string representation is the uncompiled pattern if it is not
172 :data:`None`; otherwise, an empty string.
173 """
174 return str(self.pattern or "")
176 def __copy__(self: RegexPatternSelf) -> RegexPatternSelf:
177 """
178 Performa a shallow copy of the pattern.
180 Returns the copy (:class:`RegexPattern`).
181 """
182 other = self.__class__(self.regex, self.include)
183 other.pattern = self.pattern
184 return other
186 def __eq__(self, other: object) -> bool:
187 """
188 Tests the equality of this regex pattern with *other* (:class:`RegexPattern`)
189 by comparing their :attr:`~Pattern.include` and :attr:`~RegexPattern.regex`
190 attributes.
191 """
192 if isinstance(other, RegexPattern):
193 return self.include == other.include and self.regex == other.regex
194 else:
195 return NotImplemented
197 @override
198 def match_file(self, file: AnyStr) -> Optional[RegexMatchResult]:
199 """
200 Matches this pattern against the specified file.
202 *file* (:class:`str` or :class:`bytes`) is the file path relative to the
203 root directory (e.g., "relative/path/to/file").
205 Returns the match result (:class:`.RegexMatchResult`) if *file* matched;
206 otherwise, :data:`None`.
207 """
208 if self.include is not None:
209 match = self.regex.search(file)
210 if match is not None:
211 return RegexMatchResult(match)
213 return None
215 @classmethod
216 def pattern_to_regex(
217 cls,
218 pattern: AnyStr,
219 ) -> tuple[Optional[AnyStr], Optional[bool]]:
220 """
221 Convert the pattern into an uncompiled regular expression.
223 *pattern* (:class:`str` or :class:`bytes`) is the pattern to convert into a
224 regular expression.
226 Returns a :class:`tuple` containing:
228 - *pattern* (:class:`str`, :class:`bytes` or :data:`None`) is the
229 uncompiled regular expression .
231 - *include* (:class:`bool` or :data:`None`) is whether matched files
232 should be included (:data:`True`), excluded (:data:`False`), or is a
233 null-operation (:data:`None`).
235 .. note:: The default implementation simply returns *pattern* and
236 :data:`True`.
237 """
238 return pattern, True
241@dataclass()
242class RegexMatchResult(object):
243 """
244 The :class:`RegexMatchResult` data class is used to return information about
245 the matched regular expression.
246 """
248 # Keep the class dict-less.
249 __slots__ = (
250 'match',
251 )
253 match: re.Match
254 """
255 *match* (:class:`re.Match`) is the regex match result.
256 """