##// END OF EJS Templates
revset: added cache to lazysets...
Lucas Moscovicz -
r20512:659b8d8d default
parent child Browse files
Show More
@@ -1,2214 +1,2218 b''
1 1 # revset.py - revision set queries for mercurial
2 2 #
3 3 # Copyright 2010 Matt Mackall <mpm@selenic.com>
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 import re
9 9 import parser, util, error, discovery, hbisect, phases
10 10 import node
11 11 import match as matchmod
12 12 from i18n import _
13 13 import encoding
14 14 import obsolete as obsmod
15 15 import pathutil
16 16 import repoview
17 17
18 18 def _revancestors(repo, revs, followfirst):
19 19 """Like revlog.ancestors(), but supports followfirst."""
20 20 cut = followfirst and 1 or None
21 21 cl = repo.changelog
22 22 visit = util.deque(revs)
23 23 seen = set([node.nullrev])
24 24 while visit:
25 25 for parent in cl.parentrevs(visit.popleft())[:cut]:
26 26 if parent not in seen:
27 27 visit.append(parent)
28 28 seen.add(parent)
29 29 yield parent
30 30
31 31 def _revdescendants(repo, revs, followfirst):
32 32 """Like revlog.descendants() but supports followfirst."""
33 33 cut = followfirst and 1 or None
34 34 cl = repo.changelog
35 35 first = min(revs)
36 36 nullrev = node.nullrev
37 37 if first == nullrev:
38 38 # Are there nodes with a null first parent and a non-null
39 39 # second one? Maybe. Do we care? Probably not.
40 40 for i in cl:
41 41 yield i
42 42 return
43 43
44 44 seen = set(revs)
45 45 for i in cl.revs(first + 1):
46 46 for x in cl.parentrevs(i)[:cut]:
47 47 if x != nullrev and x in seen:
48 48 seen.add(i)
49 49 yield i
50 50 break
51 51
52 52 def _revsbetween(repo, roots, heads):
53 53 """Return all paths between roots and heads, inclusive of both endpoint
54 54 sets."""
55 55 if not roots:
56 56 return baseset([])
57 57 parentrevs = repo.changelog.parentrevs
58 58 visit = baseset(heads)
59 59 reachable = set()
60 60 seen = {}
61 61 minroot = min(roots)
62 62 roots = set(roots)
63 63 # open-code the post-order traversal due to the tiny size of
64 64 # sys.getrecursionlimit()
65 65 while visit:
66 66 rev = visit.pop()
67 67 if rev in roots:
68 68 reachable.add(rev)
69 69 parents = parentrevs(rev)
70 70 seen[rev] = parents
71 71 for parent in parents:
72 72 if parent >= minroot and parent not in seen:
73 73 visit.append(parent)
74 74 if not reachable:
75 75 return baseset([])
76 76 for rev in sorted(seen):
77 77 for parent in seen[rev]:
78 78 if parent in reachable:
79 79 reachable.add(rev)
80 80 return baseset(sorted(reachable))
81 81
82 82 elements = {
83 83 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
84 84 "~": (18, None, ("ancestor", 18)),
85 85 "^": (18, None, ("parent", 18), ("parentpost", 18)),
86 86 "-": (5, ("negate", 19), ("minus", 5)),
87 87 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
88 88 ("dagrangepost", 17)),
89 89 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
90 90 ("dagrangepost", 17)),
91 91 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
92 92 "not": (10, ("not", 10)),
93 93 "!": (10, ("not", 10)),
94 94 "and": (5, None, ("and", 5)),
95 95 "&": (5, None, ("and", 5)),
96 96 "or": (4, None, ("or", 4)),
97 97 "|": (4, None, ("or", 4)),
98 98 "+": (4, None, ("or", 4)),
99 99 ",": (2, None, ("list", 2)),
100 100 ")": (0, None, None),
101 101 "symbol": (0, ("symbol",), None),
102 102 "string": (0, ("string",), None),
103 103 "end": (0, None, None),
104 104 }
105 105
106 106 keywords = set(['and', 'or', 'not'])
107 107
108 108 def tokenize(program):
109 109 '''
110 110 Parse a revset statement into a stream of tokens
111 111
112 112 Check that @ is a valid unquoted token character (issue3686):
113 113 >>> list(tokenize("@::"))
114 114 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
115 115
116 116 '''
117 117
118 118 pos, l = 0, len(program)
119 119 while pos < l:
120 120 c = program[pos]
121 121 if c.isspace(): # skip inter-token whitespace
122 122 pass
123 123 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
124 124 yield ('::', None, pos)
125 125 pos += 1 # skip ahead
126 126 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
127 127 yield ('..', None, pos)
128 128 pos += 1 # skip ahead
129 129 elif c in "():,-|&+!~^": # handle simple operators
130 130 yield (c, None, pos)
131 131 elif (c in '"\'' or c == 'r' and
132 132 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
133 133 if c == 'r':
134 134 pos += 1
135 135 c = program[pos]
136 136 decode = lambda x: x
137 137 else:
138 138 decode = lambda x: x.decode('string-escape')
139 139 pos += 1
140 140 s = pos
141 141 while pos < l: # find closing quote
142 142 d = program[pos]
143 143 if d == '\\': # skip over escaped characters
144 144 pos += 2
145 145 continue
146 146 if d == c:
147 147 yield ('string', decode(program[s:pos]), s)
148 148 break
149 149 pos += 1
150 150 else:
151 151 raise error.ParseError(_("unterminated string"), s)
152 152 # gather up a symbol/keyword
153 153 elif c.isalnum() or c in '._@' or ord(c) > 127:
154 154 s = pos
155 155 pos += 1
156 156 while pos < l: # find end of symbol
157 157 d = program[pos]
158 158 if not (d.isalnum() or d in "._/@" or ord(d) > 127):
159 159 break
160 160 if d == '.' and program[pos - 1] == '.': # special case for ..
161 161 pos -= 1
162 162 break
163 163 pos += 1
164 164 sym = program[s:pos]
165 165 if sym in keywords: # operator keywords
166 166 yield (sym, None, s)
167 167 else:
168 168 yield ('symbol', sym, s)
169 169 pos -= 1
170 170 else:
171 171 raise error.ParseError(_("syntax error"), pos)
172 172 pos += 1
173 173 yield ('end', None, pos)
174 174
175 175 # helpers
176 176
177 177 def getstring(x, err):
178 178 if x and (x[0] == 'string' or x[0] == 'symbol'):
179 179 return x[1]
180 180 raise error.ParseError(err)
181 181
182 182 def getlist(x):
183 183 if not x:
184 184 return []
185 185 if x[0] == 'list':
186 186 return getlist(x[1]) + [x[2]]
187 187 return [x]
188 188
189 189 def getargs(x, min, max, err):
190 190 l = getlist(x)
191 191 if len(l) < min or (max >= 0 and len(l) > max):
192 192 raise error.ParseError(err)
193 193 return l
194 194
195 195 def getset(repo, subset, x):
196 196 if not x:
197 197 raise error.ParseError(_("missing argument"))
198 198 return methods[x[0]](repo, subset, *x[1:])
199 199
200 200 def _getrevsource(repo, r):
201 201 extra = repo[r].extra()
202 202 for label in ('source', 'transplant_source', 'rebase_source'):
203 203 if label in extra:
204 204 try:
205 205 return repo[extra[label]].rev()
206 206 except error.RepoLookupError:
207 207 pass
208 208 return None
209 209
210 210 # operator methods
211 211
212 212 def stringset(repo, subset, x):
213 213 x = repo[x].rev()
214 214 if x == -1 and len(subset) == len(repo):
215 215 return baseset([-1])
216 216 if len(subset) == len(repo) or x in subset:
217 217 return baseset([x])
218 218 return baseset([])
219 219
220 220 def symbolset(repo, subset, x):
221 221 if x in symbols:
222 222 raise error.ParseError(_("can't use %s here") % x)
223 223 return stringset(repo, subset, x)
224 224
225 225 def rangeset(repo, subset, x, y):
226 226 cl = baseset(repo.changelog)
227 227 m = getset(repo, cl, x)
228 228 n = getset(repo, cl, y)
229 229
230 230 if not m or not n:
231 231 return baseset([])
232 232 m, n = m[0], n[-1]
233 233
234 234 if m < n:
235 235 r = range(m, n + 1)
236 236 else:
237 237 r = range(m, n - 1, -1)
238 238 s = subset.set()
239 239 return baseset([x for x in r if x in s])
240 240
241 241 def dagrange(repo, subset, x, y):
242 242 r = baseset(repo)
243 243 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
244 244 s = subset.set()
245 245 return baseset([r for r in xs if r in s])
246 246
247 247 def andset(repo, subset, x, y):
248 248 return getset(repo, getset(repo, subset, x), y)
249 249
250 250 def orset(repo, subset, x, y):
251 251 xl = getset(repo, subset, x)
252 252 yl = getset(repo, subset - xl, y)
253 253 return xl + yl
254 254
255 255 def notset(repo, subset, x):
256 256 return subset - getset(repo, subset, x)
257 257
258 258 def listset(repo, subset, a, b):
259 259 raise error.ParseError(_("can't use a list in this context"))
260 260
261 261 def func(repo, subset, a, b):
262 262 if a[0] == 'symbol' and a[1] in symbols:
263 263 return symbols[a[1]](repo, subset, b)
264 264 raise error.ParseError(_("not a function: %s") % a[1])
265 265
266 266 # functions
267 267
268 268 def adds(repo, subset, x):
269 269 """``adds(pattern)``
270 270 Changesets that add a file matching pattern.
271 271
272 272 The pattern without explicit kind like ``glob:`` is expected to be
273 273 relative to the current directory and match against a file or a
274 274 directory.
275 275 """
276 276 # i18n: "adds" is a keyword
277 277 pat = getstring(x, _("adds requires a pattern"))
278 278 return checkstatus(repo, subset, pat, 1)
279 279
280 280 def ancestor(repo, subset, x):
281 281 """``ancestor(*changeset)``
282 282 Greatest common ancestor of the changesets.
283 283
284 284 Accepts 0 or more changesets.
285 285 Will return empty list when passed no args.
286 286 Greatest common ancestor of a single changeset is that changeset.
287 287 """
288 288 # i18n: "ancestor" is a keyword
289 289 l = getlist(x)
290 290 rl = baseset(repo)
291 291 anc = None
292 292
293 293 # (getset(repo, rl, i) for i in l) generates a list of lists
294 294 rev = repo.changelog.rev
295 295 ancestor = repo.changelog.ancestor
296 296 node = repo.changelog.node
297 297 for revs in (getset(repo, rl, i) for i in l):
298 298 for r in revs:
299 299 if anc is None:
300 300 anc = r
301 301 else:
302 302 anc = rev(ancestor(node(anc), node(r)))
303 303
304 304 if anc is not None and anc in subset:
305 305 return baseset([anc])
306 306 return baseset([])
307 307
308 308 def _ancestors(repo, subset, x, followfirst=False):
309 309 args = getset(repo, baseset(repo), x)
310 310 if not args:
311 311 return baseset([])
312 312 s = set(_revancestors(repo, args, followfirst)) | set(args)
313 313 return baseset([r for r in subset if r in s])
314 314
315 315 def ancestors(repo, subset, x):
316 316 """``ancestors(set)``
317 317 Changesets that are ancestors of a changeset in set.
318 318 """
319 319 return _ancestors(repo, subset, x)
320 320
321 321 def _firstancestors(repo, subset, x):
322 322 # ``_firstancestors(set)``
323 323 # Like ``ancestors(set)`` but follows only the first parents.
324 324 return _ancestors(repo, subset, x, followfirst=True)
325 325
326 326 def ancestorspec(repo, subset, x, n):
327 327 """``set~n``
328 328 Changesets that are the Nth ancestor (first parents only) of a changeset
329 329 in set.
330 330 """
331 331 try:
332 332 n = int(n[1])
333 333 except (TypeError, ValueError):
334 334 raise error.ParseError(_("~ expects a number"))
335 335 ps = set()
336 336 cl = repo.changelog
337 337 for r in getset(repo, baseset(cl), x):
338 338 for i in range(n):
339 339 r = cl.parentrevs(r)[0]
340 340 ps.add(r)
341 341 return baseset([r for r in subset if r in ps])
342 342
343 343 def author(repo, subset, x):
344 344 """``author(string)``
345 345 Alias for ``user(string)``.
346 346 """
347 347 # i18n: "author" is a keyword
348 348 n = encoding.lower(getstring(x, _("author requires a string")))
349 349 kind, pattern, matcher = _substringmatcher(n)
350 350 return lazyset(subset, lambda x: matcher(encoding.lower(repo[x].user())))
351 351
352 352 def bisect(repo, subset, x):
353 353 """``bisect(string)``
354 354 Changesets marked in the specified bisect status:
355 355
356 356 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
357 357 - ``goods``, ``bads`` : csets topologically good/bad
358 358 - ``range`` : csets taking part in the bisection
359 359 - ``pruned`` : csets that are goods, bads or skipped
360 360 - ``untested`` : csets whose fate is yet unknown
361 361 - ``ignored`` : csets ignored due to DAG topology
362 362 - ``current`` : the cset currently being bisected
363 363 """
364 364 # i18n: "bisect" is a keyword
365 365 status = getstring(x, _("bisect requires a string")).lower()
366 366 state = set(hbisect.get(repo, status))
367 367 return baseset([r for r in subset if r in state])
368 368
369 369 # Backward-compatibility
370 370 # - no help entry so that we do not advertise it any more
371 371 def bisected(repo, subset, x):
372 372 return bisect(repo, subset, x)
373 373
374 374 def bookmark(repo, subset, x):
375 375 """``bookmark([name])``
376 376 The named bookmark or all bookmarks.
377 377
378 378 If `name` starts with `re:`, the remainder of the name is treated as
379 379 a regular expression. To match a bookmark that actually starts with `re:`,
380 380 use the prefix `literal:`.
381 381 """
382 382 # i18n: "bookmark" is a keyword
383 383 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
384 384 if args:
385 385 bm = getstring(args[0],
386 386 # i18n: "bookmark" is a keyword
387 387 _('the argument to bookmark must be a string'))
388 388 kind, pattern, matcher = _stringmatcher(bm)
389 389 if kind == 'literal':
390 390 bmrev = repo._bookmarks.get(bm, None)
391 391 if not bmrev:
392 392 raise util.Abort(_("bookmark '%s' does not exist") % bm)
393 393 bmrev = repo[bmrev].rev()
394 394 return lazyset(subset, lambda r: r == bmrev)
395 395 else:
396 396 matchrevs = set()
397 397 for name, bmrev in repo._bookmarks.iteritems():
398 398 if matcher(name):
399 399 matchrevs.add(bmrev)
400 400 if not matchrevs:
401 401 raise util.Abort(_("no bookmarks exist that match '%s'")
402 402 % pattern)
403 403 bmrevs = set()
404 404 for bmrev in matchrevs:
405 405 bmrevs.add(repo[bmrev].rev())
406 406 return subset & bmrevs
407 407
408 408 bms = set([repo[r].rev()
409 409 for r in repo._bookmarks.values()])
410 410 return lazyset(subset, lambda r: r in bms)
411 411
412 412 def branch(repo, subset, x):
413 413 """``branch(string or set)``
414 414 All changesets belonging to the given branch or the branches of the given
415 415 changesets.
416 416
417 417 If `string` starts with `re:`, the remainder of the name is treated as
418 418 a regular expression. To match a branch that actually starts with `re:`,
419 419 use the prefix `literal:`.
420 420 """
421 421 try:
422 422 b = getstring(x, '')
423 423 except error.ParseError:
424 424 # not a string, but another revspec, e.g. tip()
425 425 pass
426 426 else:
427 427 kind, pattern, matcher = _stringmatcher(b)
428 428 if kind == 'literal':
429 429 # note: falls through to the revspec case if no branch with
430 430 # this name exists
431 431 if pattern in repo.branchmap():
432 432 return lazyset(subset, lambda r: matcher(repo[r].branch()))
433 433 else:
434 434 return lazyset(subset, lambda r: matcher(repo[r].branch()))
435 435
436 436 s = getset(repo, baseset(repo), x)
437 437 b = set()
438 438 for r in s:
439 439 b.add(repo[r].branch())
440 440 s = s.set()
441 441 return lazyset(subset, lambda r: r in s or repo[r].branch() in b)
442 442
443 443 def bumped(repo, subset, x):
444 444 """``bumped()``
445 445 Mutable changesets marked as successors of public changesets.
446 446
447 447 Only non-public and non-obsolete changesets can be `bumped`.
448 448 """
449 449 # i18n: "bumped" is a keyword
450 450 getargs(x, 0, 0, _("bumped takes no arguments"))
451 451 bumped = obsmod.getrevs(repo, 'bumped')
452 452 return subset & bumped
453 453
454 454 def bundle(repo, subset, x):
455 455 """``bundle()``
456 456 Changesets in the bundle.
457 457
458 458 Bundle must be specified by the -R option."""
459 459
460 460 try:
461 461 bundlerevs = repo.changelog.bundlerevs
462 462 except AttributeError:
463 463 raise util.Abort(_("no bundle provided - specify with -R"))
464 464 return subset & bundlerevs
465 465
466 466 def checkstatus(repo, subset, pat, field):
467 467 hasset = matchmod.patkind(pat) == 'set'
468 468
469 469 def matches(x):
470 470 m = None
471 471 fname = None
472 472 c = repo[x]
473 473 if not m or hasset:
474 474 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
475 475 if not m.anypats() and len(m.files()) == 1:
476 476 fname = m.files()[0]
477 477 if fname is not None:
478 478 if fname not in c.files():
479 479 return False
480 480 else:
481 481 for f in c.files():
482 482 if m(f):
483 483 break
484 484 else:
485 485 return False
486 486 files = repo.status(c.p1().node(), c.node())[field]
487 487 if fname is not None:
488 488 if fname in files:
489 489 return True
490 490 else:
491 491 for f in files:
492 492 if m(f):
493 493 return True
494 494
495 495 return lazyset(subset, matches)
496 496
497 497 def _children(repo, narrow, parentset):
498 498 cs = set()
499 499 if not parentset:
500 500 return baseset(cs)
501 501 pr = repo.changelog.parentrevs
502 502 minrev = min(parentset)
503 503 for r in narrow:
504 504 if r <= minrev:
505 505 continue
506 506 for p in pr(r):
507 507 if p in parentset:
508 508 cs.add(r)
509 509 return baseset(cs)
510 510
511 511 def children(repo, subset, x):
512 512 """``children(set)``
513 513 Child changesets of changesets in set.
514 514 """
515 515 s = getset(repo, baseset(repo), x).set()
516 516 cs = _children(repo, subset, s)
517 517 return subset & cs
518 518
519 519 def closed(repo, subset, x):
520 520 """``closed()``
521 521 Changeset is closed.
522 522 """
523 523 # i18n: "closed" is a keyword
524 524 getargs(x, 0, 0, _("closed takes no arguments"))
525 525 return lazyset(subset, lambda r: repo[r].closesbranch())
526 526
527 527 def contains(repo, subset, x):
528 528 """``contains(pattern)``
529 529 Revision contains a file matching pattern. See :hg:`help patterns`
530 530 for information about file patterns.
531 531
532 532 The pattern without explicit kind like ``glob:`` is expected to be
533 533 relative to the current directory and match against a file exactly
534 534 for efficiency.
535 535 """
536 536 # i18n: "contains" is a keyword
537 537 pat = getstring(x, _("contains requires a pattern"))
538 538
539 539 def matches(x):
540 540 if not matchmod.patkind(pat):
541 541 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
542 542 if pats in repo[x]:
543 543 return True
544 544 else:
545 545 c = repo[x]
546 546 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
547 547 for f in c.manifest():
548 548 if m(f):
549 549 return True
550 550 return False
551 551
552 552 return lazyset(subset, matches)
553 553
554 554 def converted(repo, subset, x):
555 555 """``converted([id])``
556 556 Changesets converted from the given identifier in the old repository if
557 557 present, or all converted changesets if no identifier is specified.
558 558 """
559 559
560 560 # There is exactly no chance of resolving the revision, so do a simple
561 561 # string compare and hope for the best
562 562
563 563 rev = None
564 564 # i18n: "converted" is a keyword
565 565 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
566 566 if l:
567 567 # i18n: "converted" is a keyword
568 568 rev = getstring(l[0], _('converted requires a revision'))
569 569
570 570 def _matchvalue(r):
571 571 source = repo[r].extra().get('convert_revision', None)
572 572 return source is not None and (rev is None or source.startswith(rev))
573 573
574 574 return lazyset(subset, lambda r: _matchvalue(r))
575 575
576 576 def date(repo, subset, x):
577 577 """``date(interval)``
578 578 Changesets within the interval, see :hg:`help dates`.
579 579 """
580 580 # i18n: "date" is a keyword
581 581 ds = getstring(x, _("date requires a string"))
582 582 dm = util.matchdate(ds)
583 583 return lazyset(subset, lambda x: dm(repo[x].date()[0]))
584 584
585 585 def desc(repo, subset, x):
586 586 """``desc(string)``
587 587 Search commit message for string. The match is case-insensitive.
588 588 """
589 589 # i18n: "desc" is a keyword
590 590 ds = encoding.lower(getstring(x, _("desc requires a string")))
591 591
592 592 def matches(x):
593 593 c = repo[x]
594 594 return ds in encoding.lower(c.description())
595 595
596 596 return lazyset(subset, matches)
597 597
598 598 def _descendants(repo, subset, x, followfirst=False):
599 599 args = getset(repo, baseset(repo), x)
600 600 if not args:
601 601 return baseset([])
602 602 s = set(_revdescendants(repo, args, followfirst)) | set(args)
603 603 return baseset([r for r in subset if r in s])
604 604
605 605 def descendants(repo, subset, x):
606 606 """``descendants(set)``
607 607 Changesets which are descendants of changesets in set.
608 608 """
609 609 return _descendants(repo, subset, x)
610 610
611 611 def _firstdescendants(repo, subset, x):
612 612 # ``_firstdescendants(set)``
613 613 # Like ``descendants(set)`` but follows only the first parents.
614 614 return _descendants(repo, subset, x, followfirst=True)
615 615
616 616 def destination(repo, subset, x):
617 617 """``destination([set])``
618 618 Changesets that were created by a graft, transplant or rebase operation,
619 619 with the given revisions specified as the source. Omitting the optional set
620 620 is the same as passing all().
621 621 """
622 622 if x is not None:
623 623 args = getset(repo, baseset(repo), x).set()
624 624 else:
625 625 args = getall(repo, baseset(repo), x).set()
626 626
627 627 dests = set()
628 628
629 629 # subset contains all of the possible destinations that can be returned, so
630 630 # iterate over them and see if their source(s) were provided in the args.
631 631 # Even if the immediate src of r is not in the args, src's source (or
632 632 # further back) may be. Scanning back further than the immediate src allows
633 633 # transitive transplants and rebases to yield the same results as transitive
634 634 # grafts.
635 635 for r in subset:
636 636 src = _getrevsource(repo, r)
637 637 lineage = None
638 638
639 639 while src is not None:
640 640 if lineage is None:
641 641 lineage = list()
642 642
643 643 lineage.append(r)
644 644
645 645 # The visited lineage is a match if the current source is in the arg
646 646 # set. Since every candidate dest is visited by way of iterating
647 647 # subset, any dests further back in the lineage will be tested by a
648 648 # different iteration over subset. Likewise, if the src was already
649 649 # selected, the current lineage can be selected without going back
650 650 # further.
651 651 if src in args or src in dests:
652 652 dests.update(lineage)
653 653 break
654 654
655 655 r = src
656 656 src = _getrevsource(repo, r)
657 657
658 658 return baseset([r for r in subset if r in dests])
659 659
660 660 def divergent(repo, subset, x):
661 661 """``divergent()``
662 662 Final successors of changesets with an alternative set of final successors.
663 663 """
664 664 # i18n: "divergent" is a keyword
665 665 getargs(x, 0, 0, _("divergent takes no arguments"))
666 666 divergent = obsmod.getrevs(repo, 'divergent')
667 667 return baseset([r for r in subset if r in divergent])
668 668
669 669 def draft(repo, subset, x):
670 670 """``draft()``
671 671 Changeset in draft phase."""
672 672 # i18n: "draft" is a keyword
673 673 getargs(x, 0, 0, _("draft takes no arguments"))
674 674 pc = repo._phasecache
675 675 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.draft)
676 676
677 677 def extinct(repo, subset, x):
678 678 """``extinct()``
679 679 Obsolete changesets with obsolete descendants only.
680 680 """
681 681 # i18n: "extinct" is a keyword
682 682 getargs(x, 0, 0, _("extinct takes no arguments"))
683 683 extincts = obsmod.getrevs(repo, 'extinct')
684 684 return subset & extincts
685 685
686 686 def extra(repo, subset, x):
687 687 """``extra(label, [value])``
688 688 Changesets with the given label in the extra metadata, with the given
689 689 optional value.
690 690
691 691 If `value` starts with `re:`, the remainder of the value is treated as
692 692 a regular expression. To match a value that actually starts with `re:`,
693 693 use the prefix `literal:`.
694 694 """
695 695
696 696 # i18n: "extra" is a keyword
697 697 l = getargs(x, 1, 2, _('extra takes at least 1 and at most 2 arguments'))
698 698 # i18n: "extra" is a keyword
699 699 label = getstring(l[0], _('first argument to extra must be a string'))
700 700 value = None
701 701
702 702 if len(l) > 1:
703 703 # i18n: "extra" is a keyword
704 704 value = getstring(l[1], _('second argument to extra must be a string'))
705 705 kind, value, matcher = _stringmatcher(value)
706 706
707 707 def _matchvalue(r):
708 708 extra = repo[r].extra()
709 709 return label in extra and (value is None or matcher(extra[label]))
710 710
711 711 return lazyset(subset, lambda r: _matchvalue(r))
712 712
713 713 def filelog(repo, subset, x):
714 714 """``filelog(pattern)``
715 715 Changesets connected to the specified filelog.
716 716
717 717 For performance reasons, ``filelog()`` does not show every changeset
718 718 that affects the requested file(s). See :hg:`help log` for details. For
719 719 a slower, more accurate result, use ``file()``.
720 720
721 721 The pattern without explicit kind like ``glob:`` is expected to be
722 722 relative to the current directory and match against a file exactly
723 723 for efficiency.
724 724 """
725 725
726 726 # i18n: "filelog" is a keyword
727 727 pat = getstring(x, _("filelog requires a pattern"))
728 728 s = set()
729 729
730 730 if not matchmod.patkind(pat):
731 731 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
732 732 fl = repo.file(f)
733 733 for fr in fl:
734 734 s.add(fl.linkrev(fr))
735 735 else:
736 736 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
737 737 for f in repo[None]:
738 738 if m(f):
739 739 fl = repo.file(f)
740 740 for fr in fl:
741 741 s.add(fl.linkrev(fr))
742 742
743 743 return baseset([r for r in subset if r in s])
744 744
745 745 def first(repo, subset, x):
746 746 """``first(set, [n])``
747 747 An alias for limit().
748 748 """
749 749 return limit(repo, subset, x)
750 750
751 751 def _follow(repo, subset, x, name, followfirst=False):
752 752 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
753 753 c = repo['.']
754 754 if l:
755 755 x = getstring(l[0], _("%s expected a filename") % name)
756 756 if x in c:
757 757 cx = c[x]
758 758 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
759 759 # include the revision responsible for the most recent version
760 760 s.add(cx.linkrev())
761 761 else:
762 762 return baseset([])
763 763 else:
764 764 s = set(_revancestors(repo, [c.rev()], followfirst)) | set([c.rev()])
765 765
766 766 return baseset([r for r in subset if r in s])
767 767
768 768 def follow(repo, subset, x):
769 769 """``follow([file])``
770 770 An alias for ``::.`` (ancestors of the working copy's first parent).
771 771 If a filename is specified, the history of the given file is followed,
772 772 including copies.
773 773 """
774 774 return _follow(repo, subset, x, 'follow')
775 775
776 776 def _followfirst(repo, subset, x):
777 777 # ``followfirst([file])``
778 778 # Like ``follow([file])`` but follows only the first parent of
779 779 # every revision or file revision.
780 780 return _follow(repo, subset, x, '_followfirst', followfirst=True)
781 781
782 782 def getall(repo, subset, x):
783 783 """``all()``
784 784 All changesets, the same as ``0:tip``.
785 785 """
786 786 # i18n: "all" is a keyword
787 787 getargs(x, 0, 0, _("all takes no arguments"))
788 788 return subset
789 789
790 790 def grep(repo, subset, x):
791 791 """``grep(regex)``
792 792 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
793 793 to ensure special escape characters are handled correctly. Unlike
794 794 ``keyword(string)``, the match is case-sensitive.
795 795 """
796 796 try:
797 797 # i18n: "grep" is a keyword
798 798 gr = re.compile(getstring(x, _("grep requires a string")))
799 799 except re.error, e:
800 800 raise error.ParseError(_('invalid match pattern: %s') % e)
801 801
802 802 def matches(x):
803 803 c = repo[x]
804 804 for e in c.files() + [c.user(), c.description()]:
805 805 if gr.search(e):
806 806 return True
807 807 return False
808 808
809 809 return lazyset(subset, matches)
810 810
811 811 def _matchfiles(repo, subset, x):
812 812 # _matchfiles takes a revset list of prefixed arguments:
813 813 #
814 814 # [p:foo, i:bar, x:baz]
815 815 #
816 816 # builds a match object from them and filters subset. Allowed
817 817 # prefixes are 'p:' for regular patterns, 'i:' for include
818 818 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
819 819 # a revision identifier, or the empty string to reference the
820 820 # working directory, from which the match object is
821 821 # initialized. Use 'd:' to set the default matching mode, default
822 822 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
823 823
824 824 # i18n: "_matchfiles" is a keyword
825 825 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
826 826 pats, inc, exc = [], [], []
827 827 hasset = False
828 828 rev, default = None, None
829 829 for arg in l:
830 830 # i18n: "_matchfiles" is a keyword
831 831 s = getstring(arg, _("_matchfiles requires string arguments"))
832 832 prefix, value = s[:2], s[2:]
833 833 if prefix == 'p:':
834 834 pats.append(value)
835 835 elif prefix == 'i:':
836 836 inc.append(value)
837 837 elif prefix == 'x:':
838 838 exc.append(value)
839 839 elif prefix == 'r:':
840 840 if rev is not None:
841 841 # i18n: "_matchfiles" is a keyword
842 842 raise error.ParseError(_('_matchfiles expected at most one '
843 843 'revision'))
844 844 rev = value
845 845 elif prefix == 'd:':
846 846 if default is not None:
847 847 # i18n: "_matchfiles" is a keyword
848 848 raise error.ParseError(_('_matchfiles expected at most one '
849 849 'default mode'))
850 850 default = value
851 851 else:
852 852 # i18n: "_matchfiles" is a keyword
853 853 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
854 854 if not hasset and matchmod.patkind(value) == 'set':
855 855 hasset = True
856 856 if not default:
857 857 default = 'glob'
858 858
859 859 def matches(x):
860 860 m = None
861 861 c = repo[x]
862 862 if not m or (hasset and rev is None):
863 863 ctx = c
864 864 if rev is not None:
865 865 ctx = repo[rev or None]
866 866 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
867 867 exclude=exc, ctx=ctx, default=default)
868 868 for f in c.files():
869 869 if m(f):
870 870 return True
871 871 return False
872 872
873 873 return lazyset(subset, matches)
874 874
875 875 def hasfile(repo, subset, x):
876 876 """``file(pattern)``
877 877 Changesets affecting files matched by pattern.
878 878
879 879 For a faster but less accurate result, consider using ``filelog()``
880 880 instead.
881 881
882 882 This predicate uses ``glob:`` as the default kind of pattern.
883 883 """
884 884 # i18n: "file" is a keyword
885 885 pat = getstring(x, _("file requires a pattern"))
886 886 return _matchfiles(repo, subset, ('string', 'p:' + pat))
887 887
888 888 def head(repo, subset, x):
889 889 """``head()``
890 890 Changeset is a named branch head.
891 891 """
892 892 # i18n: "head" is a keyword
893 893 getargs(x, 0, 0, _("head takes no arguments"))
894 894 hs = set()
895 895 for b, ls in repo.branchmap().iteritems():
896 896 hs.update(repo[h].rev() for h in ls)
897 897 return baseset([r for r in subset if r in hs])
898 898
899 899 def heads(repo, subset, x):
900 900 """``heads(set)``
901 901 Members of set with no children in set.
902 902 """
903 903 s = getset(repo, subset, x)
904 904 ps = parents(repo, subset, x)
905 905 return s - ps
906 906
907 907 def hidden(repo, subset, x):
908 908 """``hidden()``
909 909 Hidden changesets.
910 910 """
911 911 # i18n: "hidden" is a keyword
912 912 getargs(x, 0, 0, _("hidden takes no arguments"))
913 913 hiddenrevs = repoview.filterrevs(repo, 'visible')
914 914 return subset & hiddenrevs
915 915
916 916 def keyword(repo, subset, x):
917 917 """``keyword(string)``
918 918 Search commit message, user name, and names of changed files for
919 919 string. The match is case-insensitive.
920 920 """
921 921 # i18n: "keyword" is a keyword
922 922 kw = encoding.lower(getstring(x, _("keyword requires a string")))
923 923
924 924 def matches(r):
925 925 c = repo[r]
926 926 return util.any(kw in encoding.lower(t) for t in c.files() + [c.user(),
927 927 c.description()])
928 928
929 929 return lazyset(subset, matches)
930 930
931 931 def limit(repo, subset, x):
932 932 """``limit(set, [n])``
933 933 First n members of set, defaulting to 1.
934 934 """
935 935 # i18n: "limit" is a keyword
936 936 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
937 937 try:
938 938 lim = 1
939 939 if len(l) == 2:
940 940 # i18n: "limit" is a keyword
941 941 lim = int(getstring(l[1], _("limit requires a number")))
942 942 except (TypeError, ValueError):
943 943 # i18n: "limit" is a keyword
944 944 raise error.ParseError(_("limit expects a number"))
945 945 ss = subset.set()
946 946 os = getset(repo, baseset(repo), l[0])
947 947 bs = baseset([])
948 948 it = iter(os)
949 949 for x in xrange(lim):
950 950 try:
951 951 y = it.next()
952 952 if y in ss:
953 953 bs.append(y)
954 954 except (StopIteration):
955 955 break
956 956 return bs
957 957
958 958 def last(repo, subset, x):
959 959 """``last(set, [n])``
960 960 Last n members of set, defaulting to 1.
961 961 """
962 962 # i18n: "last" is a keyword
963 963 l = getargs(x, 1, 2, _("last requires one or two arguments"))
964 964 try:
965 965 lim = 1
966 966 if len(l) == 2:
967 967 # i18n: "last" is a keyword
968 968 lim = int(getstring(l[1], _("last requires a number")))
969 969 except (TypeError, ValueError):
970 970 # i18n: "last" is a keyword
971 971 raise error.ParseError(_("last expects a number"))
972 972 ss = subset.set()
973 973 os = getset(repo, baseset(repo), l[0])[-lim:]
974 974 return baseset([r for r in os if r in ss])
975 975
976 976 def maxrev(repo, subset, x):
977 977 """``max(set)``
978 978 Changeset with highest revision number in set.
979 979 """
980 980 os = getset(repo, baseset(repo), x)
981 981 if os:
982 982 m = max(os)
983 983 if m in subset:
984 984 return baseset([m])
985 985 return baseset([])
986 986
987 987 def merge(repo, subset, x):
988 988 """``merge()``
989 989 Changeset is a merge changeset.
990 990 """
991 991 # i18n: "merge" is a keyword
992 992 getargs(x, 0, 0, _("merge takes no arguments"))
993 993 cl = repo.changelog
994 994 return lazyset(subset, lambda r: cl.parentrevs(r)[1] != -1)
995 995
996 996 def branchpoint(repo, subset, x):
997 997 """``branchpoint()``
998 998 Changesets with more than one child.
999 999 """
1000 1000 # i18n: "branchpoint" is a keyword
1001 1001 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1002 1002 cl = repo.changelog
1003 1003 if not subset:
1004 1004 return baseset([])
1005 1005 baserev = min(subset)
1006 1006 parentscount = [0]*(len(repo) - baserev)
1007 1007 for r in cl.revs(start=baserev + 1):
1008 1008 for p in cl.parentrevs(r):
1009 1009 if p >= baserev:
1010 1010 parentscount[p - baserev] += 1
1011 1011 return baseset([r for r in subset if (parentscount[r - baserev] > 1)])
1012 1012
1013 1013 def minrev(repo, subset, x):
1014 1014 """``min(set)``
1015 1015 Changeset with lowest revision number in set.
1016 1016 """
1017 1017 os = getset(repo, baseset(repo), x)
1018 1018 if os:
1019 1019 m = min(os)
1020 1020 if m in subset:
1021 1021 return baseset([m])
1022 1022 return baseset([])
1023 1023
1024 1024 def _missingancestors(repo, subset, x):
1025 1025 # i18n: "_missingancestors" is a keyword
1026 1026 revs, bases = getargs(x, 2, 2,
1027 1027 _("_missingancestors requires two arguments"))
1028 1028 rs = baseset(repo)
1029 1029 revs = getset(repo, rs, revs)
1030 1030 bases = getset(repo, rs, bases)
1031 1031 missing = set(repo.changelog.findmissingrevs(bases, revs))
1032 1032 return baseset([r for r in subset if r in missing])
1033 1033
1034 1034 def modifies(repo, subset, x):
1035 1035 """``modifies(pattern)``
1036 1036 Changesets modifying files matched by pattern.
1037 1037
1038 1038 The pattern without explicit kind like ``glob:`` is expected to be
1039 1039 relative to the current directory and match against a file or a
1040 1040 directory.
1041 1041 """
1042 1042 # i18n: "modifies" is a keyword
1043 1043 pat = getstring(x, _("modifies requires a pattern"))
1044 1044 return checkstatus(repo, subset, pat, 0)
1045 1045
1046 1046 def node_(repo, subset, x):
1047 1047 """``id(string)``
1048 1048 Revision non-ambiguously specified by the given hex string prefix.
1049 1049 """
1050 1050 # i18n: "id" is a keyword
1051 1051 l = getargs(x, 1, 1, _("id requires one argument"))
1052 1052 # i18n: "id" is a keyword
1053 1053 n = getstring(l[0], _("id requires a string"))
1054 1054 if len(n) == 40:
1055 1055 rn = repo[n].rev()
1056 1056 else:
1057 1057 rn = None
1058 1058 pm = repo.changelog._partialmatch(n)
1059 1059 if pm is not None:
1060 1060 rn = repo.changelog.rev(pm)
1061 1061
1062 1062 return baseset([r for r in subset if r == rn])
1063 1063
1064 1064 def obsolete(repo, subset, x):
1065 1065 """``obsolete()``
1066 1066 Mutable changeset with a newer version."""
1067 1067 # i18n: "obsolete" is a keyword
1068 1068 getargs(x, 0, 0, _("obsolete takes no arguments"))
1069 1069 obsoletes = obsmod.getrevs(repo, 'obsolete')
1070 1070 return subset & obsoletes
1071 1071
1072 1072 def origin(repo, subset, x):
1073 1073 """``origin([set])``
1074 1074 Changesets that were specified as a source for the grafts, transplants or
1075 1075 rebases that created the given revisions. Omitting the optional set is the
1076 1076 same as passing all(). If a changeset created by these operations is itself
1077 1077 specified as a source for one of these operations, only the source changeset
1078 1078 for the first operation is selected.
1079 1079 """
1080 1080 if x is not None:
1081 1081 args = getset(repo, baseset(repo), x).set()
1082 1082 else:
1083 1083 args = getall(repo, baseset(repo), x).set()
1084 1084
1085 1085 def _firstsrc(rev):
1086 1086 src = _getrevsource(repo, rev)
1087 1087 if src is None:
1088 1088 return None
1089 1089
1090 1090 while True:
1091 1091 prev = _getrevsource(repo, src)
1092 1092
1093 1093 if prev is None:
1094 1094 return src
1095 1095 src = prev
1096 1096
1097 1097 o = set([_firstsrc(r) for r in args])
1098 1098 return baseset([r for r in subset if r in o])
1099 1099
1100 1100 def outgoing(repo, subset, x):
1101 1101 """``outgoing([path])``
1102 1102 Changesets not found in the specified destination repository, or the
1103 1103 default push location.
1104 1104 """
1105 1105 import hg # avoid start-up nasties
1106 1106 # i18n: "outgoing" is a keyword
1107 1107 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1108 1108 # i18n: "outgoing" is a keyword
1109 1109 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1110 1110 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1111 1111 dest, branches = hg.parseurl(dest)
1112 1112 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1113 1113 if revs:
1114 1114 revs = [repo.lookup(rev) for rev in revs]
1115 1115 other = hg.peer(repo, {}, dest)
1116 1116 repo.ui.pushbuffer()
1117 1117 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1118 1118 repo.ui.popbuffer()
1119 1119 cl = repo.changelog
1120 1120 o = set([cl.rev(r) for r in outgoing.missing])
1121 1121 return baseset([r for r in subset if r in o])
1122 1122
1123 1123 def p1(repo, subset, x):
1124 1124 """``p1([set])``
1125 1125 First parent of changesets in set, or the working directory.
1126 1126 """
1127 1127 if x is None:
1128 1128 p = repo[x].p1().rev()
1129 1129 return baseset([r for r in subset if r == p])
1130 1130
1131 1131 ps = set()
1132 1132 cl = repo.changelog
1133 1133 for r in getset(repo, baseset(repo), x):
1134 1134 ps.add(cl.parentrevs(r)[0])
1135 1135 return subset & ps
1136 1136
1137 1137 def p2(repo, subset, x):
1138 1138 """``p2([set])``
1139 1139 Second parent of changesets in set, or the working directory.
1140 1140 """
1141 1141 if x is None:
1142 1142 ps = repo[x].parents()
1143 1143 try:
1144 1144 p = ps[1].rev()
1145 1145 return baseset([r for r in subset if r == p])
1146 1146 except IndexError:
1147 1147 return baseset([])
1148 1148
1149 1149 ps = set()
1150 1150 cl = repo.changelog
1151 1151 for r in getset(repo, baseset(repo), x):
1152 1152 ps.add(cl.parentrevs(r)[1])
1153 1153 return subset & ps
1154 1154
1155 1155 def parents(repo, subset, x):
1156 1156 """``parents([set])``
1157 1157 The set of all parents for all changesets in set, or the working directory.
1158 1158 """
1159 1159 if x is None:
1160 1160 ps = tuple(p.rev() for p in repo[x].parents())
1161 1161 return subset & ps
1162 1162
1163 1163 ps = set()
1164 1164 cl = repo.changelog
1165 1165 for r in getset(repo, baseset(repo), x):
1166 1166 ps.update(cl.parentrevs(r))
1167 1167 return subset & ps
1168 1168
1169 1169 def parentspec(repo, subset, x, n):
1170 1170 """``set^0``
1171 1171 The set.
1172 1172 ``set^1`` (or ``set^``), ``set^2``
1173 1173 First or second parent, respectively, of all changesets in set.
1174 1174 """
1175 1175 try:
1176 1176 n = int(n[1])
1177 1177 if n not in (0, 1, 2):
1178 1178 raise ValueError
1179 1179 except (TypeError, ValueError):
1180 1180 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1181 1181 ps = set()
1182 1182 cl = repo.changelog
1183 1183 for r in getset(repo, baseset(cl), x):
1184 1184 if n == 0:
1185 1185 ps.add(r)
1186 1186 elif n == 1:
1187 1187 ps.add(cl.parentrevs(r)[0])
1188 1188 elif n == 2:
1189 1189 parents = cl.parentrevs(r)
1190 1190 if len(parents) > 1:
1191 1191 ps.add(parents[1])
1192 1192 return subset & ps
1193 1193
1194 1194 def present(repo, subset, x):
1195 1195 """``present(set)``
1196 1196 An empty set, if any revision in set isn't found; otherwise,
1197 1197 all revisions in set.
1198 1198
1199 1199 If any of specified revisions is not present in the local repository,
1200 1200 the query is normally aborted. But this predicate allows the query
1201 1201 to continue even in such cases.
1202 1202 """
1203 1203 try:
1204 1204 return getset(repo, subset, x)
1205 1205 except error.RepoLookupError:
1206 1206 return baseset([])
1207 1207
1208 1208 def public(repo, subset, x):
1209 1209 """``public()``
1210 1210 Changeset in public phase."""
1211 1211 # i18n: "public" is a keyword
1212 1212 getargs(x, 0, 0, _("public takes no arguments"))
1213 1213 pc = repo._phasecache
1214 1214 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.public)
1215 1215
1216 1216 def remote(repo, subset, x):
1217 1217 """``remote([id [,path]])``
1218 1218 Local revision that corresponds to the given identifier in a
1219 1219 remote repository, if present. Here, the '.' identifier is a
1220 1220 synonym for the current local branch.
1221 1221 """
1222 1222
1223 1223 import hg # avoid start-up nasties
1224 1224 # i18n: "remote" is a keyword
1225 1225 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1226 1226
1227 1227 q = '.'
1228 1228 if len(l) > 0:
1229 1229 # i18n: "remote" is a keyword
1230 1230 q = getstring(l[0], _("remote requires a string id"))
1231 1231 if q == '.':
1232 1232 q = repo['.'].branch()
1233 1233
1234 1234 dest = ''
1235 1235 if len(l) > 1:
1236 1236 # i18n: "remote" is a keyword
1237 1237 dest = getstring(l[1], _("remote requires a repository path"))
1238 1238 dest = repo.ui.expandpath(dest or 'default')
1239 1239 dest, branches = hg.parseurl(dest)
1240 1240 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1241 1241 if revs:
1242 1242 revs = [repo.lookup(rev) for rev in revs]
1243 1243 other = hg.peer(repo, {}, dest)
1244 1244 n = other.lookup(q)
1245 1245 if n in repo:
1246 1246 r = repo[n].rev()
1247 1247 if r in subset:
1248 1248 return baseset([r])
1249 1249 return baseset([])
1250 1250
1251 1251 def removes(repo, subset, x):
1252 1252 """``removes(pattern)``
1253 1253 Changesets which remove files matching pattern.
1254 1254
1255 1255 The pattern without explicit kind like ``glob:`` is expected to be
1256 1256 relative to the current directory and match against a file or a
1257 1257 directory.
1258 1258 """
1259 1259 # i18n: "removes" is a keyword
1260 1260 pat = getstring(x, _("removes requires a pattern"))
1261 1261 return checkstatus(repo, subset, pat, 2)
1262 1262
1263 1263 def rev(repo, subset, x):
1264 1264 """``rev(number)``
1265 1265 Revision with the given numeric identifier.
1266 1266 """
1267 1267 # i18n: "rev" is a keyword
1268 1268 l = getargs(x, 1, 1, _("rev requires one argument"))
1269 1269 try:
1270 1270 # i18n: "rev" is a keyword
1271 1271 l = int(getstring(l[0], _("rev requires a number")))
1272 1272 except (TypeError, ValueError):
1273 1273 # i18n: "rev" is a keyword
1274 1274 raise error.ParseError(_("rev expects a number"))
1275 1275 return baseset([r for r in subset if r == l])
1276 1276
1277 1277 def matching(repo, subset, x):
1278 1278 """``matching(revision [, field])``
1279 1279 Changesets in which a given set of fields match the set of fields in the
1280 1280 selected revision or set.
1281 1281
1282 1282 To match more than one field pass the list of fields to match separated
1283 1283 by spaces (e.g. ``author description``).
1284 1284
1285 1285 Valid fields are most regular revision fields and some special fields.
1286 1286
1287 1287 Regular revision fields are ``description``, ``author``, ``branch``,
1288 1288 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1289 1289 and ``diff``.
1290 1290 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1291 1291 contents of the revision. Two revisions matching their ``diff`` will
1292 1292 also match their ``files``.
1293 1293
1294 1294 Special fields are ``summary`` and ``metadata``:
1295 1295 ``summary`` matches the first line of the description.
1296 1296 ``metadata`` is equivalent to matching ``description user date``
1297 1297 (i.e. it matches the main metadata fields).
1298 1298
1299 1299 ``metadata`` is the default field which is used when no fields are
1300 1300 specified. You can match more than one field at a time.
1301 1301 """
1302 1302 # i18n: "matching" is a keyword
1303 1303 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1304 1304
1305 1305 revs = getset(repo, baseset(repo.changelog), l[0])
1306 1306
1307 1307 fieldlist = ['metadata']
1308 1308 if len(l) > 1:
1309 1309 fieldlist = getstring(l[1],
1310 1310 # i18n: "matching" is a keyword
1311 1311 _("matching requires a string "
1312 1312 "as its second argument")).split()
1313 1313
1314 1314 # Make sure that there are no repeated fields,
1315 1315 # expand the 'special' 'metadata' field type
1316 1316 # and check the 'files' whenever we check the 'diff'
1317 1317 fields = []
1318 1318 for field in fieldlist:
1319 1319 if field == 'metadata':
1320 1320 fields += ['user', 'description', 'date']
1321 1321 elif field == 'diff':
1322 1322 # a revision matching the diff must also match the files
1323 1323 # since matching the diff is very costly, make sure to
1324 1324 # also match the files first
1325 1325 fields += ['files', 'diff']
1326 1326 else:
1327 1327 if field == 'author':
1328 1328 field = 'user'
1329 1329 fields.append(field)
1330 1330 fields = set(fields)
1331 1331 if 'summary' in fields and 'description' in fields:
1332 1332 # If a revision matches its description it also matches its summary
1333 1333 fields.discard('summary')
1334 1334
1335 1335 # We may want to match more than one field
1336 1336 # Not all fields take the same amount of time to be matched
1337 1337 # Sort the selected fields in order of increasing matching cost
1338 1338 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1339 1339 'files', 'description', 'substate', 'diff']
1340 1340 def fieldkeyfunc(f):
1341 1341 try:
1342 1342 return fieldorder.index(f)
1343 1343 except ValueError:
1344 1344 # assume an unknown field is very costly
1345 1345 return len(fieldorder)
1346 1346 fields = list(fields)
1347 1347 fields.sort(key=fieldkeyfunc)
1348 1348
1349 1349 # Each field will be matched with its own "getfield" function
1350 1350 # which will be added to the getfieldfuncs array of functions
1351 1351 getfieldfuncs = []
1352 1352 _funcs = {
1353 1353 'user': lambda r: repo[r].user(),
1354 1354 'branch': lambda r: repo[r].branch(),
1355 1355 'date': lambda r: repo[r].date(),
1356 1356 'description': lambda r: repo[r].description(),
1357 1357 'files': lambda r: repo[r].files(),
1358 1358 'parents': lambda r: repo[r].parents(),
1359 1359 'phase': lambda r: repo[r].phase(),
1360 1360 'substate': lambda r: repo[r].substate,
1361 1361 'summary': lambda r: repo[r].description().splitlines()[0],
1362 1362 'diff': lambda r: list(repo[r].diff(git=True),)
1363 1363 }
1364 1364 for info in fields:
1365 1365 getfield = _funcs.get(info, None)
1366 1366 if getfield is None:
1367 1367 raise error.ParseError(
1368 1368 # i18n: "matching" is a keyword
1369 1369 _("unexpected field name passed to matching: %s") % info)
1370 1370 getfieldfuncs.append(getfield)
1371 1371 # convert the getfield array of functions into a "getinfo" function
1372 1372 # which returns an array of field values (or a single value if there
1373 1373 # is only one field to match)
1374 1374 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1375 1375
1376 1376 def matches(x):
1377 1377 for rev in revs:
1378 1378 target = getinfo(rev)
1379 1379 match = True
1380 1380 for n, f in enumerate(getfieldfuncs):
1381 1381 if target[n] != f(x):
1382 1382 match = False
1383 1383 if match:
1384 1384 return True
1385 1385 return False
1386 1386
1387 1387 return lazyset(subset, matches)
1388 1388
1389 1389 def reverse(repo, subset, x):
1390 1390 """``reverse(set)``
1391 1391 Reverse order of set.
1392 1392 """
1393 1393 l = getset(repo, subset, x)
1394 1394 l.reverse()
1395 1395 return l
1396 1396
1397 1397 def roots(repo, subset, x):
1398 1398 """``roots(set)``
1399 1399 Changesets in set with no parent changeset in set.
1400 1400 """
1401 1401 s = getset(repo, baseset(repo.changelog), x).set()
1402 1402 subset = baseset([r for r in subset if r in s])
1403 1403 cs = _children(repo, subset, s)
1404 1404 return subset - cs
1405 1405
1406 1406 def secret(repo, subset, x):
1407 1407 """``secret()``
1408 1408 Changeset in secret phase."""
1409 1409 # i18n: "secret" is a keyword
1410 1410 getargs(x, 0, 0, _("secret takes no arguments"))
1411 1411 pc = repo._phasecache
1412 1412 return lazyset(subset, lambda x: pc.phase(repo, x) == phases.secret)
1413 1413
1414 1414 def sort(repo, subset, x):
1415 1415 """``sort(set[, [-]key...])``
1416 1416 Sort set by keys. The default sort order is ascending, specify a key
1417 1417 as ``-key`` to sort in descending order.
1418 1418
1419 1419 The keys can be:
1420 1420
1421 1421 - ``rev`` for the revision number,
1422 1422 - ``branch`` for the branch name,
1423 1423 - ``desc`` for the commit message (description),
1424 1424 - ``user`` for user name (``author`` can be used as an alias),
1425 1425 - ``date`` for the commit date
1426 1426 """
1427 1427 # i18n: "sort" is a keyword
1428 1428 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1429 1429 keys = "rev"
1430 1430 if len(l) == 2:
1431 1431 # i18n: "sort" is a keyword
1432 1432 keys = getstring(l[1], _("sort spec must be a string"))
1433 1433
1434 1434 s = l[0]
1435 1435 keys = keys.split()
1436 1436 l = []
1437 1437 def invert(s):
1438 1438 return "".join(chr(255 - ord(c)) for c in s)
1439 1439 for r in getset(repo, subset, s):
1440 1440 c = repo[r]
1441 1441 e = []
1442 1442 for k in keys:
1443 1443 if k == 'rev':
1444 1444 e.append(r)
1445 1445 elif k == '-rev':
1446 1446 e.append(-r)
1447 1447 elif k == 'branch':
1448 1448 e.append(c.branch())
1449 1449 elif k == '-branch':
1450 1450 e.append(invert(c.branch()))
1451 1451 elif k == 'desc':
1452 1452 e.append(c.description())
1453 1453 elif k == '-desc':
1454 1454 e.append(invert(c.description()))
1455 1455 elif k in 'user author':
1456 1456 e.append(c.user())
1457 1457 elif k in '-user -author':
1458 1458 e.append(invert(c.user()))
1459 1459 elif k == 'date':
1460 1460 e.append(c.date()[0])
1461 1461 elif k == '-date':
1462 1462 e.append(-c.date()[0])
1463 1463 else:
1464 1464 raise error.ParseError(_("unknown sort key %r") % k)
1465 1465 e.append(r)
1466 1466 l.append(e)
1467 1467 l.sort()
1468 1468 return baseset([e[-1] for e in l])
1469 1469
1470 1470 def _stringmatcher(pattern):
1471 1471 """
1472 1472 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1473 1473 returns the matcher name, pattern, and matcher function.
1474 1474 missing or unknown prefixes are treated as literal matches.
1475 1475
1476 1476 helper for tests:
1477 1477 >>> def test(pattern, *tests):
1478 1478 ... kind, pattern, matcher = _stringmatcher(pattern)
1479 1479 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1480 1480
1481 1481 exact matching (no prefix):
1482 1482 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1483 1483 ('literal', 'abcdefg', [False, False, True])
1484 1484
1485 1485 regex matching ('re:' prefix)
1486 1486 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1487 1487 ('re', 'a.+b', [False, False, True])
1488 1488
1489 1489 force exact matches ('literal:' prefix)
1490 1490 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1491 1491 ('literal', 're:foobar', [False, True])
1492 1492
1493 1493 unknown prefixes are ignored and treated as literals
1494 1494 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1495 1495 ('literal', 'foo:bar', [False, False, True])
1496 1496 """
1497 1497 if pattern.startswith('re:'):
1498 1498 pattern = pattern[3:]
1499 1499 try:
1500 1500 regex = re.compile(pattern)
1501 1501 except re.error, e:
1502 1502 raise error.ParseError(_('invalid regular expression: %s')
1503 1503 % e)
1504 1504 return 're', pattern, regex.search
1505 1505 elif pattern.startswith('literal:'):
1506 1506 pattern = pattern[8:]
1507 1507 return 'literal', pattern, pattern.__eq__
1508 1508
1509 1509 def _substringmatcher(pattern):
1510 1510 kind, pattern, matcher = _stringmatcher(pattern)
1511 1511 if kind == 'literal':
1512 1512 matcher = lambda s: pattern in s
1513 1513 return kind, pattern, matcher
1514 1514
1515 1515 def tag(repo, subset, x):
1516 1516 """``tag([name])``
1517 1517 The specified tag by name, or all tagged revisions if no name is given.
1518 1518 """
1519 1519 # i18n: "tag" is a keyword
1520 1520 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1521 1521 cl = repo.changelog
1522 1522 if args:
1523 1523 pattern = getstring(args[0],
1524 1524 # i18n: "tag" is a keyword
1525 1525 _('the argument to tag must be a string'))
1526 1526 kind, pattern, matcher = _stringmatcher(pattern)
1527 1527 if kind == 'literal':
1528 1528 # avoid resolving all tags
1529 1529 tn = repo._tagscache.tags.get(pattern, None)
1530 1530 if tn is None:
1531 1531 raise util.Abort(_("tag '%s' does not exist") % pattern)
1532 1532 s = set([repo[tn].rev()])
1533 1533 else:
1534 1534 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1535 1535 else:
1536 1536 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1537 1537 return subset & s
1538 1538
1539 1539 def tagged(repo, subset, x):
1540 1540 return tag(repo, subset, x)
1541 1541
1542 1542 def unstable(repo, subset, x):
1543 1543 """``unstable()``
1544 1544 Non-obsolete changesets with obsolete ancestors.
1545 1545 """
1546 1546 # i18n: "unstable" is a keyword
1547 1547 getargs(x, 0, 0, _("unstable takes no arguments"))
1548 1548 unstables = obsmod.getrevs(repo, 'unstable')
1549 1549 return subset & unstables
1550 1550
1551 1551
1552 1552 def user(repo, subset, x):
1553 1553 """``user(string)``
1554 1554 User name contains string. The match is case-insensitive.
1555 1555
1556 1556 If `string` starts with `re:`, the remainder of the string is treated as
1557 1557 a regular expression. To match a user that actually contains `re:`, use
1558 1558 the prefix `literal:`.
1559 1559 """
1560 1560 return author(repo, subset, x)
1561 1561
1562 1562 # for internal use
1563 1563 def _list(repo, subset, x):
1564 1564 s = getstring(x, "internal error")
1565 1565 if not s:
1566 1566 return baseset([])
1567 1567 ls = [repo[r].rev() for r in s.split('\0')]
1568 1568 s = subset.set()
1569 1569 return baseset([r for r in ls if r in s])
1570 1570
1571 1571 symbols = {
1572 1572 "adds": adds,
1573 1573 "all": getall,
1574 1574 "ancestor": ancestor,
1575 1575 "ancestors": ancestors,
1576 1576 "_firstancestors": _firstancestors,
1577 1577 "author": author,
1578 1578 "bisect": bisect,
1579 1579 "bisected": bisected,
1580 1580 "bookmark": bookmark,
1581 1581 "branch": branch,
1582 1582 "branchpoint": branchpoint,
1583 1583 "bumped": bumped,
1584 1584 "bundle": bundle,
1585 1585 "children": children,
1586 1586 "closed": closed,
1587 1587 "contains": contains,
1588 1588 "converted": converted,
1589 1589 "date": date,
1590 1590 "desc": desc,
1591 1591 "descendants": descendants,
1592 1592 "_firstdescendants": _firstdescendants,
1593 1593 "destination": destination,
1594 1594 "divergent": divergent,
1595 1595 "draft": draft,
1596 1596 "extinct": extinct,
1597 1597 "extra": extra,
1598 1598 "file": hasfile,
1599 1599 "filelog": filelog,
1600 1600 "first": first,
1601 1601 "follow": follow,
1602 1602 "_followfirst": _followfirst,
1603 1603 "grep": grep,
1604 1604 "head": head,
1605 1605 "heads": heads,
1606 1606 "hidden": hidden,
1607 1607 "id": node_,
1608 1608 "keyword": keyword,
1609 1609 "last": last,
1610 1610 "limit": limit,
1611 1611 "_matchfiles": _matchfiles,
1612 1612 "max": maxrev,
1613 1613 "merge": merge,
1614 1614 "min": minrev,
1615 1615 "_missingancestors": _missingancestors,
1616 1616 "modifies": modifies,
1617 1617 "obsolete": obsolete,
1618 1618 "origin": origin,
1619 1619 "outgoing": outgoing,
1620 1620 "p1": p1,
1621 1621 "p2": p2,
1622 1622 "parents": parents,
1623 1623 "present": present,
1624 1624 "public": public,
1625 1625 "remote": remote,
1626 1626 "removes": removes,
1627 1627 "rev": rev,
1628 1628 "reverse": reverse,
1629 1629 "roots": roots,
1630 1630 "sort": sort,
1631 1631 "secret": secret,
1632 1632 "matching": matching,
1633 1633 "tag": tag,
1634 1634 "tagged": tagged,
1635 1635 "user": user,
1636 1636 "unstable": unstable,
1637 1637 "_list": _list,
1638 1638 }
1639 1639
1640 1640 # symbols which can't be used for a DoS attack for any given input
1641 1641 # (e.g. those which accept regexes as plain strings shouldn't be included)
1642 1642 # functions that just return a lot of changesets (like all) don't count here
1643 1643 safesymbols = set([
1644 1644 "adds",
1645 1645 "all",
1646 1646 "ancestor",
1647 1647 "ancestors",
1648 1648 "_firstancestors",
1649 1649 "author",
1650 1650 "bisect",
1651 1651 "bisected",
1652 1652 "bookmark",
1653 1653 "branch",
1654 1654 "branchpoint",
1655 1655 "bumped",
1656 1656 "bundle",
1657 1657 "children",
1658 1658 "closed",
1659 1659 "converted",
1660 1660 "date",
1661 1661 "desc",
1662 1662 "descendants",
1663 1663 "_firstdescendants",
1664 1664 "destination",
1665 1665 "divergent",
1666 1666 "draft",
1667 1667 "extinct",
1668 1668 "extra",
1669 1669 "file",
1670 1670 "filelog",
1671 1671 "first",
1672 1672 "follow",
1673 1673 "_followfirst",
1674 1674 "head",
1675 1675 "heads",
1676 1676 "hidden",
1677 1677 "id",
1678 1678 "keyword",
1679 1679 "last",
1680 1680 "limit",
1681 1681 "_matchfiles",
1682 1682 "max",
1683 1683 "merge",
1684 1684 "min",
1685 1685 "_missingancestors",
1686 1686 "modifies",
1687 1687 "obsolete",
1688 1688 "origin",
1689 1689 "outgoing",
1690 1690 "p1",
1691 1691 "p2",
1692 1692 "parents",
1693 1693 "present",
1694 1694 "public",
1695 1695 "remote",
1696 1696 "removes",
1697 1697 "rev",
1698 1698 "reverse",
1699 1699 "roots",
1700 1700 "sort",
1701 1701 "secret",
1702 1702 "matching",
1703 1703 "tag",
1704 1704 "tagged",
1705 1705 "user",
1706 1706 "unstable",
1707 1707 "_list",
1708 1708 ])
1709 1709
1710 1710 methods = {
1711 1711 "range": rangeset,
1712 1712 "dagrange": dagrange,
1713 1713 "string": stringset,
1714 1714 "symbol": symbolset,
1715 1715 "and": andset,
1716 1716 "or": orset,
1717 1717 "not": notset,
1718 1718 "list": listset,
1719 1719 "func": func,
1720 1720 "ancestor": ancestorspec,
1721 1721 "parent": parentspec,
1722 1722 "parentpost": p1,
1723 1723 }
1724 1724
1725 1725 def optimize(x, small):
1726 1726 if x is None:
1727 1727 return 0, x
1728 1728
1729 1729 smallbonus = 1
1730 1730 if small:
1731 1731 smallbonus = .5
1732 1732
1733 1733 op = x[0]
1734 1734 if op == 'minus':
1735 1735 return optimize(('and', x[1], ('not', x[2])), small)
1736 1736 elif op == 'dagrangepre':
1737 1737 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
1738 1738 elif op == 'dagrangepost':
1739 1739 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
1740 1740 elif op == 'rangepre':
1741 1741 return optimize(('range', ('string', '0'), x[1]), small)
1742 1742 elif op == 'rangepost':
1743 1743 return optimize(('range', x[1], ('string', 'tip')), small)
1744 1744 elif op == 'negate':
1745 1745 return optimize(('string',
1746 1746 '-' + getstring(x[1], _("can't negate that"))), small)
1747 1747 elif op in 'string symbol negate':
1748 1748 return smallbonus, x # single revisions are small
1749 1749 elif op == 'and':
1750 1750 wa, ta = optimize(x[1], True)
1751 1751 wb, tb = optimize(x[2], True)
1752 1752
1753 1753 # (::x and not ::y)/(not ::y and ::x) have a fast path
1754 1754 def ismissingancestors(revs, bases):
1755 1755 return (
1756 1756 revs[0] == 'func'
1757 1757 and getstring(revs[1], _('not a symbol')) == 'ancestors'
1758 1758 and bases[0] == 'not'
1759 1759 and bases[1][0] == 'func'
1760 1760 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
1761 1761
1762 1762 w = min(wa, wb)
1763 1763 if ismissingancestors(ta, tb):
1764 1764 return w, ('func', ('symbol', '_missingancestors'),
1765 1765 ('list', ta[2], tb[1][2]))
1766 1766 if ismissingancestors(tb, ta):
1767 1767 return w, ('func', ('symbol', '_missingancestors'),
1768 1768 ('list', tb[2], ta[1][2]))
1769 1769
1770 1770 if wa > wb:
1771 1771 return w, (op, tb, ta)
1772 1772 return w, (op, ta, tb)
1773 1773 elif op == 'or':
1774 1774 wa, ta = optimize(x[1], False)
1775 1775 wb, tb = optimize(x[2], False)
1776 1776 if wb < wa:
1777 1777 wb, wa = wa, wb
1778 1778 return max(wa, wb), (op, ta, tb)
1779 1779 elif op == 'not':
1780 1780 o = optimize(x[1], not small)
1781 1781 return o[0], (op, o[1])
1782 1782 elif op == 'parentpost':
1783 1783 o = optimize(x[1], small)
1784 1784 return o[0], (op, o[1])
1785 1785 elif op == 'group':
1786 1786 return optimize(x[1], small)
1787 1787 elif op in 'dagrange range list parent ancestorspec':
1788 1788 if op == 'parent':
1789 1789 # x^:y means (x^) : y, not x ^ (:y)
1790 1790 post = ('parentpost', x[1])
1791 1791 if x[2][0] == 'dagrangepre':
1792 1792 return optimize(('dagrange', post, x[2][1]), small)
1793 1793 elif x[2][0] == 'rangepre':
1794 1794 return optimize(('range', post, x[2][1]), small)
1795 1795
1796 1796 wa, ta = optimize(x[1], small)
1797 1797 wb, tb = optimize(x[2], small)
1798 1798 return wa + wb, (op, ta, tb)
1799 1799 elif op == 'func':
1800 1800 f = getstring(x[1], _("not a symbol"))
1801 1801 wa, ta = optimize(x[2], small)
1802 1802 if f in ("author branch closed date desc file grep keyword "
1803 1803 "outgoing user"):
1804 1804 w = 10 # slow
1805 1805 elif f in "modifies adds removes":
1806 1806 w = 30 # slower
1807 1807 elif f == "contains":
1808 1808 w = 100 # very slow
1809 1809 elif f == "ancestor":
1810 1810 w = 1 * smallbonus
1811 1811 elif f in "reverse limit first":
1812 1812 w = 0
1813 1813 elif f in "sort":
1814 1814 w = 10 # assume most sorts look at changelog
1815 1815 else:
1816 1816 w = 1
1817 1817 return w + wa, (op, x[1], ta)
1818 1818 return 1, x
1819 1819
1820 1820 _aliasarg = ('func', ('symbol', '_aliasarg'))
1821 1821 def _getaliasarg(tree):
1822 1822 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
1823 1823 return X, None otherwise.
1824 1824 """
1825 1825 if (len(tree) == 3 and tree[:2] == _aliasarg
1826 1826 and tree[2][0] == 'string'):
1827 1827 return tree[2][1]
1828 1828 return None
1829 1829
1830 1830 def _checkaliasarg(tree, known=None):
1831 1831 """Check tree contains no _aliasarg construct or only ones which
1832 1832 value is in known. Used to avoid alias placeholders injection.
1833 1833 """
1834 1834 if isinstance(tree, tuple):
1835 1835 arg = _getaliasarg(tree)
1836 1836 if arg is not None and (not known or arg not in known):
1837 1837 raise error.ParseError(_("not a function: %s") % '_aliasarg')
1838 1838 for t in tree:
1839 1839 _checkaliasarg(t, known)
1840 1840
1841 1841 class revsetalias(object):
1842 1842 funcre = re.compile('^([^(]+)\(([^)]+)\)$')
1843 1843 args = None
1844 1844
1845 1845 def __init__(self, name, value):
1846 1846 '''Aliases like:
1847 1847
1848 1848 h = heads(default)
1849 1849 b($1) = ancestors($1) - ancestors(default)
1850 1850 '''
1851 1851 m = self.funcre.search(name)
1852 1852 if m:
1853 1853 self.name = m.group(1)
1854 1854 self.tree = ('func', ('symbol', m.group(1)))
1855 1855 self.args = [x.strip() for x in m.group(2).split(',')]
1856 1856 for arg in self.args:
1857 1857 # _aliasarg() is an unknown symbol only used separate
1858 1858 # alias argument placeholders from regular strings.
1859 1859 value = value.replace(arg, '_aliasarg(%r)' % (arg,))
1860 1860 else:
1861 1861 self.name = name
1862 1862 self.tree = ('symbol', name)
1863 1863
1864 1864 self.replacement, pos = parse(value)
1865 1865 if pos != len(value):
1866 1866 raise error.ParseError(_('invalid token'), pos)
1867 1867 # Check for placeholder injection
1868 1868 _checkaliasarg(self.replacement, self.args)
1869 1869
1870 1870 def _getalias(aliases, tree):
1871 1871 """If tree looks like an unexpanded alias, return it. Return None
1872 1872 otherwise.
1873 1873 """
1874 1874 if isinstance(tree, tuple) and tree:
1875 1875 if tree[0] == 'symbol' and len(tree) == 2:
1876 1876 name = tree[1]
1877 1877 alias = aliases.get(name)
1878 1878 if alias and alias.args is None and alias.tree == tree:
1879 1879 return alias
1880 1880 if tree[0] == 'func' and len(tree) > 1:
1881 1881 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
1882 1882 name = tree[1][1]
1883 1883 alias = aliases.get(name)
1884 1884 if alias and alias.args is not None and alias.tree == tree[:2]:
1885 1885 return alias
1886 1886 return None
1887 1887
1888 1888 def _expandargs(tree, args):
1889 1889 """Replace _aliasarg instances with the substitution value of the
1890 1890 same name in args, recursively.
1891 1891 """
1892 1892 if not tree or not isinstance(tree, tuple):
1893 1893 return tree
1894 1894 arg = _getaliasarg(tree)
1895 1895 if arg is not None:
1896 1896 return args[arg]
1897 1897 return tuple(_expandargs(t, args) for t in tree)
1898 1898
1899 1899 def _expandaliases(aliases, tree, expanding, cache):
1900 1900 """Expand aliases in tree, recursively.
1901 1901
1902 1902 'aliases' is a dictionary mapping user defined aliases to
1903 1903 revsetalias objects.
1904 1904 """
1905 1905 if not isinstance(tree, tuple):
1906 1906 # Do not expand raw strings
1907 1907 return tree
1908 1908 alias = _getalias(aliases, tree)
1909 1909 if alias is not None:
1910 1910 if alias in expanding:
1911 1911 raise error.ParseError(_('infinite expansion of revset alias "%s" '
1912 1912 'detected') % alias.name)
1913 1913 expanding.append(alias)
1914 1914 if alias.name not in cache:
1915 1915 cache[alias.name] = _expandaliases(aliases, alias.replacement,
1916 1916 expanding, cache)
1917 1917 result = cache[alias.name]
1918 1918 expanding.pop()
1919 1919 if alias.args is not None:
1920 1920 l = getlist(tree[2])
1921 1921 if len(l) != len(alias.args):
1922 1922 raise error.ParseError(
1923 1923 _('invalid number of arguments: %s') % len(l))
1924 1924 l = [_expandaliases(aliases, a, [], cache) for a in l]
1925 1925 result = _expandargs(result, dict(zip(alias.args, l)))
1926 1926 else:
1927 1927 result = tuple(_expandaliases(aliases, t, expanding, cache)
1928 1928 for t in tree)
1929 1929 return result
1930 1930
1931 1931 def findaliases(ui, tree):
1932 1932 _checkaliasarg(tree)
1933 1933 aliases = {}
1934 1934 for k, v in ui.configitems('revsetalias'):
1935 1935 alias = revsetalias(k, v)
1936 1936 aliases[alias.name] = alias
1937 1937 return _expandaliases(aliases, tree, [], {})
1938 1938
1939 1939 def parse(spec):
1940 1940 p = parser.parser(tokenize, elements)
1941 1941 return p.parse(spec)
1942 1942
1943 1943 def match(ui, spec):
1944 1944 if not spec:
1945 1945 raise error.ParseError(_("empty query"))
1946 1946 tree, pos = parse(spec)
1947 1947 if (pos != len(spec)):
1948 1948 raise error.ParseError(_("invalid token"), pos)
1949 1949 if ui:
1950 1950 tree = findaliases(ui, tree)
1951 1951 weight, tree = optimize(tree, True)
1952 1952 def mfunc(repo, subset):
1953 1953 return getset(repo, subset, tree)
1954 1954 return mfunc
1955 1955
1956 1956 def formatspec(expr, *args):
1957 1957 '''
1958 1958 This is a convenience function for using revsets internally, and
1959 1959 escapes arguments appropriately. Aliases are intentionally ignored
1960 1960 so that intended expression behavior isn't accidentally subverted.
1961 1961
1962 1962 Supported arguments:
1963 1963
1964 1964 %r = revset expression, parenthesized
1965 1965 %d = int(arg), no quoting
1966 1966 %s = string(arg), escaped and single-quoted
1967 1967 %b = arg.branch(), escaped and single-quoted
1968 1968 %n = hex(arg), single-quoted
1969 1969 %% = a literal '%'
1970 1970
1971 1971 Prefixing the type with 'l' specifies a parenthesized list of that type.
1972 1972
1973 1973 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
1974 1974 '(10 or 11):: and ((this()) or (that()))'
1975 1975 >>> formatspec('%d:: and not %d::', 10, 20)
1976 1976 '10:: and not 20::'
1977 1977 >>> formatspec('%ld or %ld', [], [1])
1978 1978 "_list('') or 1"
1979 1979 >>> formatspec('keyword(%s)', 'foo\\xe9')
1980 1980 "keyword('foo\\\\xe9')"
1981 1981 >>> b = lambda: 'default'
1982 1982 >>> b.branch = b
1983 1983 >>> formatspec('branch(%b)', b)
1984 1984 "branch('default')"
1985 1985 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
1986 1986 "root(_list('a\\x00b\\x00c\\x00d'))"
1987 1987 '''
1988 1988
1989 1989 def quote(s):
1990 1990 return repr(str(s))
1991 1991
1992 1992 def argtype(c, arg):
1993 1993 if c == 'd':
1994 1994 return str(int(arg))
1995 1995 elif c == 's':
1996 1996 return quote(arg)
1997 1997 elif c == 'r':
1998 1998 parse(arg) # make sure syntax errors are confined
1999 1999 return '(%s)' % arg
2000 2000 elif c == 'n':
2001 2001 return quote(node.hex(arg))
2002 2002 elif c == 'b':
2003 2003 return quote(arg.branch())
2004 2004
2005 2005 def listexp(s, t):
2006 2006 l = len(s)
2007 2007 if l == 0:
2008 2008 return "_list('')"
2009 2009 elif l == 1:
2010 2010 return argtype(t, s[0])
2011 2011 elif t == 'd':
2012 2012 return "_list('%s')" % "\0".join(str(int(a)) for a in s)
2013 2013 elif t == 's':
2014 2014 return "_list('%s')" % "\0".join(s)
2015 2015 elif t == 'n':
2016 2016 return "_list('%s')" % "\0".join(node.hex(a) for a in s)
2017 2017 elif t == 'b':
2018 2018 return "_list('%s')" % "\0".join(a.branch() for a in s)
2019 2019
2020 2020 m = l // 2
2021 2021 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2022 2022
2023 2023 ret = ''
2024 2024 pos = 0
2025 2025 arg = 0
2026 2026 while pos < len(expr):
2027 2027 c = expr[pos]
2028 2028 if c == '%':
2029 2029 pos += 1
2030 2030 d = expr[pos]
2031 2031 if d == '%':
2032 2032 ret += d
2033 2033 elif d in 'dsnbr':
2034 2034 ret += argtype(d, args[arg])
2035 2035 arg += 1
2036 2036 elif d == 'l':
2037 2037 # a list of some type
2038 2038 pos += 1
2039 2039 d = expr[pos]
2040 2040 ret += listexp(list(args[arg]), d)
2041 2041 arg += 1
2042 2042 else:
2043 2043 raise util.Abort('unexpected revspec format character %s' % d)
2044 2044 else:
2045 2045 ret += c
2046 2046 pos += 1
2047 2047
2048 2048 return ret
2049 2049
2050 2050 def prettyformat(tree):
2051 2051 def _prettyformat(tree, level, lines):
2052 2052 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2053 2053 lines.append((level, str(tree)))
2054 2054 else:
2055 2055 lines.append((level, '(%s' % tree[0]))
2056 2056 for s in tree[1:]:
2057 2057 _prettyformat(s, level + 1, lines)
2058 2058 lines[-1:] = [(lines[-1][0], lines[-1][1] + ')')]
2059 2059
2060 2060 lines = []
2061 2061 _prettyformat(tree, 0, lines)
2062 2062 output = '\n'.join((' '*l + s) for l, s in lines)
2063 2063 return output
2064 2064
2065 2065 def depth(tree):
2066 2066 if isinstance(tree, tuple):
2067 2067 return max(map(depth, tree)) + 1
2068 2068 else:
2069 2069 return 0
2070 2070
2071 2071 def funcsused(tree):
2072 2072 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2073 2073 return set()
2074 2074 else:
2075 2075 funcs = set()
2076 2076 for s in tree[1:]:
2077 2077 funcs |= funcsused(s)
2078 2078 if tree[0] == 'func':
2079 2079 funcs.add(tree[1][1])
2080 2080 return funcs
2081 2081
2082 2082 class baseset(list):
2083 2083 """Basic data structure that represents a revset and contains the basic
2084 2084 operation that it should be able to perform.
2085 2085 """
2086 2086 def __init__(self, data):
2087 2087 super(baseset, self).__init__(data)
2088 2088 self._set = None
2089 2089
2090 2090 def set(self):
2091 2091 if not self._set:
2092 2092 self._set = set(self)
2093 2093 return self._set
2094 2094
2095 2095 def __sub__(self, x):
2096 2096 if isinstance(x, baseset):
2097 2097 s = x.set()
2098 2098 else:
2099 2099 s = set(x)
2100 2100 return baseset(self.set() - s)
2101 2101
2102 2102 def __and__(self, x):
2103 2103 if isinstance(x, baseset):
2104 2104 x = x.set()
2105 2105 return baseset([y for y in self if y in x])
2106 2106
2107 2107 def __add__(self, x):
2108 2108 s = self.set()
2109 2109 l = [r for r in x if r not in s]
2110 2110 return baseset(list(self) + l)
2111 2111
2112 2112 class lazyset(object):
2113 2113 """Duck type for baseset class which iterates lazily over the revisions in
2114 2114 the subset and contains a function which tests for membership in the
2115 2115 revset
2116 2116 """
2117 2117 def __init__(self, subset, condition):
2118 2118 self._subset = subset
2119 2119 self._condition = condition
2120 self._cache = {}
2120 2121
2121 2122 def __contains__(self, x):
2122 return x in self._subset and self._condition(x)
2123 c = self._cache
2124 if x not in c:
2125 c[x] = x in self._subset and self._condition(x)
2126 return c[x]
2123 2127
2124 2128 def __iter__(self):
2125 2129 cond = self._condition
2126 2130 for x in self._subset:
2127 2131 if cond(x):
2128 2132 yield x
2129 2133
2130 2134 def __and__(self, x):
2131 2135 return lazyset(self, lambda r: r in x)
2132 2136
2133 2137 def __sub__(self, x):
2134 2138 return lazyset(self, lambda r: r not in x)
2135 2139
2136 2140 def __add__(self, x):
2137 2141 l = baseset([r for r in self])
2138 2142 return l + baseset(x)
2139 2143
2140 2144 def __len__(self):
2141 2145 # Basic implementation to be changed in future patches.
2142 2146 l = baseset([r for r in self])
2143 2147 return len(l)
2144 2148
2145 2149 def __getitem__(self, x):
2146 2150 # Basic implementation to be changed in future patches.
2147 2151 l = baseset([r for r in self])
2148 2152 return l[x]
2149 2153
2150 2154 def sort(self, reverse=False):
2151 2155 # Basic implementation to be changed in future patches.
2152 2156 self._subset = baseset(self._subset)
2153 2157 self._subset.sort(reverse=reverse)
2154 2158
2155 2159 def reverse(self):
2156 2160 self._subset.reverse()
2157 2161
2158 2162 def set(self):
2159 2163 return set([r for r in self])
2160 2164
2161 2165 class spanset(object):
2162 2166 """Duck type for baseset class which represents a range of revisions and
2163 2167 can work lazily and without having all the range in memory
2164 2168 """
2165 2169 def __init__(self, start, end):
2166 2170 self._start = start
2167 2171 self._end = end
2168 2172
2169 2173 def __iter__(self):
2170 2174 if self._start <= self._end:
2171 2175 for r in xrange(self._start, self._end):
2172 2176 yield r
2173 2177 else:
2174 2178 for r in xrange(self._start, self._end, -1):
2175 2179 yield r
2176 2180
2177 2181 def __contains__(self, x):
2178 2182 return (x <= self._start and x > self._end) or (x >= self._start and x<
2179 2183 self._end)
2180 2184
2181 2185 def __and__(self, x):
2182 2186 return lazyset(self, lambda r: r in x)
2183 2187
2184 2188 def __sub__(self, x):
2185 2189 return lazyset(self, lambda r: r not in x)
2186 2190
2187 2191 def __add__(self, x):
2188 2192 l = baseset(self)
2189 2193 return l + baseset(x)
2190 2194
2191 2195 def __len__(self):
2192 2196 return abs(self._end - self._start)
2193 2197
2194 2198 def __getitem__(self, x):
2195 2199 # Basic implementation to be changed in future patches.
2196 2200 l = baseset([r for r in self])
2197 2201 return l[x]
2198 2202
2199 2203 def sort(self, reverse=False):
2200 2204 # Basic implementation to be changed in future patches.
2201 2205 if reverse:
2202 2206 self.reverse()
2203 2207
2204 2208 def reverse(self):
2205 2209 if self._start <= self._end:
2206 2210 self._start, self._end = self._end - 1, self._start - 1
2207 2211 else:
2208 2212 self._start, self._end = self._end + 1, self._start + 1
2209 2213
2210 2214 def set(self):
2211 2215 return self
2212 2216
2213 2217 # tell hggettext to extract docstrings from these functions:
2214 2218 i18nfunctions = symbols.values()
General Comments 0
You need to be logged in to leave comments. Login now