Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pathspec/pattern.py: 65%
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"""
5import re
6import warnings
7from collections.abc import (
8 Iterable,
9 Iterator)
10from dataclasses import (
11 dataclass)
12from typing import (
13 Any,
14 AnyStr,
15 Optional, # Replaced by `X | None` in 3.10.
16 Union) # Replaced by `X | Y` in 3.10.
18from ._typing import (
19 override) # Added in 3.12.
22class Pattern(object):
23 """
24 The :class:`Pattern` class is the abstract definition of a pattern.
25 """
27 # Make the class dict-less.
28 __slots__ = (
29 'include',
30 )
32 def __init__(self, include: Optional[bool]) -> None:
33 """
34 Initializes the :class:`Pattern` instance.
36 *include* (:class:`bool` or :data:`None`) is whether the matched files
37 should be included (:data:`True`), excluded (:data:`False`), or is a
38 null-operation (:data:`None`).
39 """
41 self.include = include
42 """
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 def match(self, files: Iterable[str]) -> Iterator[str]:
49 """
50 DEPRECATED: This method is no longer used and has been replaced by
51 :meth:`.match_file`. Use the :meth:`.match_file` method with a loop for
52 similar results.
54 Matches this pattern against the specified files.
56 *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each
57 file relative to the root directory (e.g., ``"relative/path/to/file"``).
59 Returns an :class:`~collections.abc.Iterable` yielding each matched file
60 path (:class:`str`).
61 """
62 warnings.warn((
63 "{cls.__module__}.{cls.__qualname__}.match() is deprecated. Use "
64 "{cls.__module__}.{cls.__qualname__}.match_file() with a loop for "
65 "similar results."
66 ).format(cls=self.__class__), DeprecationWarning, stacklevel=2)
68 for file in files:
69 if self.match_file(file) is not None:
70 yield file
72 def match_file(self, file: str) -> Optional[Any]:
73 """
74 Matches this pattern against the specified file.
76 *file* (:class:`str`) is the normalized file path to match against.
78 Returns the match result if *file* matched; otherwise, :data:`None`.
79 """
80 raise NotImplementedError((
81 "{cls.__module__}.{cls.__qualname__} must override match_file()."
82 ).format(cls=self.__class__))
85class RegexPattern(Pattern):
86 """
87 The :class:`RegexPattern` class is an implementation of a pattern using
88 regular expressions.
89 """
91 # Keep the class dict-less.
92 __slots__ = (
93 'pattern',
94 'regex',
95 )
97 def __init__(
98 self,
99 pattern: Union[AnyStr, re.Pattern, None],
100 include: Optional[bool] = None,
101 ) -> None:
102 """
103 Initializes the :class:`RegexPattern` instance.
105 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
106 :data:`None`) is the pattern to compile into a regular expression.
108 *include* (:class:`bool` or :data:`None`) must be :data:`None` unless
109 *pattern* is a precompiled regular expression (:class:`re.Pattern`) in which
110 case it is whether matched files should be included (:data:`True`), excluded
111 (:data:`False`), or is a null operation (:data:`None`).
113 .. NOTE:: Subclasses do not need to support the *include* parameter.
114 """
116 if isinstance(pattern, (str, bytes)):
117 assert include is None, (
118 f"include:{include!r} must be null when pattern:{pattern!r} is a string."
119 )
120 regex, include = self.pattern_to_regex(pattern)
121 # NOTE: Make sure to allow a null regular expression to be
122 # returned for a null-operation.
123 if include is not None:
124 regex = re.compile(regex)
126 elif pattern is not None and hasattr(pattern, 'match'):
127 # Assume pattern is a precompiled regular expression.
128 # - NOTE: Used specified *include*.
129 regex = pattern
131 elif pattern is None:
132 # NOTE: Make sure to allow a null pattern to be passed for a
133 # null-operation.
134 assert include is None, (
135 f"include:{include!r} must be null when pattern:{pattern!r} is null."
136 )
137 regex = None
139 else:
140 raise TypeError(f"pattern:{pattern!r} is not a string, re.Pattern, or None.")
142 super(RegexPattern, self).__init__(include)
144 self.pattern: Union[AnyStr, re.Pattern, None] = pattern
145 """
146 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
147 :data:`None`) is the uncompiled, input pattern. This is for reference.
148 """
150 self.regex: Optional[re.Pattern] = regex
151 """
152 *regex* (:class:`re.Pattern` or :data:`None`) is the compiled regular
153 expression for the pattern.
154 """
156 def __eq__(self, other: 'RegexPattern') -> bool:
157 """
158 Tests the equality of this regex pattern with *other* (:class:`RegexPattern`)
159 by comparing their :attr:`~Pattern.include` and :attr:`~RegexPattern.regex`
160 attributes.
161 """
162 if isinstance(other, RegexPattern):
163 return self.include == other.include and self.regex == other.regex
164 else:
165 return NotImplemented
167 @override
168 def match_file(self, file: str) -> Optional['RegexMatchResult']:
169 """
170 Matches this pattern against the specified file.
172 *file* (:class:`str`) contains each file relative to the root directory
173 (e.g., "relative/path/to/file").
175 Returns the match result (:class:`.RegexMatchResult`) if *file* matched;
176 otherwise, :data:`None`.
177 """
178 if self.include is not None:
179 match = self.regex.match(file)
180 if match is not None:
181 return RegexMatchResult(match)
183 return None
185 @classmethod
186 def pattern_to_regex(cls, pattern: str) -> tuple[str, bool]:
187 """
188 Convert the pattern into an uncompiled regular expression.
190 *pattern* (:class:`str`) is the pattern to convert into a regular
191 expression.
193 Returns the uncompiled regular expression (:class:`str` or :data:`None`),
194 and whether matched files should be included (:data:`True`), excluded
195 (:data:`False`), or is a null-operation (:data:`None`).
197 .. NOTE:: The default implementation simply returns *pattern* and
198 :data:`True`.
199 """
200 return pattern, True
203@dataclass()
204class RegexMatchResult(object):
205 """
206 The :class:`RegexMatchResult` data class is used to return information about
207 the matched regular expression.
208 """
210 # Keep the class dict-less.
211 __slots__ = (
212 'match',
213 )
215 match: re.Match
216 """
217 *match* (:class:`re.Match`) is the regex match result.
218 """