Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pathspec/pattern.py: 63%

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

63 statements  

1""" 

2This module provides the base definition for patterns. 

3""" 

4 

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 TypeVar, 

17 Union) # Replaced by `X | Y` in 3.10. 

18 

19from ._typing import ( 

20 override) # Added in 3.12. 

21 

22RegexPatternSelf = TypeVar("RegexPatternSelf", bound="RegexPattern") 

23""" 

24:class:`RegexPattern` self type hint to support Python v<3.11 using PEP 673 

25recommendation. 

26""" 

27 

28 

29class Pattern(object): 

30 """ 

31 The :class:`Pattern` class is the abstract definition of a pattern. 

32 """ 

33 

34 # Make the class dict-less. 

35 __slots__ = ( 

36 'include', 

37 ) 

38 

39 def __init__(self, include: Optional[bool]) -> None: 

40 """ 

41 Initializes the :class:`Pattern` instance. 

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 """ 

47 

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 """ 

54 

55 def match(self, files: Iterable[str]) -> Iterator[str]: 

56 """ 

57 DEPRECATED: This method is no longer used and has been replaced by 

58 :meth:`.match_file`. Use the :meth:`.match_file` method with a loop for 

59 similar results. 

60 

61 Matches this pattern against the specified files. 

62 

63 *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each 

64 file relative to the root directory (e.g., ``"relative/path/to/file"``). 

65 

66 Returns an :class:`~collections.abc.Iterable` yielding each matched file 

67 path (:class:`str`). 

68 """ 

69 warnings.warn(( 

70 "{cls.__module__}.{cls.__qualname__}.match() is deprecated. Use " 

71 "{cls.__module__}.{cls.__qualname__}.match_file() with a loop for " 

72 "similar results." 

73 ).format(cls=self.__class__), DeprecationWarning, stacklevel=2) 

74 

75 for file in files: 

76 if self.match_file(file) is not None: 

77 yield file 

78 

79 def match_file(self, file: str) -> Optional[Any]: 

80 """ 

81 Matches this pattern against the specified file. 

82 

83 *file* (:class:`str`) is the normalized file path to match against. 

84 

85 Returns the match result if *file* matched; otherwise, :data:`None`. 

86 """ 

87 raise NotImplementedError(( 

88 "{cls.__module__}.{cls.__qualname__} must override match_file()." 

89 ).format(cls=self.__class__)) 

90 

91 

92class RegexPattern(Pattern): 

93 """ 

94 The :class:`RegexPattern` class is an implementation of a pattern using 

95 regular expressions. 

96 """ 

97 

98 # Keep the class dict-less. 

99 __slots__ = ( 

100 'pattern', 

101 'regex', 

102 ) 

103 

104 def __init__( 

105 self, 

106 pattern: Union[AnyStr, re.Pattern, None], 

107 include: Optional[bool] = None, 

108 ) -> None: 

109 """ 

110 Initializes the :class:`RegexPattern` instance. 

111 

112 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or 

113 :data:`None`) is the pattern to compile into a regular expression. 

114 

115 *include* (:class:`bool` or :data:`None`) must be :data:`None` unless 

116 *pattern* is a precompiled regular expression (:class:`re.Pattern`) in which 

117 case it is whether matched files should be included (:data:`True`), excluded 

118 (:data:`False`), or is a null operation (:data:`None`). 

119 

120 .. NOTE:: Subclasses do not need to support the *include* parameter. 

121 """ 

122 

123 if isinstance(pattern, (str, bytes)): 

124 assert include is None, ( 

125 f"include:{include!r} must be null when pattern:{pattern!r} is a string." 

126 ) 

127 regex, include = self.pattern_to_regex(pattern) 

128 # NOTE: Make sure to allow a null regular expression to be 

129 # returned for a null-operation. 

130 if include is not None: 

131 regex = re.compile(regex) 

132 

133 elif pattern is not None and hasattr(pattern, 'match'): 

134 # Assume pattern is a precompiled regular expression. 

135 # - NOTE: Used specified *include*. 

136 regex = pattern 

137 

138 elif pattern is None: 

139 # NOTE: Make sure to allow a null pattern to be passed for a 

140 # null-operation. 

141 assert include is None, ( 

142 f"include:{include!r} must be null when pattern:{pattern!r} is null." 

143 ) 

144 regex = None 

145 

146 else: 

147 raise TypeError(f"pattern:{pattern!r} is not a string, re.Pattern, or None.") 

148 

149 super(RegexPattern, self).__init__(include) 

150 

151 self.pattern: Union[AnyStr, re.Pattern, None] = pattern 

152 """ 

153 *pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or 

154 :data:`None`) is the uncompiled, input pattern. This is for reference. 

155 """ 

156 

157 self.regex: Optional[re.Pattern] = regex 

158 """ 

159 *regex* (:class:`re.Pattern` or :data:`None`) is the compiled regular 

160 expression for the pattern. 

161 """ 

162 

163 def __copy__(self: RegexPatternSelf) -> RegexPatternSelf: 

164 """ 

165 Performa a shallow copy of the pattern. 

166 

167 Returns the copy (:class:`RegexPattern`). 

168 """ 

169 other = self.__class__(self.regex, self.include) 

170 other.pattern = self.pattern 

171 return other 

172 

173 def __eq__(self, other: 'RegexPattern') -> bool: 

174 """ 

175 Tests the equality of this regex pattern with *other* (:class:`RegexPattern`) 

176 by comparing their :attr:`~Pattern.include` and :attr:`~RegexPattern.regex` 

177 attributes. 

178 """ 

179 if isinstance(other, RegexPattern): 

180 return self.include == other.include and self.regex == other.regex 

181 else: 

182 return NotImplemented 

183 

184 @override 

185 def match_file(self, file: str) -> Optional['RegexMatchResult']: 

186 """ 

187 Matches this pattern against the specified file. 

188 

189 *file* (:class:`str`) contains each file relative to the root directory 

190 (e.g., "relative/path/to/file"). 

191 

192 Returns the match result (:class:`.RegexMatchResult`) if *file* matched; 

193 otherwise, :data:`None`. 

194 """ 

195 if self.include is not None: 

196 match = self.regex.search(file) 

197 if match is not None: 

198 return RegexMatchResult(match) 

199 

200 return None 

201 

202 @classmethod 

203 def pattern_to_regex(cls, pattern: str) -> tuple[str, bool]: 

204 """ 

205 Convert the pattern into an uncompiled regular expression. 

206 

207 *pattern* (:class:`str`) is the pattern to convert into a regular 

208 expression. 

209 

210 Returns the uncompiled regular expression (:class:`str` or :data:`None`), 

211 and whether matched files should be included (:data:`True`), excluded 

212 (:data:`False`), or is a null-operation (:data:`None`). 

213 

214 .. NOTE:: The default implementation simply returns *pattern* and 

215 :data:`True`. 

216 """ 

217 return pattern, True 

218 

219 

220@dataclass() 

221class RegexMatchResult(object): 

222 """ 

223 The :class:`RegexMatchResult` data class is used to return information about 

224 the matched regular expression. 

225 """ 

226 

227 # Keep the class dict-less. 

228 __slots__ = ( 

229 'match', 

230 ) 

231 

232 match: re.Match 

233 """ 

234 *match* (:class:`re.Match`) is the regex match result. 

235 """