Show More
@@ -1,799 +1,800 | |||
|
1 | 1 | # match.py - filename matching |
|
2 | 2 | # |
|
3 | 3 | # Copyright 2008, 2009 Matt Mackall <mpm@selenic.com> and others |
|
4 | 4 | # |
|
5 | 5 | # This software may be used and distributed according to the terms of the |
|
6 | 6 | # GNU General Public License version 2 or any later version. |
|
7 | 7 | |
|
8 | 8 | from __future__ import absolute_import |
|
9 | 9 | |
|
10 | 10 | import copy |
|
11 | 11 | import os |
|
12 | 12 | import re |
|
13 | 13 | |
|
14 | 14 | from .i18n import _ |
|
15 | 15 | from . import ( |
|
16 | 16 | error, |
|
17 | 17 | pathutil, |
|
18 | 18 | util, |
|
19 | 19 | ) |
|
20 | 20 | |
|
21 | 21 | propertycache = util.propertycache |
|
22 | 22 | |
|
23 | 23 | def _rematcher(regex): |
|
24 | 24 | '''compile the regexp with the best available regexp engine and return a |
|
25 | 25 | matcher function''' |
|
26 | 26 | m = util.re.compile(regex) |
|
27 | 27 | try: |
|
28 | 28 | # slightly faster, provided by facebook's re2 bindings |
|
29 | 29 | return m.test_match |
|
30 | 30 | except AttributeError: |
|
31 | 31 | return m.match |
|
32 | 32 | |
|
33 | 33 | def _expandsets(kindpats, ctx, listsubrepos): |
|
34 | 34 | '''Returns the kindpats list with the 'set' patterns expanded.''' |
|
35 | 35 | fset = set() |
|
36 | 36 | other = [] |
|
37 | 37 | |
|
38 | 38 | for kind, pat, source in kindpats: |
|
39 | 39 | if kind == 'set': |
|
40 | 40 | if not ctx: |
|
41 |
raise error. |
|
|
41 | raise error.ProgrammingError("fileset expression with no " | |
|
42 | "context") | |
|
42 | 43 | s = ctx.getfileset(pat) |
|
43 | 44 | fset.update(s) |
|
44 | 45 | |
|
45 | 46 | if listsubrepos: |
|
46 | 47 | for subpath in ctx.substate: |
|
47 | 48 | s = ctx.sub(subpath).getfileset(pat) |
|
48 | 49 | fset.update(subpath + '/' + f for f in s) |
|
49 | 50 | |
|
50 | 51 | continue |
|
51 | 52 | other.append((kind, pat, source)) |
|
52 | 53 | return fset, other |
|
53 | 54 | |
|
54 | 55 | def _expandsubinclude(kindpats, root): |
|
55 | 56 | '''Returns the list of subinclude matcher args and the kindpats without the |
|
56 | 57 | subincludes in it.''' |
|
57 | 58 | relmatchers = [] |
|
58 | 59 | other = [] |
|
59 | 60 | |
|
60 | 61 | for kind, pat, source in kindpats: |
|
61 | 62 | if kind == 'subinclude': |
|
62 | 63 | sourceroot = pathutil.dirname(util.normpath(source)) |
|
63 | 64 | pat = util.pconvert(pat) |
|
64 | 65 | path = pathutil.join(sourceroot, pat) |
|
65 | 66 | |
|
66 | 67 | newroot = pathutil.dirname(path) |
|
67 | 68 | matcherargs = (newroot, '', [], ['include:%s' % path]) |
|
68 | 69 | |
|
69 | 70 | prefix = pathutil.canonpath(root, root, newroot) |
|
70 | 71 | if prefix: |
|
71 | 72 | prefix += '/' |
|
72 | 73 | relmatchers.append((prefix, matcherargs)) |
|
73 | 74 | else: |
|
74 | 75 | other.append((kind, pat, source)) |
|
75 | 76 | |
|
76 | 77 | return relmatchers, other |
|
77 | 78 | |
|
78 | 79 | def _kindpatsalwaysmatch(kindpats): |
|
79 | 80 | """"Checks whether the kindspats match everything, as e.g. |
|
80 | 81 | 'relpath:.' does. |
|
81 | 82 | """ |
|
82 | 83 | for kind, pat, source in kindpats: |
|
83 | 84 | if pat != '' or kind not in ['relpath', 'glob']: |
|
84 | 85 | return False |
|
85 | 86 | return True |
|
86 | 87 | |
|
87 | 88 | def match(root, cwd, patterns, include=None, exclude=None, default='glob', |
|
88 | 89 | exact=False, auditor=None, ctx=None, listsubrepos=False, warn=None, |
|
89 | 90 | badfn=None, icasefs=False): |
|
90 | 91 | """build an object to match a set of file patterns |
|
91 | 92 | |
|
92 | 93 | arguments: |
|
93 | 94 | root - the canonical root of the tree you're matching against |
|
94 | 95 | cwd - the current working directory, if relevant |
|
95 | 96 | patterns - patterns to find |
|
96 | 97 | include - patterns to include (unless they are excluded) |
|
97 | 98 | exclude - patterns to exclude (even if they are included) |
|
98 | 99 | default - if a pattern in patterns has no explicit type, assume this one |
|
99 | 100 | exact - patterns are actually filenames (include/exclude still apply) |
|
100 | 101 | warn - optional function used for printing warnings |
|
101 | 102 | badfn - optional bad() callback for this matcher instead of the default |
|
102 | 103 | icasefs - make a matcher for wdir on case insensitive filesystems, which |
|
103 | 104 | normalizes the given patterns to the case in the filesystem |
|
104 | 105 | |
|
105 | 106 | a pattern is one of: |
|
106 | 107 | 'glob:<glob>' - a glob relative to cwd |
|
107 | 108 | 're:<regexp>' - a regular expression |
|
108 | 109 | 'path:<path>' - a path relative to repository root, which is matched |
|
109 | 110 | recursively |
|
110 | 111 | 'rootfilesin:<path>' - a path relative to repository root, which is |
|
111 | 112 | matched non-recursively (will not match subdirectories) |
|
112 | 113 | 'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs) |
|
113 | 114 | 'relpath:<path>' - a path relative to cwd |
|
114 | 115 | 'relre:<regexp>' - a regexp that needn't match the start of a name |
|
115 | 116 | 'set:<fileset>' - a fileset expression |
|
116 | 117 | 'include:<path>' - a file of patterns to read and include |
|
117 | 118 | 'subinclude:<path>' - a file of patterns to match against files under |
|
118 | 119 | the same directory |
|
119 | 120 | '<something>' - a pattern of the specified default type |
|
120 | 121 | """ |
|
121 | 122 | normalize = _donormalize |
|
122 | 123 | if icasefs: |
|
123 | 124 | if exact: |
|
124 |
raise error. |
|
|
125 |
"make sense") |
|
|
125 | raise error.ProgrammingError("a case-insensitive exact matcher " | |
|
126 | "doesn't make sense") | |
|
126 | 127 | dirstate = ctx.repo().dirstate |
|
127 | 128 | dsnormalize = dirstate.normalize |
|
128 | 129 | |
|
129 | 130 | def normalize(patterns, default, root, cwd, auditor, warn): |
|
130 | 131 | kp = _donormalize(patterns, default, root, cwd, auditor, warn) |
|
131 | 132 | kindpats = [] |
|
132 | 133 | for kind, pats, source in kp: |
|
133 | 134 | if kind not in ('re', 'relre'): # regex can't be normalized |
|
134 | 135 | p = pats |
|
135 | 136 | pats = dsnormalize(pats) |
|
136 | 137 | |
|
137 | 138 | # Preserve the original to handle a case only rename. |
|
138 | 139 | if p != pats and p in dirstate: |
|
139 | 140 | kindpats.append((kind, p, source)) |
|
140 | 141 | |
|
141 | 142 | kindpats.append((kind, pats, source)) |
|
142 | 143 | return kindpats |
|
143 | 144 | |
|
144 | 145 | return matcher(root, cwd, normalize, patterns, include=include, |
|
145 | 146 | exclude=exclude, default=default, exact=exact, |
|
146 | 147 | auditor=auditor, ctx=ctx, listsubrepos=listsubrepos, |
|
147 | 148 | warn=warn, badfn=badfn) |
|
148 | 149 | |
|
149 | 150 | def exact(root, cwd, files, badfn=None): |
|
150 | 151 | return match(root, cwd, files, exact=True, badfn=badfn) |
|
151 | 152 | |
|
152 | 153 | def always(root, cwd): |
|
153 | 154 | return match(root, cwd, []) |
|
154 | 155 | |
|
155 | 156 | def badmatch(match, badfn): |
|
156 | 157 | """Make a copy of the given matcher, replacing its bad method with the given |
|
157 | 158 | one. |
|
158 | 159 | """ |
|
159 | 160 | m = copy.copy(match) |
|
160 | 161 | m.bad = badfn |
|
161 | 162 | return m |
|
162 | 163 | |
|
163 | 164 | def _donormalize(patterns, default, root, cwd, auditor, warn): |
|
164 | 165 | '''Convert 'kind:pat' from the patterns list to tuples with kind and |
|
165 | 166 | normalized and rooted patterns and with listfiles expanded.''' |
|
166 | 167 | kindpats = [] |
|
167 | 168 | for kind, pat in [_patsplit(p, default) for p in patterns]: |
|
168 | 169 | if kind in ('glob', 'relpath'): |
|
169 | 170 | pat = pathutil.canonpath(root, cwd, pat, auditor) |
|
170 | 171 | elif kind in ('relglob', 'path', 'rootfilesin'): |
|
171 | 172 | pat = util.normpath(pat) |
|
172 | 173 | elif kind in ('listfile', 'listfile0'): |
|
173 | 174 | try: |
|
174 | 175 | files = util.readfile(pat) |
|
175 | 176 | if kind == 'listfile0': |
|
176 | 177 | files = files.split('\0') |
|
177 | 178 | else: |
|
178 | 179 | files = files.splitlines() |
|
179 | 180 | files = [f for f in files if f] |
|
180 | 181 | except EnvironmentError: |
|
181 | 182 | raise error.Abort(_("unable to read file list (%s)") % pat) |
|
182 | 183 | for k, p, source in _donormalize(files, default, root, cwd, |
|
183 | 184 | auditor, warn): |
|
184 | 185 | kindpats.append((k, p, pat)) |
|
185 | 186 | continue |
|
186 | 187 | elif kind == 'include': |
|
187 | 188 | try: |
|
188 | 189 | fullpath = os.path.join(root, util.localpath(pat)) |
|
189 | 190 | includepats = readpatternfile(fullpath, warn) |
|
190 | 191 | for k, p, source in _donormalize(includepats, default, |
|
191 | 192 | root, cwd, auditor, warn): |
|
192 | 193 | kindpats.append((k, p, source or pat)) |
|
193 | 194 | except error.Abort as inst: |
|
194 | 195 | raise error.Abort('%s: %s' % (pat, inst[0])) |
|
195 | 196 | except IOError as inst: |
|
196 | 197 | if warn: |
|
197 | 198 | warn(_("skipping unreadable pattern file '%s': %s\n") % |
|
198 | 199 | (pat, inst.strerror)) |
|
199 | 200 | continue |
|
200 | 201 | # else: re or relre - which cannot be normalized |
|
201 | 202 | kindpats.append((kind, pat, '')) |
|
202 | 203 | return kindpats |
|
203 | 204 | |
|
204 | 205 | class matcher(object): |
|
205 | 206 | |
|
206 | 207 | def __init__(self, root, cwd, normalize, patterns, include=None, |
|
207 | 208 | exclude=None, default='glob', exact=False, auditor=None, |
|
208 | 209 | ctx=None, listsubrepos=False, warn=None, badfn=None): |
|
209 | 210 | if include is None: |
|
210 | 211 | include = [] |
|
211 | 212 | if exclude is None: |
|
212 | 213 | exclude = [] |
|
213 | 214 | |
|
214 | 215 | self._root = root |
|
215 | 216 | self._cwd = cwd |
|
216 | 217 | self._files = [] # exact files and roots of patterns |
|
217 | 218 | self._anypats = bool(include or exclude) |
|
218 | 219 | self._always = False |
|
219 | 220 | self._pathrestricted = bool(include or exclude or patterns) |
|
220 | 221 | self.patternspat = None |
|
221 | 222 | self.includepat = None |
|
222 | 223 | self.excludepat = None |
|
223 | 224 | |
|
224 | 225 | # roots are directories which are recursively included/excluded. |
|
225 | 226 | self._includeroots = set() |
|
226 | 227 | self._excluderoots = set() |
|
227 | 228 | # dirs are directories which are non-recursively included. |
|
228 | 229 | self._includedirs = set() |
|
229 | 230 | |
|
230 | 231 | if badfn is not None: |
|
231 | 232 | self.bad = badfn |
|
232 | 233 | |
|
233 | 234 | matchfns = [] |
|
234 | 235 | if include: |
|
235 | 236 | kindpats = normalize(include, 'glob', root, cwd, auditor, warn) |
|
236 | 237 | self.includepat, im = _buildmatch(ctx, kindpats, '(?:/|$)', |
|
237 | 238 | listsubrepos, root) |
|
238 | 239 | roots, dirs = _rootsanddirs(kindpats) |
|
239 | 240 | self._includeroots.update(roots) |
|
240 | 241 | self._includedirs.update(dirs) |
|
241 | 242 | matchfns.append(im) |
|
242 | 243 | if exclude: |
|
243 | 244 | kindpats = normalize(exclude, 'glob', root, cwd, auditor, warn) |
|
244 | 245 | self.excludepat, em = _buildmatch(ctx, kindpats, '(?:/|$)', |
|
245 | 246 | listsubrepos, root) |
|
246 | 247 | if not _anypats(kindpats): |
|
247 | 248 | # Only consider recursive excludes as such - if a non-recursive |
|
248 | 249 | # exclude is used, we must still recurse into the excluded |
|
249 | 250 | # directory, at least to find subdirectories. In such a case, |
|
250 | 251 | # the regex still won't match the non-recursively-excluded |
|
251 | 252 | # files. |
|
252 | 253 | self._excluderoots.update(_roots(kindpats)) |
|
253 | 254 | matchfns.append(lambda f: not em(f)) |
|
254 | 255 | if exact: |
|
255 | 256 | if isinstance(patterns, list): |
|
256 | 257 | self._files = patterns |
|
257 | 258 | else: |
|
258 | 259 | self._files = list(patterns) |
|
259 | 260 | matchfns.append(self.exact) |
|
260 | 261 | elif patterns: |
|
261 | 262 | kindpats = normalize(patterns, default, root, cwd, auditor, warn) |
|
262 | 263 | if not _kindpatsalwaysmatch(kindpats): |
|
263 | 264 | self._files = _explicitfiles(kindpats) |
|
264 | 265 | self._anypats = self._anypats or _anypats(kindpats) |
|
265 | 266 | self.patternspat, pm = _buildmatch(ctx, kindpats, '$', |
|
266 | 267 | listsubrepos, root) |
|
267 | 268 | matchfns.append(pm) |
|
268 | 269 | |
|
269 | 270 | if not matchfns: |
|
270 | 271 | m = util.always |
|
271 | 272 | self._always = True |
|
272 | 273 | elif len(matchfns) == 1: |
|
273 | 274 | m = matchfns[0] |
|
274 | 275 | else: |
|
275 | 276 | def m(f): |
|
276 | 277 | for matchfn in matchfns: |
|
277 | 278 | if not matchfn(f): |
|
278 | 279 | return False |
|
279 | 280 | return True |
|
280 | 281 | |
|
281 | 282 | self.matchfn = m |
|
282 | 283 | |
|
283 | 284 | def __call__(self, fn): |
|
284 | 285 | return self.matchfn(fn) |
|
285 | 286 | def __iter__(self): |
|
286 | 287 | for f in self._files: |
|
287 | 288 | yield f |
|
288 | 289 | |
|
289 | 290 | # Callbacks related to how the matcher is used by dirstate.walk. |
|
290 | 291 | # Subscribers to these events must monkeypatch the matcher object. |
|
291 | 292 | def bad(self, f, msg): |
|
292 | 293 | '''Callback from dirstate.walk for each explicit file that can't be |
|
293 | 294 | found/accessed, with an error message.''' |
|
294 | 295 | pass |
|
295 | 296 | |
|
296 | 297 | # If an explicitdir is set, it will be called when an explicitly listed |
|
297 | 298 | # directory is visited. |
|
298 | 299 | explicitdir = None |
|
299 | 300 | |
|
300 | 301 | # If an traversedir is set, it will be called when a directory discovered |
|
301 | 302 | # by recursive traversal is visited. |
|
302 | 303 | traversedir = None |
|
303 | 304 | |
|
304 | 305 | def abs(self, f): |
|
305 | 306 | '''Convert a repo path back to path that is relative to the root of the |
|
306 | 307 | matcher.''' |
|
307 | 308 | return f |
|
308 | 309 | |
|
309 | 310 | def rel(self, f): |
|
310 | 311 | '''Convert repo path back to path that is relative to cwd of matcher.''' |
|
311 | 312 | return util.pathto(self._root, self._cwd, f) |
|
312 | 313 | |
|
313 | 314 | def uipath(self, f): |
|
314 | 315 | '''Convert repo path to a display path. If patterns or -I/-X were used |
|
315 | 316 | to create this matcher, the display path will be relative to cwd. |
|
316 | 317 | Otherwise it is relative to the root of the repo.''' |
|
317 | 318 | return (self._pathrestricted and self.rel(f)) or self.abs(f) |
|
318 | 319 | |
|
319 | 320 | def files(self): |
|
320 | 321 | '''Explicitly listed files or patterns or roots: |
|
321 | 322 | if no patterns or .always(): empty list, |
|
322 | 323 | if exact: list exact files, |
|
323 | 324 | if not .anypats(): list all files and dirs, |
|
324 | 325 | else: optimal roots''' |
|
325 | 326 | return self._files |
|
326 | 327 | |
|
327 | 328 | @propertycache |
|
328 | 329 | def _fileset(self): |
|
329 | 330 | return set(self._files) |
|
330 | 331 | |
|
331 | 332 | @propertycache |
|
332 | 333 | def _dirs(self): |
|
333 | 334 | return set(util.dirs(self._fileset)) | {'.'} |
|
334 | 335 | |
|
335 | 336 | def visitdir(self, dir): |
|
336 | 337 | '''Decides whether a directory should be visited based on whether it |
|
337 | 338 | has potential matches in it or one of its subdirectories. This is |
|
338 | 339 | based on the match's primary, included, and excluded patterns. |
|
339 | 340 | |
|
340 | 341 | Returns the string 'all' if the given directory and all subdirectories |
|
341 | 342 | should be visited. Otherwise returns True or False indicating whether |
|
342 | 343 | the given directory should be visited. |
|
343 | 344 | |
|
344 | 345 | This function's behavior is undefined if it has returned False for |
|
345 | 346 | one of the dir's parent directories. |
|
346 | 347 | ''' |
|
347 | 348 | if self.prefix() and dir in self._fileset: |
|
348 | 349 | return 'all' |
|
349 | 350 | if dir in self._excluderoots: |
|
350 | 351 | return False |
|
351 | 352 | if ((self._includeroots or self._includedirs) and |
|
352 | 353 | '.' not in self._includeroots and |
|
353 | 354 | dir not in self._includeroots and |
|
354 | 355 | dir not in self._includedirs and |
|
355 | 356 | not any(parent in self._includeroots |
|
356 | 357 | for parent in util.finddirs(dir))): |
|
357 | 358 | return False |
|
358 | 359 | return (not self._fileset or |
|
359 | 360 | '.' in self._fileset or |
|
360 | 361 | dir in self._fileset or |
|
361 | 362 | dir in self._dirs or |
|
362 | 363 | any(parentdir in self._fileset |
|
363 | 364 | for parentdir in util.finddirs(dir))) |
|
364 | 365 | |
|
365 | 366 | def exact(self, f): |
|
366 | 367 | '''Returns True if f is in .files().''' |
|
367 | 368 | return f in self._fileset |
|
368 | 369 | |
|
369 | 370 | def anypats(self): |
|
370 | 371 | '''Matcher uses patterns or include/exclude.''' |
|
371 | 372 | return self._anypats |
|
372 | 373 | |
|
373 | 374 | def always(self): |
|
374 | 375 | '''Matcher will match everything and .files() will be empty |
|
375 | 376 | - optimization might be possible and necessary.''' |
|
376 | 377 | return self._always |
|
377 | 378 | |
|
378 | 379 | def isexact(self): |
|
379 | 380 | return self.matchfn == self.exact |
|
380 | 381 | |
|
381 | 382 | def prefix(self): |
|
382 | 383 | return not self.always() and not self.isexact() and not self.anypats() |
|
383 | 384 | |
|
384 | 385 | def __repr__(self): |
|
385 | 386 | return ('<matcher files=%r, patterns=%r, includes=%r, excludes=%r>' % |
|
386 | 387 | (self._files, self.patternspat, self.includepat, |
|
387 | 388 | self.excludepat)) |
|
388 | 389 | |
|
389 | 390 | class subdirmatcher(matcher): |
|
390 | 391 | """Adapt a matcher to work on a subdirectory only. |
|
391 | 392 | |
|
392 | 393 | The paths are remapped to remove/insert the path as needed: |
|
393 | 394 | |
|
394 | 395 | >>> m1 = match('root', '', ['a.txt', 'sub/b.txt']) |
|
395 | 396 | >>> m2 = subdirmatcher('sub', m1) |
|
396 | 397 | >>> bool(m2('a.txt')) |
|
397 | 398 | False |
|
398 | 399 | >>> bool(m2('b.txt')) |
|
399 | 400 | True |
|
400 | 401 | >>> bool(m2.matchfn('a.txt')) |
|
401 | 402 | False |
|
402 | 403 | >>> bool(m2.matchfn('b.txt')) |
|
403 | 404 | True |
|
404 | 405 | >>> m2.files() |
|
405 | 406 | ['b.txt'] |
|
406 | 407 | >>> m2.exact('b.txt') |
|
407 | 408 | True |
|
408 | 409 | >>> util.pconvert(m2.rel('b.txt')) |
|
409 | 410 | 'sub/b.txt' |
|
410 | 411 | >>> def bad(f, msg): |
|
411 | 412 | ... print "%s: %s" % (f, msg) |
|
412 | 413 | >>> m1.bad = bad |
|
413 | 414 | >>> m2.bad('x.txt', 'No such file') |
|
414 | 415 | sub/x.txt: No such file |
|
415 | 416 | >>> m2.abs('c.txt') |
|
416 | 417 | 'sub/c.txt' |
|
417 | 418 | """ |
|
418 | 419 | |
|
419 | 420 | def __init__(self, path, matcher): |
|
420 | 421 | self._root = matcher._root |
|
421 | 422 | self._cwd = matcher._cwd |
|
422 | 423 | self._path = path |
|
423 | 424 | self._matcher = matcher |
|
424 | 425 | self._always = matcher._always |
|
425 | 426 | |
|
426 | 427 | self._files = [f[len(path) + 1:] for f in matcher._files |
|
427 | 428 | if f.startswith(path + "/")] |
|
428 | 429 | |
|
429 | 430 | # If the parent repo had a path to this subrepo and the matcher is |
|
430 | 431 | # a prefix matcher, this submatcher always matches. |
|
431 | 432 | if matcher.prefix(): |
|
432 | 433 | self._always = any(f == path for f in matcher._files) |
|
433 | 434 | |
|
434 | 435 | self._anypats = matcher._anypats |
|
435 | 436 | # Some information is lost in the superclass's constructor, so we |
|
436 | 437 | # can not accurately create the matching function for the subdirectory |
|
437 | 438 | # from the inputs. Instead, we override matchfn() and visitdir() to |
|
438 | 439 | # call the original matcher with the subdirectory path prepended. |
|
439 | 440 | self.matchfn = lambda fn: matcher.matchfn(self._path + "/" + fn) |
|
440 | 441 | |
|
441 | 442 | def bad(self, f, msg): |
|
442 | 443 | self._matcher.bad(self._path + "/" + f, msg) |
|
443 | 444 | |
|
444 | 445 | def abs(self, f): |
|
445 | 446 | return self._matcher.abs(self._path + "/" + f) |
|
446 | 447 | |
|
447 | 448 | def rel(self, f): |
|
448 | 449 | return self._matcher.rel(self._path + "/" + f) |
|
449 | 450 | |
|
450 | 451 | def uipath(self, f): |
|
451 | 452 | return self._matcher.uipath(self._path + "/" + f) |
|
452 | 453 | |
|
453 | 454 | def visitdir(self, dir): |
|
454 | 455 | if dir == '.': |
|
455 | 456 | dir = self._path |
|
456 | 457 | else: |
|
457 | 458 | dir = self._path + "/" + dir |
|
458 | 459 | return self._matcher.visitdir(dir) |
|
459 | 460 | |
|
460 | 461 | def patkind(pattern, default=None): |
|
461 | 462 | '''If pattern is 'kind:pat' with a known kind, return kind.''' |
|
462 | 463 | return _patsplit(pattern, default)[0] |
|
463 | 464 | |
|
464 | 465 | def _patsplit(pattern, default): |
|
465 | 466 | """Split a string into the optional pattern kind prefix and the actual |
|
466 | 467 | pattern.""" |
|
467 | 468 | if ':' in pattern: |
|
468 | 469 | kind, pat = pattern.split(':', 1) |
|
469 | 470 | if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre', |
|
470 | 471 | 'listfile', 'listfile0', 'set', 'include', 'subinclude', |
|
471 | 472 | 'rootfilesin'): |
|
472 | 473 | return kind, pat |
|
473 | 474 | return default, pattern |
|
474 | 475 | |
|
475 | 476 | def _globre(pat): |
|
476 | 477 | r'''Convert an extended glob string to a regexp string. |
|
477 | 478 | |
|
478 | 479 | >>> print _globre(r'?') |
|
479 | 480 | . |
|
480 | 481 | >>> print _globre(r'*') |
|
481 | 482 | [^/]* |
|
482 | 483 | >>> print _globre(r'**') |
|
483 | 484 | .* |
|
484 | 485 | >>> print _globre(r'**/a') |
|
485 | 486 | (?:.*/)?a |
|
486 | 487 | >>> print _globre(r'a/**/b') |
|
487 | 488 | a\/(?:.*/)?b |
|
488 | 489 | >>> print _globre(r'[a*?!^][^b][!c]') |
|
489 | 490 | [a*?!^][\^b][^c] |
|
490 | 491 | >>> print _globre(r'{a,b}') |
|
491 | 492 | (?:a|b) |
|
492 | 493 | >>> print _globre(r'.\*\?') |
|
493 | 494 | \.\*\? |
|
494 | 495 | ''' |
|
495 | 496 | i, n = 0, len(pat) |
|
496 | 497 | res = '' |
|
497 | 498 | group = 0 |
|
498 | 499 | escape = util.re.escape |
|
499 | 500 | def peek(): |
|
500 | 501 | return i < n and pat[i:i + 1] |
|
501 | 502 | while i < n: |
|
502 | 503 | c = pat[i:i + 1] |
|
503 | 504 | i += 1 |
|
504 | 505 | if c not in '*?[{},\\': |
|
505 | 506 | res += escape(c) |
|
506 | 507 | elif c == '*': |
|
507 | 508 | if peek() == '*': |
|
508 | 509 | i += 1 |
|
509 | 510 | if peek() == '/': |
|
510 | 511 | i += 1 |
|
511 | 512 | res += '(?:.*/)?' |
|
512 | 513 | else: |
|
513 | 514 | res += '.*' |
|
514 | 515 | else: |
|
515 | 516 | res += '[^/]*' |
|
516 | 517 | elif c == '?': |
|
517 | 518 | res += '.' |
|
518 | 519 | elif c == '[': |
|
519 | 520 | j = i |
|
520 | 521 | if j < n and pat[j:j + 1] in '!]': |
|
521 | 522 | j += 1 |
|
522 | 523 | while j < n and pat[j:j + 1] != ']': |
|
523 | 524 | j += 1 |
|
524 | 525 | if j >= n: |
|
525 | 526 | res += '\\[' |
|
526 | 527 | else: |
|
527 | 528 | stuff = pat[i:j].replace('\\','\\\\') |
|
528 | 529 | i = j + 1 |
|
529 | 530 | if stuff[0:1] == '!': |
|
530 | 531 | stuff = '^' + stuff[1:] |
|
531 | 532 | elif stuff[0:1] == '^': |
|
532 | 533 | stuff = '\\' + stuff |
|
533 | 534 | res = '%s[%s]' % (res, stuff) |
|
534 | 535 | elif c == '{': |
|
535 | 536 | group += 1 |
|
536 | 537 | res += '(?:' |
|
537 | 538 | elif c == '}' and group: |
|
538 | 539 | res += ')' |
|
539 | 540 | group -= 1 |
|
540 | 541 | elif c == ',' and group: |
|
541 | 542 | res += '|' |
|
542 | 543 | elif c == '\\': |
|
543 | 544 | p = peek() |
|
544 | 545 | if p: |
|
545 | 546 | i += 1 |
|
546 | 547 | res += escape(p) |
|
547 | 548 | else: |
|
548 | 549 | res += escape(c) |
|
549 | 550 | else: |
|
550 | 551 | res += escape(c) |
|
551 | 552 | return res |
|
552 | 553 | |
|
553 | 554 | def _regex(kind, pat, globsuffix): |
|
554 | 555 | '''Convert a (normalized) pattern of any kind into a regular expression. |
|
555 | 556 | globsuffix is appended to the regexp of globs.''' |
|
556 | 557 | if not pat: |
|
557 | 558 | return '' |
|
558 | 559 | if kind == 're': |
|
559 | 560 | return pat |
|
560 | 561 | if kind == 'path': |
|
561 | 562 | if pat == '.': |
|
562 | 563 | return '' |
|
563 | 564 | return '^' + util.re.escape(pat) + '(?:/|$)' |
|
564 | 565 | if kind == 'rootfilesin': |
|
565 | 566 | if pat == '.': |
|
566 | 567 | escaped = '' |
|
567 | 568 | else: |
|
568 | 569 | # Pattern is a directory name. |
|
569 | 570 | escaped = util.re.escape(pat) + '/' |
|
570 | 571 | # Anything after the pattern must be a non-directory. |
|
571 | 572 | return '^' + escaped + '[^/]+$' |
|
572 | 573 | if kind == 'relglob': |
|
573 | 574 | return '(?:|.*/)' + _globre(pat) + globsuffix |
|
574 | 575 | if kind == 'relpath': |
|
575 | 576 | return util.re.escape(pat) + '(?:/|$)' |
|
576 | 577 | if kind == 'relre': |
|
577 | 578 | if pat.startswith('^'): |
|
578 | 579 | return pat |
|
579 | 580 | return '.*' + pat |
|
580 | 581 | return _globre(pat) + globsuffix |
|
581 | 582 | |
|
582 | 583 | def _buildmatch(ctx, kindpats, globsuffix, listsubrepos, root): |
|
583 | 584 | '''Return regexp string and a matcher function for kindpats. |
|
584 | 585 | globsuffix is appended to the regexp of globs.''' |
|
585 | 586 | matchfuncs = [] |
|
586 | 587 | |
|
587 | 588 | subincludes, kindpats = _expandsubinclude(kindpats, root) |
|
588 | 589 | if subincludes: |
|
589 | 590 | submatchers = {} |
|
590 | 591 | def matchsubinclude(f): |
|
591 | 592 | for prefix, matcherargs in subincludes: |
|
592 | 593 | if f.startswith(prefix): |
|
593 | 594 | mf = submatchers.get(prefix) |
|
594 | 595 | if mf is None: |
|
595 | 596 | mf = match(*matcherargs) |
|
596 | 597 | submatchers[prefix] = mf |
|
597 | 598 | |
|
598 | 599 | if mf(f[len(prefix):]): |
|
599 | 600 | return True |
|
600 | 601 | return False |
|
601 | 602 | matchfuncs.append(matchsubinclude) |
|
602 | 603 | |
|
603 | 604 | fset, kindpats = _expandsets(kindpats, ctx, listsubrepos) |
|
604 | 605 | if fset: |
|
605 | 606 | matchfuncs.append(fset.__contains__) |
|
606 | 607 | |
|
607 | 608 | regex = '' |
|
608 | 609 | if kindpats: |
|
609 | 610 | regex, mf = _buildregexmatch(kindpats, globsuffix) |
|
610 | 611 | matchfuncs.append(mf) |
|
611 | 612 | |
|
612 | 613 | if len(matchfuncs) == 1: |
|
613 | 614 | return regex, matchfuncs[0] |
|
614 | 615 | else: |
|
615 | 616 | return regex, lambda f: any(mf(f) for mf in matchfuncs) |
|
616 | 617 | |
|
617 | 618 | def _buildregexmatch(kindpats, globsuffix): |
|
618 | 619 | """Build a match function from a list of kinds and kindpats, |
|
619 | 620 | return regexp string and a matcher function.""" |
|
620 | 621 | try: |
|
621 | 622 | regex = '(?:%s)' % '|'.join([_regex(k, p, globsuffix) |
|
622 | 623 | for (k, p, s) in kindpats]) |
|
623 | 624 | if len(regex) > 20000: |
|
624 | 625 | raise OverflowError |
|
625 | 626 | return regex, _rematcher(regex) |
|
626 | 627 | except OverflowError: |
|
627 | 628 | # We're using a Python with a tiny regex engine and we |
|
628 | 629 | # made it explode, so we'll divide the pattern list in two |
|
629 | 630 | # until it works |
|
630 | 631 | l = len(kindpats) |
|
631 | 632 | if l < 2: |
|
632 | 633 | raise |
|
633 | 634 | regexa, a = _buildregexmatch(kindpats[:l//2], globsuffix) |
|
634 | 635 | regexb, b = _buildregexmatch(kindpats[l//2:], globsuffix) |
|
635 | 636 | return regex, lambda s: a(s) or b(s) |
|
636 | 637 | except re.error: |
|
637 | 638 | for k, p, s in kindpats: |
|
638 | 639 | try: |
|
639 | 640 | _rematcher('(?:%s)' % _regex(k, p, globsuffix)) |
|
640 | 641 | except re.error: |
|
641 | 642 | if s: |
|
642 | 643 | raise error.Abort(_("%s: invalid pattern (%s): %s") % |
|
643 | 644 | (s, k, p)) |
|
644 | 645 | else: |
|
645 | 646 | raise error.Abort(_("invalid pattern (%s): %s") % (k, p)) |
|
646 | 647 | raise error.Abort(_("invalid pattern")) |
|
647 | 648 | |
|
648 | 649 | def _patternrootsanddirs(kindpats): |
|
649 | 650 | '''Returns roots and directories corresponding to each pattern. |
|
650 | 651 | |
|
651 | 652 | This calculates the roots and directories exactly matching the patterns and |
|
652 | 653 | returns a tuple of (roots, dirs) for each. It does not return other |
|
653 | 654 | directories which may also need to be considered, like the parent |
|
654 | 655 | directories. |
|
655 | 656 | ''' |
|
656 | 657 | r = [] |
|
657 | 658 | d = [] |
|
658 | 659 | for kind, pat, source in kindpats: |
|
659 | 660 | if kind == 'glob': # find the non-glob prefix |
|
660 | 661 | root = [] |
|
661 | 662 | for p in pat.split('/'): |
|
662 | 663 | if '[' in p or '{' in p or '*' in p or '?' in p: |
|
663 | 664 | break |
|
664 | 665 | root.append(p) |
|
665 | 666 | r.append('/'.join(root) or '.') |
|
666 | 667 | elif kind in ('relpath', 'path'): |
|
667 | 668 | r.append(pat or '.') |
|
668 | 669 | elif kind in ('rootfilesin',): |
|
669 | 670 | d.append(pat or '.') |
|
670 | 671 | else: # relglob, re, relre |
|
671 | 672 | r.append('.') |
|
672 | 673 | return r, d |
|
673 | 674 | |
|
674 | 675 | def _roots(kindpats): |
|
675 | 676 | '''Returns root directories to match recursively from the given patterns.''' |
|
676 | 677 | roots, dirs = _patternrootsanddirs(kindpats) |
|
677 | 678 | return roots |
|
678 | 679 | |
|
679 | 680 | def _rootsanddirs(kindpats): |
|
680 | 681 | '''Returns roots and exact directories from patterns. |
|
681 | 682 | |
|
682 | 683 | roots are directories to match recursively, whereas exact directories should |
|
683 | 684 | be matched non-recursively. The returned (roots, dirs) tuple will also |
|
684 | 685 | include directories that need to be implicitly considered as either, such as |
|
685 | 686 | parent directories. |
|
686 | 687 | |
|
687 | 688 | >>> _rootsanddirs(\ |
|
688 | 689 | [('glob', 'g/h/*', ''), ('glob', 'g/h', ''), ('glob', 'g*', '')]) |
|
689 | 690 | (['g/h', 'g/h', '.'], ['g', '.']) |
|
690 | 691 | >>> _rootsanddirs(\ |
|
691 | 692 | [('rootfilesin', 'g/h', ''), ('rootfilesin', '', '')]) |
|
692 | 693 | ([], ['g/h', '.', 'g', '.']) |
|
693 | 694 | >>> _rootsanddirs(\ |
|
694 | 695 | [('relpath', 'r', ''), ('path', 'p/p', ''), ('path', '', '')]) |
|
695 | 696 | (['r', 'p/p', '.'], ['p', '.']) |
|
696 | 697 | >>> _rootsanddirs(\ |
|
697 | 698 | [('relglob', 'rg*', ''), ('re', 're/', ''), ('relre', 'rr', '')]) |
|
698 | 699 | (['.', '.', '.'], ['.']) |
|
699 | 700 | ''' |
|
700 | 701 | r, d = _patternrootsanddirs(kindpats) |
|
701 | 702 | |
|
702 | 703 | # Append the parents as non-recursive/exact directories, since they must be |
|
703 | 704 | # scanned to get to either the roots or the other exact directories. |
|
704 | 705 | d.extend(util.dirs(d)) |
|
705 | 706 | d.extend(util.dirs(r)) |
|
706 | 707 | # util.dirs() does not include the root directory, so add it manually |
|
707 | 708 | d.append('.') |
|
708 | 709 | |
|
709 | 710 | return r, d |
|
710 | 711 | |
|
711 | 712 | def _explicitfiles(kindpats): |
|
712 | 713 | '''Returns the potential explicit filenames from the patterns. |
|
713 | 714 | |
|
714 | 715 | >>> _explicitfiles([('path', 'foo/bar', '')]) |
|
715 | 716 | ['foo/bar'] |
|
716 | 717 | >>> _explicitfiles([('rootfilesin', 'foo/bar', '')]) |
|
717 | 718 | [] |
|
718 | 719 | ''' |
|
719 | 720 | # Keep only the pattern kinds where one can specify filenames (vs only |
|
720 | 721 | # directory names). |
|
721 | 722 | filable = [kp for kp in kindpats if kp[0] not in ('rootfilesin',)] |
|
722 | 723 | return _roots(filable) |
|
723 | 724 | |
|
724 | 725 | def _anypats(kindpats): |
|
725 | 726 | for kind, pat, source in kindpats: |
|
726 | 727 | if kind in ('glob', 're', 'relglob', 'relre', 'set', 'rootfilesin'): |
|
727 | 728 | return True |
|
728 | 729 | |
|
729 | 730 | _commentre = None |
|
730 | 731 | |
|
731 | 732 | def readpatternfile(filepath, warn, sourceinfo=False): |
|
732 | 733 | '''parse a pattern file, returning a list of |
|
733 | 734 | patterns. These patterns should be given to compile() |
|
734 | 735 | to be validated and converted into a match function. |
|
735 | 736 | |
|
736 | 737 | trailing white space is dropped. |
|
737 | 738 | the escape character is backslash. |
|
738 | 739 | comments start with #. |
|
739 | 740 | empty lines are skipped. |
|
740 | 741 | |
|
741 | 742 | lines can be of the following formats: |
|
742 | 743 | |
|
743 | 744 | syntax: regexp # defaults following lines to non-rooted regexps |
|
744 | 745 | syntax: glob # defaults following lines to non-rooted globs |
|
745 | 746 | re:pattern # non-rooted regular expression |
|
746 | 747 | glob:pattern # non-rooted glob |
|
747 | 748 | pattern # pattern of the current default type |
|
748 | 749 | |
|
749 | 750 | if sourceinfo is set, returns a list of tuples: |
|
750 | 751 | (pattern, lineno, originalline). This is useful to debug ignore patterns. |
|
751 | 752 | ''' |
|
752 | 753 | |
|
753 | 754 | syntaxes = {'re': 'relre:', 'regexp': 'relre:', 'glob': 'relglob:', |
|
754 | 755 | 'include': 'include', 'subinclude': 'subinclude'} |
|
755 | 756 | syntax = 'relre:' |
|
756 | 757 | patterns = [] |
|
757 | 758 | |
|
758 | 759 | fp = open(filepath, 'rb') |
|
759 | 760 | for lineno, line in enumerate(util.iterfile(fp), start=1): |
|
760 | 761 | if "#" in line: |
|
761 | 762 | global _commentre |
|
762 | 763 | if not _commentre: |
|
763 | 764 | _commentre = util.re.compile(br'((?:^|[^\\])(?:\\\\)*)#.*') |
|
764 | 765 | # remove comments prefixed by an even number of escapes |
|
765 | 766 | m = _commentre.search(line) |
|
766 | 767 | if m: |
|
767 | 768 | line = line[:m.end(1)] |
|
768 | 769 | # fixup properly escaped comments that survived the above |
|
769 | 770 | line = line.replace("\\#", "#") |
|
770 | 771 | line = line.rstrip() |
|
771 | 772 | if not line: |
|
772 | 773 | continue |
|
773 | 774 | |
|
774 | 775 | if line.startswith('syntax:'): |
|
775 | 776 | s = line[7:].strip() |
|
776 | 777 | try: |
|
777 | 778 | syntax = syntaxes[s] |
|
778 | 779 | except KeyError: |
|
779 | 780 | if warn: |
|
780 | 781 | warn(_("%s: ignoring invalid syntax '%s'\n") % |
|
781 | 782 | (filepath, s)) |
|
782 | 783 | continue |
|
783 | 784 | |
|
784 | 785 | linesyntax = syntax |
|
785 | 786 | for s, rels in syntaxes.iteritems(): |
|
786 | 787 | if line.startswith(rels): |
|
787 | 788 | linesyntax = rels |
|
788 | 789 | line = line[len(rels):] |
|
789 | 790 | break |
|
790 | 791 | elif line.startswith(s+':'): |
|
791 | 792 | linesyntax = rels |
|
792 | 793 | line = line[len(s) + 1:] |
|
793 | 794 | break |
|
794 | 795 | if sourceinfo: |
|
795 | 796 | patterns.append((linesyntax + line, lineno, line)) |
|
796 | 797 | else: |
|
797 | 798 | patterns.append(linesyntax + line) |
|
798 | 799 | fp.close() |
|
799 | 800 | return patterns |
General Comments 0
You need to be logged in to leave comments.
Login now