##// END OF EJS Templates
revset: prevent crash caused by empty group expression while optimizing "and"...
Yuya Nishihara -
r25995:4f703dcc stable
parent child Browse files
Show More
@@ -1,3661 +1,3663
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, hbisect, phases
10 10 import node
11 11 import heapq
12 12 import match as matchmod
13 13 from i18n import _
14 14 import encoding
15 15 import obsolete as obsmod
16 16 import pathutil
17 17 import repoview
18 18
19 19 def _revancestors(repo, revs, followfirst):
20 20 """Like revlog.ancestors(), but supports followfirst."""
21 21 if followfirst:
22 22 cut = 1
23 23 else:
24 24 cut = None
25 25 cl = repo.changelog
26 26
27 27 def iterate():
28 28 revs.sort(reverse=True)
29 29 irevs = iter(revs)
30 30 h = []
31 31
32 32 inputrev = next(irevs, None)
33 33 if inputrev is not None:
34 34 heapq.heappush(h, -inputrev)
35 35
36 36 seen = set()
37 37 while h:
38 38 current = -heapq.heappop(h)
39 39 if current == inputrev:
40 40 inputrev = next(irevs, None)
41 41 if inputrev is not None:
42 42 heapq.heappush(h, -inputrev)
43 43 if current not in seen:
44 44 seen.add(current)
45 45 yield current
46 46 for parent in cl.parentrevs(current)[:cut]:
47 47 if parent != node.nullrev:
48 48 heapq.heappush(h, -parent)
49 49
50 50 return generatorset(iterate(), iterasc=False)
51 51
52 52 def _revdescendants(repo, revs, followfirst):
53 53 """Like revlog.descendants() but supports followfirst."""
54 54 if followfirst:
55 55 cut = 1
56 56 else:
57 57 cut = None
58 58
59 59 def iterate():
60 60 cl = repo.changelog
61 61 # XXX this should be 'parentset.min()' assuming 'parentset' is a
62 62 # smartset (and if it is not, it should.)
63 63 first = min(revs)
64 64 nullrev = node.nullrev
65 65 if first == nullrev:
66 66 # Are there nodes with a null first parent and a non-null
67 67 # second one? Maybe. Do we care? Probably not.
68 68 for i in cl:
69 69 yield i
70 70 else:
71 71 seen = set(revs)
72 72 for i in cl.revs(first + 1):
73 73 for x in cl.parentrevs(i)[:cut]:
74 74 if x != nullrev and x in seen:
75 75 seen.add(i)
76 76 yield i
77 77 break
78 78
79 79 return generatorset(iterate(), iterasc=True)
80 80
81 81 def _revsbetween(repo, roots, heads):
82 82 """Return all paths between roots and heads, inclusive of both endpoint
83 83 sets."""
84 84 if not roots:
85 85 return baseset()
86 86 parentrevs = repo.changelog.parentrevs
87 87 visit = list(heads)
88 88 reachable = set()
89 89 seen = {}
90 90 # XXX this should be 'parentset.min()' assuming 'parentset' is a smartset
91 91 # (and if it is not, it should.)
92 92 minroot = min(roots)
93 93 roots = set(roots)
94 94 # prefetch all the things! (because python is slow)
95 95 reached = reachable.add
96 96 dovisit = visit.append
97 97 nextvisit = visit.pop
98 98 # open-code the post-order traversal due to the tiny size of
99 99 # sys.getrecursionlimit()
100 100 while visit:
101 101 rev = nextvisit()
102 102 if rev in roots:
103 103 reached(rev)
104 104 parents = parentrevs(rev)
105 105 seen[rev] = parents
106 106 for parent in parents:
107 107 if parent >= minroot and parent not in seen:
108 108 dovisit(parent)
109 109 if not reachable:
110 110 return baseset()
111 111 for rev in sorted(seen):
112 112 for parent in seen[rev]:
113 113 if parent in reachable:
114 114 reached(rev)
115 115 return baseset(sorted(reachable))
116 116
117 117 elements = {
118 118 # token-type: binding-strength, primary, prefix, infix, suffix
119 119 "(": (21, None, ("group", 1, ")"), ("func", 1, ")"), None),
120 120 "##": (20, None, None, ("_concat", 20), None),
121 121 "~": (18, None, None, ("ancestor", 18), None),
122 122 "^": (18, None, None, ("parent", 18), ("parentpost", 18)),
123 123 "-": (5, None, ("negate", 19), ("minus", 5), None),
124 124 "::": (17, None, ("dagrangepre", 17), ("dagrange", 17),
125 125 ("dagrangepost", 17)),
126 126 "..": (17, None, ("dagrangepre", 17), ("dagrange", 17),
127 127 ("dagrangepost", 17)),
128 128 ":": (15, "rangeall", ("rangepre", 15), ("range", 15), ("rangepost", 15)),
129 129 "not": (10, None, ("not", 10), None, None),
130 130 "!": (10, None, ("not", 10), None, None),
131 131 "and": (5, None, None, ("and", 5), None),
132 132 "&": (5, None, None, ("and", 5), None),
133 133 "%": (5, None, None, ("only", 5), ("onlypost", 5)),
134 134 "or": (4, None, None, ("or", 4), None),
135 135 "|": (4, None, None, ("or", 4), None),
136 136 "+": (4, None, None, ("or", 4), None),
137 137 "=": (3, None, None, ("keyvalue", 3), None),
138 138 ",": (2, None, None, ("list", 2), None),
139 139 ")": (0, None, None, None, None),
140 140 "symbol": (0, "symbol", None, None, None),
141 141 "string": (0, "string", None, None, None),
142 142 "end": (0, None, None, None, None),
143 143 }
144 144
145 145 keywords = set(['and', 'or', 'not'])
146 146
147 147 # default set of valid characters for the initial letter of symbols
148 148 _syminitletters = set(c for c in [chr(i) for i in xrange(256)]
149 149 if c.isalnum() or c in '._@' or ord(c) > 127)
150 150
151 151 # default set of valid characters for non-initial letters of symbols
152 152 _symletters = set(c for c in [chr(i) for i in xrange(256)]
153 153 if c.isalnum() or c in '-._/@' or ord(c) > 127)
154 154
155 155 def tokenize(program, lookup=None, syminitletters=None, symletters=None):
156 156 '''
157 157 Parse a revset statement into a stream of tokens
158 158
159 159 ``syminitletters`` is the set of valid characters for the initial
160 160 letter of symbols.
161 161
162 162 By default, character ``c`` is recognized as valid for initial
163 163 letter of symbols, if ``c.isalnum() or c in '._@' or ord(c) > 127``.
164 164
165 165 ``symletters`` is the set of valid characters for non-initial
166 166 letters of symbols.
167 167
168 168 By default, character ``c`` is recognized as valid for non-initial
169 169 letters of symbols, if ``c.isalnum() or c in '-._/@' or ord(c) > 127``.
170 170
171 171 Check that @ is a valid unquoted token character (issue3686):
172 172 >>> list(tokenize("@::"))
173 173 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
174 174
175 175 '''
176 176 if syminitletters is None:
177 177 syminitletters = _syminitletters
178 178 if symletters is None:
179 179 symletters = _symletters
180 180
181 181 pos, l = 0, len(program)
182 182 while pos < l:
183 183 c = program[pos]
184 184 if c.isspace(): # skip inter-token whitespace
185 185 pass
186 186 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
187 187 yield ('::', None, pos)
188 188 pos += 1 # skip ahead
189 189 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
190 190 yield ('..', None, pos)
191 191 pos += 1 # skip ahead
192 192 elif c == '#' and program[pos:pos + 2] == '##': # look ahead carefully
193 193 yield ('##', None, pos)
194 194 pos += 1 # skip ahead
195 195 elif c in "():=,-|&+!~^%": # handle simple operators
196 196 yield (c, None, pos)
197 197 elif (c in '"\'' or c == 'r' and
198 198 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
199 199 if c == 'r':
200 200 pos += 1
201 201 c = program[pos]
202 202 decode = lambda x: x
203 203 else:
204 204 decode = lambda x: x.decode('string-escape')
205 205 pos += 1
206 206 s = pos
207 207 while pos < l: # find closing quote
208 208 d = program[pos]
209 209 if d == '\\': # skip over escaped characters
210 210 pos += 2
211 211 continue
212 212 if d == c:
213 213 yield ('string', decode(program[s:pos]), s)
214 214 break
215 215 pos += 1
216 216 else:
217 217 raise error.ParseError(_("unterminated string"), s)
218 218 # gather up a symbol/keyword
219 219 elif c in syminitletters:
220 220 s = pos
221 221 pos += 1
222 222 while pos < l: # find end of symbol
223 223 d = program[pos]
224 224 if d not in symletters:
225 225 break
226 226 if d == '.' and program[pos - 1] == '.': # special case for ..
227 227 pos -= 1
228 228 break
229 229 pos += 1
230 230 sym = program[s:pos]
231 231 if sym in keywords: # operator keywords
232 232 yield (sym, None, s)
233 233 elif '-' in sym:
234 234 # some jerk gave us foo-bar-baz, try to check if it's a symbol
235 235 if lookup and lookup(sym):
236 236 # looks like a real symbol
237 237 yield ('symbol', sym, s)
238 238 else:
239 239 # looks like an expression
240 240 parts = sym.split('-')
241 241 for p in parts[:-1]:
242 242 if p: # possible consecutive -
243 243 yield ('symbol', p, s)
244 244 s += len(p)
245 245 yield ('-', None, pos)
246 246 s += 1
247 247 if parts[-1]: # possible trailing -
248 248 yield ('symbol', parts[-1], s)
249 249 else:
250 250 yield ('symbol', sym, s)
251 251 pos -= 1
252 252 else:
253 253 raise error.ParseError(_("syntax error in revset '%s'") %
254 254 program, pos)
255 255 pos += 1
256 256 yield ('end', None, pos)
257 257
258 258 def parseerrordetail(inst):
259 259 """Compose error message from specified ParseError object
260 260 """
261 261 if len(inst.args) > 1:
262 262 return _('at %s: %s') % (inst.args[1], inst.args[0])
263 263 else:
264 264 return inst.args[0]
265 265
266 266 # helpers
267 267
268 268 def getstring(x, err):
269 269 if x and (x[0] == 'string' or x[0] == 'symbol'):
270 270 return x[1]
271 271 raise error.ParseError(err)
272 272
273 273 def getlist(x):
274 274 if not x:
275 275 return []
276 276 if x[0] == 'list':
277 277 return getlist(x[1]) + [x[2]]
278 278 return [x]
279 279
280 280 def getargs(x, min, max, err):
281 281 l = getlist(x)
282 282 if len(l) < min or (max >= 0 and len(l) > max):
283 283 raise error.ParseError(err)
284 284 return l
285 285
286 286 def getargsdict(x, funcname, keys):
287 287 return parser.buildargsdict(getlist(x), funcname, keys.split(),
288 288 keyvaluenode='keyvalue', keynode='symbol')
289 289
290 290 def isvalidsymbol(tree):
291 291 """Examine whether specified ``tree`` is valid ``symbol`` or not
292 292 """
293 293 return tree[0] == 'symbol' and len(tree) > 1
294 294
295 295 def getsymbol(tree):
296 296 """Get symbol name from valid ``symbol`` in ``tree``
297 297
298 298 This assumes that ``tree`` is already examined by ``isvalidsymbol``.
299 299 """
300 300 return tree[1]
301 301
302 302 def isvalidfunc(tree):
303 303 """Examine whether specified ``tree`` is valid ``func`` or not
304 304 """
305 305 return tree[0] == 'func' and len(tree) > 1 and isvalidsymbol(tree[1])
306 306
307 307 def getfuncname(tree):
308 308 """Get function name from valid ``func`` in ``tree``
309 309
310 310 This assumes that ``tree`` is already examined by ``isvalidfunc``.
311 311 """
312 312 return getsymbol(tree[1])
313 313
314 314 def getfuncargs(tree):
315 315 """Get list of function arguments from valid ``func`` in ``tree``
316 316
317 317 This assumes that ``tree`` is already examined by ``isvalidfunc``.
318 318 """
319 319 if len(tree) > 2:
320 320 return getlist(tree[2])
321 321 else:
322 322 return []
323 323
324 324 def getset(repo, subset, x):
325 325 if not x:
326 326 raise error.ParseError(_("missing argument"))
327 327 s = methods[x[0]](repo, subset, *x[1:])
328 328 if util.safehasattr(s, 'isascending'):
329 329 return s
330 330 if (repo.ui.configbool('devel', 'all-warnings')
331 331 or repo.ui.configbool('devel', 'old-revset')):
332 332 # else case should not happen, because all non-func are internal,
333 333 # ignoring for now.
334 334 if x[0] == 'func' and x[1][0] == 'symbol' and x[1][1] in symbols:
335 335 repo.ui.develwarn('revset "%s" use list instead of smartset, '
336 336 '(upgrade your code)' % x[1][1])
337 337 return baseset(s)
338 338
339 339 def _getrevsource(repo, r):
340 340 extra = repo[r].extra()
341 341 for label in ('source', 'transplant_source', 'rebase_source'):
342 342 if label in extra:
343 343 try:
344 344 return repo[extra[label]].rev()
345 345 except error.RepoLookupError:
346 346 pass
347 347 return None
348 348
349 349 # operator methods
350 350
351 351 def stringset(repo, subset, x):
352 352 x = repo[x].rev()
353 353 if (x in subset
354 354 or x == node.nullrev and isinstance(subset, fullreposet)):
355 355 return baseset([x])
356 356 return baseset()
357 357
358 358 def rangeset(repo, subset, x, y):
359 359 m = getset(repo, fullreposet(repo), x)
360 360 n = getset(repo, fullreposet(repo), y)
361 361
362 362 if not m or not n:
363 363 return baseset()
364 364 m, n = m.first(), n.last()
365 365
366 366 if m == n:
367 367 r = baseset([m])
368 368 elif n == node.wdirrev:
369 369 r = spanset(repo, m, len(repo)) + baseset([n])
370 370 elif m == node.wdirrev:
371 371 r = baseset([m]) + spanset(repo, len(repo) - 1, n - 1)
372 372 elif m < n:
373 373 r = spanset(repo, m, n + 1)
374 374 else:
375 375 r = spanset(repo, m, n - 1)
376 376 # XXX We should combine with subset first: 'subset & baseset(...)'. This is
377 377 # necessary to ensure we preserve the order in subset.
378 378 #
379 379 # This has performance implication, carrying the sorting over when possible
380 380 # would be more efficient.
381 381 return r & subset
382 382
383 383 def dagrange(repo, subset, x, y):
384 384 r = fullreposet(repo)
385 385 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
386 386 # XXX We should combine with subset first: 'subset & baseset(...)'. This is
387 387 # necessary to ensure we preserve the order in subset.
388 388 return xs & subset
389 389
390 390 def andset(repo, subset, x, y):
391 391 return getset(repo, getset(repo, subset, x), y)
392 392
393 393 def orset(repo, subset, *xs):
394 394 rs = [getset(repo, subset, x) for x in xs]
395 395 return _combinesets(rs)
396 396
397 397 def notset(repo, subset, x):
398 398 return subset - getset(repo, subset, x)
399 399
400 400 def listset(repo, subset, a, b):
401 401 raise error.ParseError(_("can't use a list in this context"))
402 402
403 403 def keyvaluepair(repo, subset, k, v):
404 404 raise error.ParseError(_("can't use a key-value pair in this context"))
405 405
406 406 def func(repo, subset, a, b):
407 407 if a[0] == 'symbol' and a[1] in symbols:
408 408 return symbols[a[1]](repo, subset, b)
409 409
410 410 keep = lambda fn: getattr(fn, '__doc__', None) is not None
411 411
412 412 syms = [s for (s, fn) in symbols.items() if keep(fn)]
413 413 raise error.UnknownIdentifier(a[1], syms)
414 414
415 415 # functions
416 416
417 417 def adds(repo, subset, x):
418 418 """``adds(pattern)``
419 419 Changesets that add a file matching pattern.
420 420
421 421 The pattern without explicit kind like ``glob:`` is expected to be
422 422 relative to the current directory and match against a file or a
423 423 directory.
424 424 """
425 425 # i18n: "adds" is a keyword
426 426 pat = getstring(x, _("adds requires a pattern"))
427 427 return checkstatus(repo, subset, pat, 1)
428 428
429 429 def ancestor(repo, subset, x):
430 430 """``ancestor(*changeset)``
431 431 A greatest common ancestor of the changesets.
432 432
433 433 Accepts 0 or more changesets.
434 434 Will return empty list when passed no args.
435 435 Greatest common ancestor of a single changeset is that changeset.
436 436 """
437 437 # i18n: "ancestor" is a keyword
438 438 l = getlist(x)
439 439 rl = fullreposet(repo)
440 440 anc = None
441 441
442 442 # (getset(repo, rl, i) for i in l) generates a list of lists
443 443 for revs in (getset(repo, rl, i) for i in l):
444 444 for r in revs:
445 445 if anc is None:
446 446 anc = repo[r]
447 447 else:
448 448 anc = anc.ancestor(repo[r])
449 449
450 450 if anc is not None and anc.rev() in subset:
451 451 return baseset([anc.rev()])
452 452 return baseset()
453 453
454 454 def _ancestors(repo, subset, x, followfirst=False):
455 455 heads = getset(repo, fullreposet(repo), x)
456 456 if not heads:
457 457 return baseset()
458 458 s = _revancestors(repo, heads, followfirst)
459 459 return subset & s
460 460
461 461 def ancestors(repo, subset, x):
462 462 """``ancestors(set)``
463 463 Changesets that are ancestors of a changeset in set.
464 464 """
465 465 return _ancestors(repo, subset, x)
466 466
467 467 def _firstancestors(repo, subset, x):
468 468 # ``_firstancestors(set)``
469 469 # Like ``ancestors(set)`` but follows only the first parents.
470 470 return _ancestors(repo, subset, x, followfirst=True)
471 471
472 472 def ancestorspec(repo, subset, x, n):
473 473 """``set~n``
474 474 Changesets that are the Nth ancestor (first parents only) of a changeset
475 475 in set.
476 476 """
477 477 try:
478 478 n = int(n[1])
479 479 except (TypeError, ValueError):
480 480 raise error.ParseError(_("~ expects a number"))
481 481 ps = set()
482 482 cl = repo.changelog
483 483 for r in getset(repo, fullreposet(repo), x):
484 484 for i in range(n):
485 485 r = cl.parentrevs(r)[0]
486 486 ps.add(r)
487 487 return subset & ps
488 488
489 489 def author(repo, subset, x):
490 490 """``author(string)``
491 491 Alias for ``user(string)``.
492 492 """
493 493 # i18n: "author" is a keyword
494 494 n = encoding.lower(getstring(x, _("author requires a string")))
495 495 kind, pattern, matcher = _substringmatcher(n)
496 496 return subset.filter(lambda x: matcher(encoding.lower(repo[x].user())))
497 497
498 498 def bisect(repo, subset, x):
499 499 """``bisect(string)``
500 500 Changesets marked in the specified bisect status:
501 501
502 502 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
503 503 - ``goods``, ``bads`` : csets topologically good/bad
504 504 - ``range`` : csets taking part in the bisection
505 505 - ``pruned`` : csets that are goods, bads or skipped
506 506 - ``untested`` : csets whose fate is yet unknown
507 507 - ``ignored`` : csets ignored due to DAG topology
508 508 - ``current`` : the cset currently being bisected
509 509 """
510 510 # i18n: "bisect" is a keyword
511 511 status = getstring(x, _("bisect requires a string")).lower()
512 512 state = set(hbisect.get(repo, status))
513 513 return subset & state
514 514
515 515 # Backward-compatibility
516 516 # - no help entry so that we do not advertise it any more
517 517 def bisected(repo, subset, x):
518 518 return bisect(repo, subset, x)
519 519
520 520 def bookmark(repo, subset, x):
521 521 """``bookmark([name])``
522 522 The named bookmark or all bookmarks.
523 523
524 524 If `name` starts with `re:`, the remainder of the name is treated as
525 525 a regular expression. To match a bookmark that actually starts with `re:`,
526 526 use the prefix `literal:`.
527 527 """
528 528 # i18n: "bookmark" is a keyword
529 529 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
530 530 if args:
531 531 bm = getstring(args[0],
532 532 # i18n: "bookmark" is a keyword
533 533 _('the argument to bookmark must be a string'))
534 534 kind, pattern, matcher = _stringmatcher(bm)
535 535 bms = set()
536 536 if kind == 'literal':
537 537 bmrev = repo._bookmarks.get(pattern, None)
538 538 if not bmrev:
539 539 raise error.RepoLookupError(_("bookmark '%s' does not exist")
540 540 % bm)
541 541 bms.add(repo[bmrev].rev())
542 542 else:
543 543 matchrevs = set()
544 544 for name, bmrev in repo._bookmarks.iteritems():
545 545 if matcher(name):
546 546 matchrevs.add(bmrev)
547 547 if not matchrevs:
548 548 raise error.RepoLookupError(_("no bookmarks exist"
549 549 " that match '%s'") % pattern)
550 550 for bmrev in matchrevs:
551 551 bms.add(repo[bmrev].rev())
552 552 else:
553 553 bms = set([repo[r].rev()
554 554 for r in repo._bookmarks.values()])
555 555 bms -= set([node.nullrev])
556 556 return subset & bms
557 557
558 558 def branch(repo, subset, x):
559 559 """``branch(string or set)``
560 560 All changesets belonging to the given branch or the branches of the given
561 561 changesets.
562 562
563 563 If `string` starts with `re:`, the remainder of the name is treated as
564 564 a regular expression. To match a branch that actually starts with `re:`,
565 565 use the prefix `literal:`.
566 566 """
567 567 getbi = repo.revbranchcache().branchinfo
568 568
569 569 try:
570 570 b = getstring(x, '')
571 571 except error.ParseError:
572 572 # not a string, but another revspec, e.g. tip()
573 573 pass
574 574 else:
575 575 kind, pattern, matcher = _stringmatcher(b)
576 576 if kind == 'literal':
577 577 # note: falls through to the revspec case if no branch with
578 578 # this name exists
579 579 if pattern in repo.branchmap():
580 580 return subset.filter(lambda r: matcher(getbi(r)[0]))
581 581 else:
582 582 return subset.filter(lambda r: matcher(getbi(r)[0]))
583 583
584 584 s = getset(repo, fullreposet(repo), x)
585 585 b = set()
586 586 for r in s:
587 587 b.add(getbi(r)[0])
588 588 c = s.__contains__
589 589 return subset.filter(lambda r: c(r) or getbi(r)[0] in b)
590 590
591 591 def bumped(repo, subset, x):
592 592 """``bumped()``
593 593 Mutable changesets marked as successors of public changesets.
594 594
595 595 Only non-public and non-obsolete changesets can be `bumped`.
596 596 """
597 597 # i18n: "bumped" is a keyword
598 598 getargs(x, 0, 0, _("bumped takes no arguments"))
599 599 bumped = obsmod.getrevs(repo, 'bumped')
600 600 return subset & bumped
601 601
602 602 def bundle(repo, subset, x):
603 603 """``bundle()``
604 604 Changesets in the bundle.
605 605
606 606 Bundle must be specified by the -R option."""
607 607
608 608 try:
609 609 bundlerevs = repo.changelog.bundlerevs
610 610 except AttributeError:
611 611 raise util.Abort(_("no bundle provided - specify with -R"))
612 612 return subset & bundlerevs
613 613
614 614 def checkstatus(repo, subset, pat, field):
615 615 hasset = matchmod.patkind(pat) == 'set'
616 616
617 617 mcache = [None]
618 618 def matches(x):
619 619 c = repo[x]
620 620 if not mcache[0] or hasset:
621 621 mcache[0] = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
622 622 m = mcache[0]
623 623 fname = None
624 624 if not m.anypats() and len(m.files()) == 1:
625 625 fname = m.files()[0]
626 626 if fname is not None:
627 627 if fname not in c.files():
628 628 return False
629 629 else:
630 630 for f in c.files():
631 631 if m(f):
632 632 break
633 633 else:
634 634 return False
635 635 files = repo.status(c.p1().node(), c.node())[field]
636 636 if fname is not None:
637 637 if fname in files:
638 638 return True
639 639 else:
640 640 for f in files:
641 641 if m(f):
642 642 return True
643 643
644 644 return subset.filter(matches)
645 645
646 646 def _children(repo, narrow, parentset):
647 647 if not parentset:
648 648 return baseset()
649 649 cs = set()
650 650 pr = repo.changelog.parentrevs
651 651 minrev = parentset.min()
652 652 for r in narrow:
653 653 if r <= minrev:
654 654 continue
655 655 for p in pr(r):
656 656 if p in parentset:
657 657 cs.add(r)
658 658 # XXX using a set to feed the baseset is wrong. Sets are not ordered.
659 659 # This does not break because of other fullreposet misbehavior.
660 660 return baseset(cs)
661 661
662 662 def children(repo, subset, x):
663 663 """``children(set)``
664 664 Child changesets of changesets in set.
665 665 """
666 666 s = getset(repo, fullreposet(repo), x)
667 667 cs = _children(repo, subset, s)
668 668 return subset & cs
669 669
670 670 def closed(repo, subset, x):
671 671 """``closed()``
672 672 Changeset is closed.
673 673 """
674 674 # i18n: "closed" is a keyword
675 675 getargs(x, 0, 0, _("closed takes no arguments"))
676 676 return subset.filter(lambda r: repo[r].closesbranch())
677 677
678 678 def contains(repo, subset, x):
679 679 """``contains(pattern)``
680 680 The revision's manifest contains a file matching pattern (but might not
681 681 modify it). See :hg:`help patterns` for information about file patterns.
682 682
683 683 The pattern without explicit kind like ``glob:`` is expected to be
684 684 relative to the current directory and match against a file exactly
685 685 for efficiency.
686 686 """
687 687 # i18n: "contains" is a keyword
688 688 pat = getstring(x, _("contains requires a pattern"))
689 689
690 690 def matches(x):
691 691 if not matchmod.patkind(pat):
692 692 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
693 693 if pats in repo[x]:
694 694 return True
695 695 else:
696 696 c = repo[x]
697 697 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
698 698 for f in c.manifest():
699 699 if m(f):
700 700 return True
701 701 return False
702 702
703 703 return subset.filter(matches)
704 704
705 705 def converted(repo, subset, x):
706 706 """``converted([id])``
707 707 Changesets converted from the given identifier in the old repository if
708 708 present, or all converted changesets if no identifier is specified.
709 709 """
710 710
711 711 # There is exactly no chance of resolving the revision, so do a simple
712 712 # string compare and hope for the best
713 713
714 714 rev = None
715 715 # i18n: "converted" is a keyword
716 716 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
717 717 if l:
718 718 # i18n: "converted" is a keyword
719 719 rev = getstring(l[0], _('converted requires a revision'))
720 720
721 721 def _matchvalue(r):
722 722 source = repo[r].extra().get('convert_revision', None)
723 723 return source is not None and (rev is None or source.startswith(rev))
724 724
725 725 return subset.filter(lambda r: _matchvalue(r))
726 726
727 727 def date(repo, subset, x):
728 728 """``date(interval)``
729 729 Changesets within the interval, see :hg:`help dates`.
730 730 """
731 731 # i18n: "date" is a keyword
732 732 ds = getstring(x, _("date requires a string"))
733 733 dm = util.matchdate(ds)
734 734 return subset.filter(lambda x: dm(repo[x].date()[0]))
735 735
736 736 def desc(repo, subset, x):
737 737 """``desc(string)``
738 738 Search commit message for string. The match is case-insensitive.
739 739 """
740 740 # i18n: "desc" is a keyword
741 741 ds = encoding.lower(getstring(x, _("desc requires a string")))
742 742
743 743 def matches(x):
744 744 c = repo[x]
745 745 return ds in encoding.lower(c.description())
746 746
747 747 return subset.filter(matches)
748 748
749 749 def _descendants(repo, subset, x, followfirst=False):
750 750 roots = getset(repo, fullreposet(repo), x)
751 751 if not roots:
752 752 return baseset()
753 753 s = _revdescendants(repo, roots, followfirst)
754 754
755 755 # Both sets need to be ascending in order to lazily return the union
756 756 # in the correct order.
757 757 base = subset & roots
758 758 desc = subset & s
759 759 result = base + desc
760 760 if subset.isascending():
761 761 result.sort()
762 762 elif subset.isdescending():
763 763 result.sort(reverse=True)
764 764 else:
765 765 result = subset & result
766 766 return result
767 767
768 768 def descendants(repo, subset, x):
769 769 """``descendants(set)``
770 770 Changesets which are descendants of changesets in set.
771 771 """
772 772 return _descendants(repo, subset, x)
773 773
774 774 def _firstdescendants(repo, subset, x):
775 775 # ``_firstdescendants(set)``
776 776 # Like ``descendants(set)`` but follows only the first parents.
777 777 return _descendants(repo, subset, x, followfirst=True)
778 778
779 779 def destination(repo, subset, x):
780 780 """``destination([set])``
781 781 Changesets that were created by a graft, transplant or rebase operation,
782 782 with the given revisions specified as the source. Omitting the optional set
783 783 is the same as passing all().
784 784 """
785 785 if x is not None:
786 786 sources = getset(repo, fullreposet(repo), x)
787 787 else:
788 788 sources = fullreposet(repo)
789 789
790 790 dests = set()
791 791
792 792 # subset contains all of the possible destinations that can be returned, so
793 793 # iterate over them and see if their source(s) were provided in the arg set.
794 794 # Even if the immediate src of r is not in the arg set, src's source (or
795 795 # further back) may be. Scanning back further than the immediate src allows
796 796 # transitive transplants and rebases to yield the same results as transitive
797 797 # grafts.
798 798 for r in subset:
799 799 src = _getrevsource(repo, r)
800 800 lineage = None
801 801
802 802 while src is not None:
803 803 if lineage is None:
804 804 lineage = list()
805 805
806 806 lineage.append(r)
807 807
808 808 # The visited lineage is a match if the current source is in the arg
809 809 # set. Since every candidate dest is visited by way of iterating
810 810 # subset, any dests further back in the lineage will be tested by a
811 811 # different iteration over subset. Likewise, if the src was already
812 812 # selected, the current lineage can be selected without going back
813 813 # further.
814 814 if src in sources or src in dests:
815 815 dests.update(lineage)
816 816 break
817 817
818 818 r = src
819 819 src = _getrevsource(repo, r)
820 820
821 821 return subset.filter(dests.__contains__)
822 822
823 823 def divergent(repo, subset, x):
824 824 """``divergent()``
825 825 Final successors of changesets with an alternative set of final successors.
826 826 """
827 827 # i18n: "divergent" is a keyword
828 828 getargs(x, 0, 0, _("divergent takes no arguments"))
829 829 divergent = obsmod.getrevs(repo, 'divergent')
830 830 return subset & divergent
831 831
832 832 def extinct(repo, subset, x):
833 833 """``extinct()``
834 834 Obsolete changesets with obsolete descendants only.
835 835 """
836 836 # i18n: "extinct" is a keyword
837 837 getargs(x, 0, 0, _("extinct takes no arguments"))
838 838 extincts = obsmod.getrevs(repo, 'extinct')
839 839 return subset & extincts
840 840
841 841 def extra(repo, subset, x):
842 842 """``extra(label, [value])``
843 843 Changesets with the given label in the extra metadata, with the given
844 844 optional value.
845 845
846 846 If `value` starts with `re:`, the remainder of the value is treated as
847 847 a regular expression. To match a value that actually starts with `re:`,
848 848 use the prefix `literal:`.
849 849 """
850 850 args = getargsdict(x, 'extra', 'label value')
851 851 if 'label' not in args:
852 852 # i18n: "extra" is a keyword
853 853 raise error.ParseError(_('extra takes at least 1 argument'))
854 854 # i18n: "extra" is a keyword
855 855 label = getstring(args['label'], _('first argument to extra must be '
856 856 'a string'))
857 857 value = None
858 858
859 859 if 'value' in args:
860 860 # i18n: "extra" is a keyword
861 861 value = getstring(args['value'], _('second argument to extra must be '
862 862 'a string'))
863 863 kind, value, matcher = _stringmatcher(value)
864 864
865 865 def _matchvalue(r):
866 866 extra = repo[r].extra()
867 867 return label in extra and (value is None or matcher(extra[label]))
868 868
869 869 return subset.filter(lambda r: _matchvalue(r))
870 870
871 871 def filelog(repo, subset, x):
872 872 """``filelog(pattern)``
873 873 Changesets connected to the specified filelog.
874 874
875 875 For performance reasons, visits only revisions mentioned in the file-level
876 876 filelog, rather than filtering through all changesets (much faster, but
877 877 doesn't include deletes or duplicate changes). For a slower, more accurate
878 878 result, use ``file()``.
879 879
880 880 The pattern without explicit kind like ``glob:`` is expected to be
881 881 relative to the current directory and match against a file exactly
882 882 for efficiency.
883 883
884 884 If some linkrev points to revisions filtered by the current repoview, we'll
885 885 work around it to return a non-filtered value.
886 886 """
887 887
888 888 # i18n: "filelog" is a keyword
889 889 pat = getstring(x, _("filelog requires a pattern"))
890 890 s = set()
891 891 cl = repo.changelog
892 892
893 893 if not matchmod.patkind(pat):
894 894 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
895 895 files = [f]
896 896 else:
897 897 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
898 898 files = (f for f in repo[None] if m(f))
899 899
900 900 for f in files:
901 901 backrevref = {} # final value for: filerev -> changerev
902 902 lowestchild = {} # lowest known filerev child of a filerev
903 903 delayed = [] # filerev with filtered linkrev, for post-processing
904 904 lowesthead = None # cache for manifest content of all head revisions
905 905 fl = repo.file(f)
906 906 for fr in list(fl):
907 907 rev = fl.linkrev(fr)
908 908 if rev not in cl:
909 909 # changerev pointed in linkrev is filtered
910 910 # record it for post processing.
911 911 delayed.append((fr, rev))
912 912 continue
913 913 for p in fl.parentrevs(fr):
914 914 if 0 <= p and p not in lowestchild:
915 915 lowestchild[p] = fr
916 916 backrevref[fr] = rev
917 917 s.add(rev)
918 918
919 919 # Post-processing of all filerevs we skipped because they were
920 920 # filtered. If such filerevs have known and unfiltered children, this
921 921 # means they have an unfiltered appearance out there. We'll use linkrev
922 922 # adjustment to find one of these appearances. The lowest known child
923 923 # will be used as a starting point because it is the best upper-bound we
924 924 # have.
925 925 #
926 926 # This approach will fail when an unfiltered but linkrev-shadowed
927 927 # appearance exists in a head changeset without unfiltered filerev
928 928 # children anywhere.
929 929 while delayed:
930 930 # must be a descending iteration. To slowly fill lowest child
931 931 # information that is of potential use by the next item.
932 932 fr, rev = delayed.pop()
933 933 lkr = rev
934 934
935 935 child = lowestchild.get(fr)
936 936
937 937 if child is None:
938 938 # search for existence of this file revision in a head revision.
939 939 # There are three possibilities:
940 940 # - the revision exists in a head and we can find an
941 941 # introduction from there,
942 942 # - the revision does not exist in a head because it has been
943 943 # changed since its introduction: we would have found a child
944 944 # and be in the other 'else' clause,
945 945 # - all versions of the revision are hidden.
946 946 if lowesthead is None:
947 947 lowesthead = {}
948 948 for h in repo.heads():
949 949 fnode = repo[h].manifest().get(f)
950 950 if fnode is not None:
951 951 lowesthead[fl.rev(fnode)] = h
952 952 headrev = lowesthead.get(fr)
953 953 if headrev is None:
954 954 # content is nowhere unfiltered
955 955 continue
956 956 rev = repo[headrev][f].introrev()
957 957 else:
958 958 # the lowest known child is a good upper bound
959 959 childcrev = backrevref[child]
960 960 # XXX this does not guarantee returning the lowest
961 961 # introduction of this revision, but this gives a
962 962 # result which is a good start and will fit in most
963 963 # cases. We probably need to fix the multiple
964 964 # introductions case properly (report each
965 965 # introduction, even for identical file revisions)
966 966 # once and for all at some point anyway.
967 967 for p in repo[childcrev][f].parents():
968 968 if p.filerev() == fr:
969 969 rev = p.rev()
970 970 break
971 971 if rev == lkr: # no shadowed entry found
972 972 # XXX This should never happen unless some manifest points
973 973 # to biggish file revisions (like a revision that uses a
974 974 # parent that never appears in the manifest ancestors)
975 975 continue
976 976
977 977 # Fill the data for the next iteration.
978 978 for p in fl.parentrevs(fr):
979 979 if 0 <= p and p not in lowestchild:
980 980 lowestchild[p] = fr
981 981 backrevref[fr] = rev
982 982 s.add(rev)
983 983
984 984 return subset & s
985 985
986 986 def first(repo, subset, x):
987 987 """``first(set, [n])``
988 988 An alias for limit().
989 989 """
990 990 return limit(repo, subset, x)
991 991
992 992 def _follow(repo, subset, x, name, followfirst=False):
993 993 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
994 994 c = repo['.']
995 995 if l:
996 996 x = getstring(l[0], _("%s expected a filename") % name)
997 997 if x in c:
998 998 cx = c[x]
999 999 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
1000 1000 # include the revision responsible for the most recent version
1001 1001 s.add(cx.introrev())
1002 1002 else:
1003 1003 return baseset()
1004 1004 else:
1005 1005 s = _revancestors(repo, baseset([c.rev()]), followfirst)
1006 1006
1007 1007 return subset & s
1008 1008
1009 1009 def follow(repo, subset, x):
1010 1010 """``follow([file])``
1011 1011 An alias for ``::.`` (ancestors of the working directory's first parent).
1012 1012 If a filename is specified, the history of the given file is followed,
1013 1013 including copies.
1014 1014 """
1015 1015 return _follow(repo, subset, x, 'follow')
1016 1016
1017 1017 def _followfirst(repo, subset, x):
1018 1018 # ``followfirst([file])``
1019 1019 # Like ``follow([file])`` but follows only the first parent of
1020 1020 # every revision or file revision.
1021 1021 return _follow(repo, subset, x, '_followfirst', followfirst=True)
1022 1022
1023 1023 def getall(repo, subset, x):
1024 1024 """``all()``
1025 1025 All changesets, the same as ``0:tip``.
1026 1026 """
1027 1027 # i18n: "all" is a keyword
1028 1028 getargs(x, 0, 0, _("all takes no arguments"))
1029 1029 return subset & spanset(repo) # drop "null" if any
1030 1030
1031 1031 def grep(repo, subset, x):
1032 1032 """``grep(regex)``
1033 1033 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
1034 1034 to ensure special escape characters are handled correctly. Unlike
1035 1035 ``keyword(string)``, the match is case-sensitive.
1036 1036 """
1037 1037 try:
1038 1038 # i18n: "grep" is a keyword
1039 1039 gr = re.compile(getstring(x, _("grep requires a string")))
1040 1040 except re.error as e:
1041 1041 raise error.ParseError(_('invalid match pattern: %s') % e)
1042 1042
1043 1043 def matches(x):
1044 1044 c = repo[x]
1045 1045 for e in c.files() + [c.user(), c.description()]:
1046 1046 if gr.search(e):
1047 1047 return True
1048 1048 return False
1049 1049
1050 1050 return subset.filter(matches)
1051 1051
1052 1052 def _matchfiles(repo, subset, x):
1053 1053 # _matchfiles takes a revset list of prefixed arguments:
1054 1054 #
1055 1055 # [p:foo, i:bar, x:baz]
1056 1056 #
1057 1057 # builds a match object from them and filters subset. Allowed
1058 1058 # prefixes are 'p:' for regular patterns, 'i:' for include
1059 1059 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
1060 1060 # a revision identifier, or the empty string to reference the
1061 1061 # working directory, from which the match object is
1062 1062 # initialized. Use 'd:' to set the default matching mode, default
1063 1063 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
1064 1064
1065 1065 # i18n: "_matchfiles" is a keyword
1066 1066 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
1067 1067 pats, inc, exc = [], [], []
1068 1068 rev, default = None, None
1069 1069 for arg in l:
1070 1070 # i18n: "_matchfiles" is a keyword
1071 1071 s = getstring(arg, _("_matchfiles requires string arguments"))
1072 1072 prefix, value = s[:2], s[2:]
1073 1073 if prefix == 'p:':
1074 1074 pats.append(value)
1075 1075 elif prefix == 'i:':
1076 1076 inc.append(value)
1077 1077 elif prefix == 'x:':
1078 1078 exc.append(value)
1079 1079 elif prefix == 'r:':
1080 1080 if rev is not None:
1081 1081 # i18n: "_matchfiles" is a keyword
1082 1082 raise error.ParseError(_('_matchfiles expected at most one '
1083 1083 'revision'))
1084 1084 if value != '': # empty means working directory; leave rev as None
1085 1085 rev = value
1086 1086 elif prefix == 'd:':
1087 1087 if default is not None:
1088 1088 # i18n: "_matchfiles" is a keyword
1089 1089 raise error.ParseError(_('_matchfiles expected at most one '
1090 1090 'default mode'))
1091 1091 default = value
1092 1092 else:
1093 1093 # i18n: "_matchfiles" is a keyword
1094 1094 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
1095 1095 if not default:
1096 1096 default = 'glob'
1097 1097
1098 1098 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
1099 1099 exclude=exc, ctx=repo[rev], default=default)
1100 1100
1101 1101 def matches(x):
1102 1102 for f in repo[x].files():
1103 1103 if m(f):
1104 1104 return True
1105 1105 return False
1106 1106
1107 1107 return subset.filter(matches)
1108 1108
1109 1109 def hasfile(repo, subset, x):
1110 1110 """``file(pattern)``
1111 1111 Changesets affecting files matched by pattern.
1112 1112
1113 1113 For a faster but less accurate result, consider using ``filelog()``
1114 1114 instead.
1115 1115
1116 1116 This predicate uses ``glob:`` as the default kind of pattern.
1117 1117 """
1118 1118 # i18n: "file" is a keyword
1119 1119 pat = getstring(x, _("file requires a pattern"))
1120 1120 return _matchfiles(repo, subset, ('string', 'p:' + pat))
1121 1121
1122 1122 def head(repo, subset, x):
1123 1123 """``head()``
1124 1124 Changeset is a named branch head.
1125 1125 """
1126 1126 # i18n: "head" is a keyword
1127 1127 getargs(x, 0, 0, _("head takes no arguments"))
1128 1128 hs = set()
1129 1129 cl = repo.changelog
1130 1130 for b, ls in repo.branchmap().iteritems():
1131 1131 hs.update(cl.rev(h) for h in ls)
1132 1132 # XXX using a set to feed the baseset is wrong. Sets are not ordered.
1133 1133 # This does not break because of other fullreposet misbehavior.
1134 1134 # XXX We should combine with subset first: 'subset & baseset(...)'. This is
1135 1135 # necessary to ensure we preserve the order in subset.
1136 1136 return baseset(hs) & subset
1137 1137
1138 1138 def heads(repo, subset, x):
1139 1139 """``heads(set)``
1140 1140 Members of set with no children in set.
1141 1141 """
1142 1142 s = getset(repo, subset, x)
1143 1143 ps = parents(repo, subset, x)
1144 1144 return s - ps
1145 1145
1146 1146 def hidden(repo, subset, x):
1147 1147 """``hidden()``
1148 1148 Hidden changesets.
1149 1149 """
1150 1150 # i18n: "hidden" is a keyword
1151 1151 getargs(x, 0, 0, _("hidden takes no arguments"))
1152 1152 hiddenrevs = repoview.filterrevs(repo, 'visible')
1153 1153 return subset & hiddenrevs
1154 1154
1155 1155 def keyword(repo, subset, x):
1156 1156 """``keyword(string)``
1157 1157 Search commit message, user name, and names of changed files for
1158 1158 string. The match is case-insensitive.
1159 1159 """
1160 1160 # i18n: "keyword" is a keyword
1161 1161 kw = encoding.lower(getstring(x, _("keyword requires a string")))
1162 1162
1163 1163 def matches(r):
1164 1164 c = repo[r]
1165 1165 return any(kw in encoding.lower(t)
1166 1166 for t in c.files() + [c.user(), c.description()])
1167 1167
1168 1168 return subset.filter(matches)
1169 1169
1170 1170 def limit(repo, subset, x):
1171 1171 """``limit(set, [n])``
1172 1172 First n members of set, defaulting to 1.
1173 1173 """
1174 1174 # i18n: "limit" is a keyword
1175 1175 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
1176 1176 try:
1177 1177 lim = 1
1178 1178 if len(l) == 2:
1179 1179 # i18n: "limit" is a keyword
1180 1180 lim = int(getstring(l[1], _("limit requires a number")))
1181 1181 except (TypeError, ValueError):
1182 1182 # i18n: "limit" is a keyword
1183 1183 raise error.ParseError(_("limit expects a number"))
1184 1184 ss = subset
1185 1185 os = getset(repo, fullreposet(repo), l[0])
1186 1186 result = []
1187 1187 it = iter(os)
1188 1188 for x in xrange(lim):
1189 1189 y = next(it, None)
1190 1190 if y is None:
1191 1191 break
1192 1192 elif y in ss:
1193 1193 result.append(y)
1194 1194 return baseset(result)
1195 1195
1196 1196 def last(repo, subset, x):
1197 1197 """``last(set, [n])``
1198 1198 Last n members of set, defaulting to 1.
1199 1199 """
1200 1200 # i18n: "last" is a keyword
1201 1201 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1202 1202 try:
1203 1203 lim = 1
1204 1204 if len(l) == 2:
1205 1205 # i18n: "last" is a keyword
1206 1206 lim = int(getstring(l[1], _("last requires a number")))
1207 1207 except (TypeError, ValueError):
1208 1208 # i18n: "last" is a keyword
1209 1209 raise error.ParseError(_("last expects a number"))
1210 1210 ss = subset
1211 1211 os = getset(repo, fullreposet(repo), l[0])
1212 1212 os.reverse()
1213 1213 result = []
1214 1214 it = iter(os)
1215 1215 for x in xrange(lim):
1216 1216 y = next(it, None)
1217 1217 if y is None:
1218 1218 break
1219 1219 elif y in ss:
1220 1220 result.append(y)
1221 1221 return baseset(result)
1222 1222
1223 1223 def maxrev(repo, subset, x):
1224 1224 """``max(set)``
1225 1225 Changeset with highest revision number in set.
1226 1226 """
1227 1227 os = getset(repo, fullreposet(repo), x)
1228 1228 if os:
1229 1229 m = os.max()
1230 1230 if m in subset:
1231 1231 return baseset([m])
1232 1232 return baseset()
1233 1233
1234 1234 def merge(repo, subset, x):
1235 1235 """``merge()``
1236 1236 Changeset is a merge changeset.
1237 1237 """
1238 1238 # i18n: "merge" is a keyword
1239 1239 getargs(x, 0, 0, _("merge takes no arguments"))
1240 1240 cl = repo.changelog
1241 1241 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1)
1242 1242
1243 1243 def branchpoint(repo, subset, x):
1244 1244 """``branchpoint()``
1245 1245 Changesets with more than one child.
1246 1246 """
1247 1247 # i18n: "branchpoint" is a keyword
1248 1248 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1249 1249 cl = repo.changelog
1250 1250 if not subset:
1251 1251 return baseset()
1252 1252 # XXX this should be 'parentset.min()' assuming 'parentset' is a smartset
1253 1253 # (and if it is not, it should.)
1254 1254 baserev = min(subset)
1255 1255 parentscount = [0]*(len(repo) - baserev)
1256 1256 for r in cl.revs(start=baserev + 1):
1257 1257 for p in cl.parentrevs(r):
1258 1258 if p >= baserev:
1259 1259 parentscount[p - baserev] += 1
1260 1260 return subset.filter(lambda r: parentscount[r - baserev] > 1)
1261 1261
1262 1262 def minrev(repo, subset, x):
1263 1263 """``min(set)``
1264 1264 Changeset with lowest revision number in set.
1265 1265 """
1266 1266 os = getset(repo, fullreposet(repo), x)
1267 1267 if os:
1268 1268 m = os.min()
1269 1269 if m in subset:
1270 1270 return baseset([m])
1271 1271 return baseset()
1272 1272
1273 1273 def modifies(repo, subset, x):
1274 1274 """``modifies(pattern)``
1275 1275 Changesets modifying files matched by pattern.
1276 1276
1277 1277 The pattern without explicit kind like ``glob:`` is expected to be
1278 1278 relative to the current directory and match against a file or a
1279 1279 directory.
1280 1280 """
1281 1281 # i18n: "modifies" is a keyword
1282 1282 pat = getstring(x, _("modifies requires a pattern"))
1283 1283 return checkstatus(repo, subset, pat, 0)
1284 1284
1285 1285 def named(repo, subset, x):
1286 1286 """``named(namespace)``
1287 1287 The changesets in a given namespace.
1288 1288
1289 1289 If `namespace` starts with `re:`, the remainder of the string is treated as
1290 1290 a regular expression. To match a namespace that actually starts with `re:`,
1291 1291 use the prefix `literal:`.
1292 1292 """
1293 1293 # i18n: "named" is a keyword
1294 1294 args = getargs(x, 1, 1, _('named requires a namespace argument'))
1295 1295
1296 1296 ns = getstring(args[0],
1297 1297 # i18n: "named" is a keyword
1298 1298 _('the argument to named must be a string'))
1299 1299 kind, pattern, matcher = _stringmatcher(ns)
1300 1300 namespaces = set()
1301 1301 if kind == 'literal':
1302 1302 if pattern not in repo.names:
1303 1303 raise error.RepoLookupError(_("namespace '%s' does not exist")
1304 1304 % ns)
1305 1305 namespaces.add(repo.names[pattern])
1306 1306 else:
1307 1307 for name, ns in repo.names.iteritems():
1308 1308 if matcher(name):
1309 1309 namespaces.add(ns)
1310 1310 if not namespaces:
1311 1311 raise error.RepoLookupError(_("no namespace exists"
1312 1312 " that match '%s'") % pattern)
1313 1313
1314 1314 names = set()
1315 1315 for ns in namespaces:
1316 1316 for name in ns.listnames(repo):
1317 1317 if name not in ns.deprecated:
1318 1318 names.update(repo[n].rev() for n in ns.nodes(repo, name))
1319 1319
1320 1320 names -= set([node.nullrev])
1321 1321 return subset & names
1322 1322
1323 1323 def node_(repo, subset, x):
1324 1324 """``id(string)``
1325 1325 Revision non-ambiguously specified by the given hex string prefix.
1326 1326 """
1327 1327 # i18n: "id" is a keyword
1328 1328 l = getargs(x, 1, 1, _("id requires one argument"))
1329 1329 # i18n: "id" is a keyword
1330 1330 n = getstring(l[0], _("id requires a string"))
1331 1331 if len(n) == 40:
1332 1332 try:
1333 1333 rn = repo.changelog.rev(node.bin(n))
1334 1334 except (LookupError, TypeError):
1335 1335 rn = None
1336 1336 else:
1337 1337 rn = None
1338 1338 pm = repo.changelog._partialmatch(n)
1339 1339 if pm is not None:
1340 1340 rn = repo.changelog.rev(pm)
1341 1341
1342 1342 if rn is None:
1343 1343 return baseset()
1344 1344 result = baseset([rn])
1345 1345 return result & subset
1346 1346
1347 1347 def obsolete(repo, subset, x):
1348 1348 """``obsolete()``
1349 1349 Mutable changeset with a newer version."""
1350 1350 # i18n: "obsolete" is a keyword
1351 1351 getargs(x, 0, 0, _("obsolete takes no arguments"))
1352 1352 obsoletes = obsmod.getrevs(repo, 'obsolete')
1353 1353 return subset & obsoletes
1354 1354
1355 1355 def only(repo, subset, x):
1356 1356 """``only(set, [set])``
1357 1357 Changesets that are ancestors of the first set that are not ancestors
1358 1358 of any other head in the repo. If a second set is specified, the result
1359 1359 is ancestors of the first set that are not ancestors of the second set
1360 1360 (i.e. ::<set1> - ::<set2>).
1361 1361 """
1362 1362 cl = repo.changelog
1363 1363 # i18n: "only" is a keyword
1364 1364 args = getargs(x, 1, 2, _('only takes one or two arguments'))
1365 1365 include = getset(repo, fullreposet(repo), args[0])
1366 1366 if len(args) == 1:
1367 1367 if not include:
1368 1368 return baseset()
1369 1369
1370 1370 descendants = set(_revdescendants(repo, include, False))
1371 1371 exclude = [rev for rev in cl.headrevs()
1372 1372 if not rev in descendants and not rev in include]
1373 1373 else:
1374 1374 exclude = getset(repo, fullreposet(repo), args[1])
1375 1375
1376 1376 results = set(cl.findmissingrevs(common=exclude, heads=include))
1377 1377 # XXX we should turn this into a baseset instead of a set, smartset may do
1378 1378 # some optimisations from the fact this is a baseset.
1379 1379 return subset & results
1380 1380
1381 1381 def origin(repo, subset, x):
1382 1382 """``origin([set])``
1383 1383 Changesets that were specified as a source for the grafts, transplants or
1384 1384 rebases that created the given revisions. Omitting the optional set is the
1385 1385 same as passing all(). If a changeset created by these operations is itself
1386 1386 specified as a source for one of these operations, only the source changeset
1387 1387 for the first operation is selected.
1388 1388 """
1389 1389 if x is not None:
1390 1390 dests = getset(repo, fullreposet(repo), x)
1391 1391 else:
1392 1392 dests = fullreposet(repo)
1393 1393
1394 1394 def _firstsrc(rev):
1395 1395 src = _getrevsource(repo, rev)
1396 1396 if src is None:
1397 1397 return None
1398 1398
1399 1399 while True:
1400 1400 prev = _getrevsource(repo, src)
1401 1401
1402 1402 if prev is None:
1403 1403 return src
1404 1404 src = prev
1405 1405
1406 1406 o = set([_firstsrc(r) for r in dests])
1407 1407 o -= set([None])
1408 1408 # XXX we should turn this into a baseset instead of a set, smartset may do
1409 1409 # some optimisations from the fact this is a baseset.
1410 1410 return subset & o
1411 1411
1412 1412 def outgoing(repo, subset, x):
1413 1413 """``outgoing([path])``
1414 1414 Changesets not found in the specified destination repository, or the
1415 1415 default push location.
1416 1416 """
1417 1417 # Avoid cycles.
1418 1418 import discovery
1419 1419 import hg
1420 1420 # i18n: "outgoing" is a keyword
1421 1421 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1422 1422 # i18n: "outgoing" is a keyword
1423 1423 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1424 1424 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1425 1425 dest, branches = hg.parseurl(dest)
1426 1426 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1427 1427 if revs:
1428 1428 revs = [repo.lookup(rev) for rev in revs]
1429 1429 other = hg.peer(repo, {}, dest)
1430 1430 repo.ui.pushbuffer()
1431 1431 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1432 1432 repo.ui.popbuffer()
1433 1433 cl = repo.changelog
1434 1434 o = set([cl.rev(r) for r in outgoing.missing])
1435 1435 return subset & o
1436 1436
1437 1437 def p1(repo, subset, x):
1438 1438 """``p1([set])``
1439 1439 First parent of changesets in set, or the working directory.
1440 1440 """
1441 1441 if x is None:
1442 1442 p = repo[x].p1().rev()
1443 1443 if p >= 0:
1444 1444 return subset & baseset([p])
1445 1445 return baseset()
1446 1446
1447 1447 ps = set()
1448 1448 cl = repo.changelog
1449 1449 for r in getset(repo, fullreposet(repo), x):
1450 1450 ps.add(cl.parentrevs(r)[0])
1451 1451 ps -= set([node.nullrev])
1452 1452 # XXX we should turn this into a baseset instead of a set, smartset may do
1453 1453 # some optimisations from the fact this is a baseset.
1454 1454 return subset & ps
1455 1455
1456 1456 def p2(repo, subset, x):
1457 1457 """``p2([set])``
1458 1458 Second parent of changesets in set, or the working directory.
1459 1459 """
1460 1460 if x is None:
1461 1461 ps = repo[x].parents()
1462 1462 try:
1463 1463 p = ps[1].rev()
1464 1464 if p >= 0:
1465 1465 return subset & baseset([p])
1466 1466 return baseset()
1467 1467 except IndexError:
1468 1468 return baseset()
1469 1469
1470 1470 ps = set()
1471 1471 cl = repo.changelog
1472 1472 for r in getset(repo, fullreposet(repo), x):
1473 1473 ps.add(cl.parentrevs(r)[1])
1474 1474 ps -= set([node.nullrev])
1475 1475 # XXX we should turn this into a baseset instead of a set, smartset may do
1476 1476 # some optimisations from the fact this is a baseset.
1477 1477 return subset & ps
1478 1478
1479 1479 def parents(repo, subset, x):
1480 1480 """``parents([set])``
1481 1481 The set of all parents for all changesets in set, or the working directory.
1482 1482 """
1483 1483 if x is None:
1484 1484 ps = set(p.rev() for p in repo[x].parents())
1485 1485 else:
1486 1486 ps = set()
1487 1487 cl = repo.changelog
1488 1488 up = ps.update
1489 1489 parentrevs = cl.parentrevs
1490 1490 for r in getset(repo, fullreposet(repo), x):
1491 1491 if r == node.wdirrev:
1492 1492 up(p.rev() for p in repo[r].parents())
1493 1493 else:
1494 1494 up(parentrevs(r))
1495 1495 ps -= set([node.nullrev])
1496 1496 return subset & ps
1497 1497
1498 1498 def _phase(repo, subset, target):
1499 1499 """helper to select all rev in phase <target>"""
1500 1500 repo._phasecache.loadphaserevs(repo) # ensure phase's sets are loaded
1501 1501 if repo._phasecache._phasesets:
1502 1502 s = repo._phasecache._phasesets[target] - repo.changelog.filteredrevs
1503 1503 s = baseset(s)
1504 1504 s.sort() # set are non ordered, so we enforce ascending
1505 1505 return subset & s
1506 1506 else:
1507 1507 phase = repo._phasecache.phase
1508 1508 condition = lambda r: phase(repo, r) == target
1509 1509 return subset.filter(condition, cache=False)
1510 1510
1511 1511 def draft(repo, subset, x):
1512 1512 """``draft()``
1513 1513 Changeset in draft phase."""
1514 1514 # i18n: "draft" is a keyword
1515 1515 getargs(x, 0, 0, _("draft takes no arguments"))
1516 1516 target = phases.draft
1517 1517 return _phase(repo, subset, target)
1518 1518
1519 1519 def secret(repo, subset, x):
1520 1520 """``secret()``
1521 1521 Changeset in secret phase."""
1522 1522 # i18n: "secret" is a keyword
1523 1523 getargs(x, 0, 0, _("secret takes no arguments"))
1524 1524 target = phases.secret
1525 1525 return _phase(repo, subset, target)
1526 1526
1527 1527 def parentspec(repo, subset, x, n):
1528 1528 """``set^0``
1529 1529 The set.
1530 1530 ``set^1`` (or ``set^``), ``set^2``
1531 1531 First or second parent, respectively, of all changesets in set.
1532 1532 """
1533 1533 try:
1534 1534 n = int(n[1])
1535 1535 if n not in (0, 1, 2):
1536 1536 raise ValueError
1537 1537 except (TypeError, ValueError):
1538 1538 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1539 1539 ps = set()
1540 1540 cl = repo.changelog
1541 1541 for r in getset(repo, fullreposet(repo), x):
1542 1542 if n == 0:
1543 1543 ps.add(r)
1544 1544 elif n == 1:
1545 1545 ps.add(cl.parentrevs(r)[0])
1546 1546 elif n == 2:
1547 1547 parents = cl.parentrevs(r)
1548 1548 if len(parents) > 1:
1549 1549 ps.add(parents[1])
1550 1550 return subset & ps
1551 1551
1552 1552 def present(repo, subset, x):
1553 1553 """``present(set)``
1554 1554 An empty set, if any revision in set isn't found; otherwise,
1555 1555 all revisions in set.
1556 1556
1557 1557 If any of specified revisions is not present in the local repository,
1558 1558 the query is normally aborted. But this predicate allows the query
1559 1559 to continue even in such cases.
1560 1560 """
1561 1561 try:
1562 1562 return getset(repo, subset, x)
1563 1563 except error.RepoLookupError:
1564 1564 return baseset()
1565 1565
1566 1566 # for internal use
1567 1567 def _notpublic(repo, subset, x):
1568 1568 getargs(x, 0, 0, "_notpublic takes no arguments")
1569 1569 repo._phasecache.loadphaserevs(repo) # ensure phase's sets are loaded
1570 1570 if repo._phasecache._phasesets:
1571 1571 s = set()
1572 1572 for u in repo._phasecache._phasesets[1:]:
1573 1573 s.update(u)
1574 1574 s = baseset(s - repo.changelog.filteredrevs)
1575 1575 s.sort()
1576 1576 return subset & s
1577 1577 else:
1578 1578 phase = repo._phasecache.phase
1579 1579 target = phases.public
1580 1580 condition = lambda r: phase(repo, r) != target
1581 1581 return subset.filter(condition, cache=False)
1582 1582
1583 1583 def public(repo, subset, x):
1584 1584 """``public()``
1585 1585 Changeset in public phase."""
1586 1586 # i18n: "public" is a keyword
1587 1587 getargs(x, 0, 0, _("public takes no arguments"))
1588 1588 phase = repo._phasecache.phase
1589 1589 target = phases.public
1590 1590 condition = lambda r: phase(repo, r) == target
1591 1591 return subset.filter(condition, cache=False)
1592 1592
1593 1593 def remote(repo, subset, x):
1594 1594 """``remote([id [,path]])``
1595 1595 Local revision that corresponds to the given identifier in a
1596 1596 remote repository, if present. Here, the '.' identifier is a
1597 1597 synonym for the current local branch.
1598 1598 """
1599 1599
1600 1600 import hg # avoid start-up nasties
1601 1601 # i18n: "remote" is a keyword
1602 1602 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1603 1603
1604 1604 q = '.'
1605 1605 if len(l) > 0:
1606 1606 # i18n: "remote" is a keyword
1607 1607 q = getstring(l[0], _("remote requires a string id"))
1608 1608 if q == '.':
1609 1609 q = repo['.'].branch()
1610 1610
1611 1611 dest = ''
1612 1612 if len(l) > 1:
1613 1613 # i18n: "remote" is a keyword
1614 1614 dest = getstring(l[1], _("remote requires a repository path"))
1615 1615 dest = repo.ui.expandpath(dest or 'default')
1616 1616 dest, branches = hg.parseurl(dest)
1617 1617 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1618 1618 if revs:
1619 1619 revs = [repo.lookup(rev) for rev in revs]
1620 1620 other = hg.peer(repo, {}, dest)
1621 1621 n = other.lookup(q)
1622 1622 if n in repo:
1623 1623 r = repo[n].rev()
1624 1624 if r in subset:
1625 1625 return baseset([r])
1626 1626 return baseset()
1627 1627
1628 1628 def removes(repo, subset, x):
1629 1629 """``removes(pattern)``
1630 1630 Changesets which remove files matching pattern.
1631 1631
1632 1632 The pattern without explicit kind like ``glob:`` is expected to be
1633 1633 relative to the current directory and match against a file or a
1634 1634 directory.
1635 1635 """
1636 1636 # i18n: "removes" is a keyword
1637 1637 pat = getstring(x, _("removes requires a pattern"))
1638 1638 return checkstatus(repo, subset, pat, 2)
1639 1639
1640 1640 def rev(repo, subset, x):
1641 1641 """``rev(number)``
1642 1642 Revision with the given numeric identifier.
1643 1643 """
1644 1644 # i18n: "rev" is a keyword
1645 1645 l = getargs(x, 1, 1, _("rev requires one argument"))
1646 1646 try:
1647 1647 # i18n: "rev" is a keyword
1648 1648 l = int(getstring(l[0], _("rev requires a number")))
1649 1649 except (TypeError, ValueError):
1650 1650 # i18n: "rev" is a keyword
1651 1651 raise error.ParseError(_("rev expects a number"))
1652 1652 if l not in repo.changelog and l != node.nullrev:
1653 1653 return baseset()
1654 1654 return subset & baseset([l])
1655 1655
1656 1656 def matching(repo, subset, x):
1657 1657 """``matching(revision [, field])``
1658 1658 Changesets in which a given set of fields match the set of fields in the
1659 1659 selected revision or set.
1660 1660
1661 1661 To match more than one field pass the list of fields to match separated
1662 1662 by spaces (e.g. ``author description``).
1663 1663
1664 1664 Valid fields are most regular revision fields and some special fields.
1665 1665
1666 1666 Regular revision fields are ``description``, ``author``, ``branch``,
1667 1667 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1668 1668 and ``diff``.
1669 1669 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1670 1670 contents of the revision. Two revisions matching their ``diff`` will
1671 1671 also match their ``files``.
1672 1672
1673 1673 Special fields are ``summary`` and ``metadata``:
1674 1674 ``summary`` matches the first line of the description.
1675 1675 ``metadata`` is equivalent to matching ``description user date``
1676 1676 (i.e. it matches the main metadata fields).
1677 1677
1678 1678 ``metadata`` is the default field which is used when no fields are
1679 1679 specified. You can match more than one field at a time.
1680 1680 """
1681 1681 # i18n: "matching" is a keyword
1682 1682 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1683 1683
1684 1684 revs = getset(repo, fullreposet(repo), l[0])
1685 1685
1686 1686 fieldlist = ['metadata']
1687 1687 if len(l) > 1:
1688 1688 fieldlist = getstring(l[1],
1689 1689 # i18n: "matching" is a keyword
1690 1690 _("matching requires a string "
1691 1691 "as its second argument")).split()
1692 1692
1693 1693 # Make sure that there are no repeated fields,
1694 1694 # expand the 'special' 'metadata' field type
1695 1695 # and check the 'files' whenever we check the 'diff'
1696 1696 fields = []
1697 1697 for field in fieldlist:
1698 1698 if field == 'metadata':
1699 1699 fields += ['user', 'description', 'date']
1700 1700 elif field == 'diff':
1701 1701 # a revision matching the diff must also match the files
1702 1702 # since matching the diff is very costly, make sure to
1703 1703 # also match the files first
1704 1704 fields += ['files', 'diff']
1705 1705 else:
1706 1706 if field == 'author':
1707 1707 field = 'user'
1708 1708 fields.append(field)
1709 1709 fields = set(fields)
1710 1710 if 'summary' in fields and 'description' in fields:
1711 1711 # If a revision matches its description it also matches its summary
1712 1712 fields.discard('summary')
1713 1713
1714 1714 # We may want to match more than one field
1715 1715 # Not all fields take the same amount of time to be matched
1716 1716 # Sort the selected fields in order of increasing matching cost
1717 1717 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1718 1718 'files', 'description', 'substate', 'diff']
1719 1719 def fieldkeyfunc(f):
1720 1720 try:
1721 1721 return fieldorder.index(f)
1722 1722 except ValueError:
1723 1723 # assume an unknown field is very costly
1724 1724 return len(fieldorder)
1725 1725 fields = list(fields)
1726 1726 fields.sort(key=fieldkeyfunc)
1727 1727
1728 1728 # Each field will be matched with its own "getfield" function
1729 1729 # which will be added to the getfieldfuncs array of functions
1730 1730 getfieldfuncs = []
1731 1731 _funcs = {
1732 1732 'user': lambda r: repo[r].user(),
1733 1733 'branch': lambda r: repo[r].branch(),
1734 1734 'date': lambda r: repo[r].date(),
1735 1735 'description': lambda r: repo[r].description(),
1736 1736 'files': lambda r: repo[r].files(),
1737 1737 'parents': lambda r: repo[r].parents(),
1738 1738 'phase': lambda r: repo[r].phase(),
1739 1739 'substate': lambda r: repo[r].substate,
1740 1740 'summary': lambda r: repo[r].description().splitlines()[0],
1741 1741 'diff': lambda r: list(repo[r].diff(git=True),)
1742 1742 }
1743 1743 for info in fields:
1744 1744 getfield = _funcs.get(info, None)
1745 1745 if getfield is None:
1746 1746 raise error.ParseError(
1747 1747 # i18n: "matching" is a keyword
1748 1748 _("unexpected field name passed to matching: %s") % info)
1749 1749 getfieldfuncs.append(getfield)
1750 1750 # convert the getfield array of functions into a "getinfo" function
1751 1751 # which returns an array of field values (or a single value if there
1752 1752 # is only one field to match)
1753 1753 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1754 1754
1755 1755 def matches(x):
1756 1756 for rev in revs:
1757 1757 target = getinfo(rev)
1758 1758 match = True
1759 1759 for n, f in enumerate(getfieldfuncs):
1760 1760 if target[n] != f(x):
1761 1761 match = False
1762 1762 if match:
1763 1763 return True
1764 1764 return False
1765 1765
1766 1766 return subset.filter(matches)
1767 1767
1768 1768 def reverse(repo, subset, x):
1769 1769 """``reverse(set)``
1770 1770 Reverse order of set.
1771 1771 """
1772 1772 l = getset(repo, subset, x)
1773 1773 l.reverse()
1774 1774 return l
1775 1775
1776 1776 def roots(repo, subset, x):
1777 1777 """``roots(set)``
1778 1778 Changesets in set with no parent changeset in set.
1779 1779 """
1780 1780 s = getset(repo, fullreposet(repo), x)
1781 1781 parents = repo.changelog.parentrevs
1782 1782 def filter(r):
1783 1783 for p in parents(r):
1784 1784 if 0 <= p and p in s:
1785 1785 return False
1786 1786 return True
1787 1787 return subset & s.filter(filter)
1788 1788
1789 1789 def sort(repo, subset, x):
1790 1790 """``sort(set[, [-]key...])``
1791 1791 Sort set by keys. The default sort order is ascending, specify a key
1792 1792 as ``-key`` to sort in descending order.
1793 1793
1794 1794 The keys can be:
1795 1795
1796 1796 - ``rev`` for the revision number,
1797 1797 - ``branch`` for the branch name,
1798 1798 - ``desc`` for the commit message (description),
1799 1799 - ``user`` for user name (``author`` can be used as an alias),
1800 1800 - ``date`` for the commit date
1801 1801 """
1802 1802 # i18n: "sort" is a keyword
1803 1803 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1804 1804 keys = "rev"
1805 1805 if len(l) == 2:
1806 1806 # i18n: "sort" is a keyword
1807 1807 keys = getstring(l[1], _("sort spec must be a string"))
1808 1808
1809 1809 s = l[0]
1810 1810 keys = keys.split()
1811 1811 l = []
1812 1812 def invert(s):
1813 1813 return "".join(chr(255 - ord(c)) for c in s)
1814 1814 revs = getset(repo, subset, s)
1815 1815 if keys == ["rev"]:
1816 1816 revs.sort()
1817 1817 return revs
1818 1818 elif keys == ["-rev"]:
1819 1819 revs.sort(reverse=True)
1820 1820 return revs
1821 1821 for r in revs:
1822 1822 c = repo[r]
1823 1823 e = []
1824 1824 for k in keys:
1825 1825 if k == 'rev':
1826 1826 e.append(r)
1827 1827 elif k == '-rev':
1828 1828 e.append(-r)
1829 1829 elif k == 'branch':
1830 1830 e.append(c.branch())
1831 1831 elif k == '-branch':
1832 1832 e.append(invert(c.branch()))
1833 1833 elif k == 'desc':
1834 1834 e.append(c.description())
1835 1835 elif k == '-desc':
1836 1836 e.append(invert(c.description()))
1837 1837 elif k in 'user author':
1838 1838 e.append(c.user())
1839 1839 elif k in '-user -author':
1840 1840 e.append(invert(c.user()))
1841 1841 elif k == 'date':
1842 1842 e.append(c.date()[0])
1843 1843 elif k == '-date':
1844 1844 e.append(-c.date()[0])
1845 1845 else:
1846 1846 raise error.ParseError(_("unknown sort key %r") % k)
1847 1847 e.append(r)
1848 1848 l.append(e)
1849 1849 l.sort()
1850 1850 return baseset([e[-1] for e in l])
1851 1851
1852 1852 def subrepo(repo, subset, x):
1853 1853 """``subrepo([pattern])``
1854 1854 Changesets that add, modify or remove the given subrepo. If no subrepo
1855 1855 pattern is named, any subrepo changes are returned.
1856 1856 """
1857 1857 # i18n: "subrepo" is a keyword
1858 1858 args = getargs(x, 0, 1, _('subrepo takes at most one argument'))
1859 1859 if len(args) != 0:
1860 1860 pat = getstring(args[0], _("subrepo requires a pattern"))
1861 1861
1862 1862 m = matchmod.exact(repo.root, repo.root, ['.hgsubstate'])
1863 1863
1864 1864 def submatches(names):
1865 1865 k, p, m = _stringmatcher(pat)
1866 1866 for name in names:
1867 1867 if m(name):
1868 1868 yield name
1869 1869
1870 1870 def matches(x):
1871 1871 c = repo[x]
1872 1872 s = repo.status(c.p1().node(), c.node(), match=m)
1873 1873
1874 1874 if len(args) == 0:
1875 1875 return s.added or s.modified or s.removed
1876 1876
1877 1877 if s.added:
1878 1878 return any(submatches(c.substate.keys()))
1879 1879
1880 1880 if s.modified:
1881 1881 subs = set(c.p1().substate.keys())
1882 1882 subs.update(c.substate.keys())
1883 1883
1884 1884 for path in submatches(subs):
1885 1885 if c.p1().substate.get(path) != c.substate.get(path):
1886 1886 return True
1887 1887
1888 1888 if s.removed:
1889 1889 return any(submatches(c.p1().substate.keys()))
1890 1890
1891 1891 return False
1892 1892
1893 1893 return subset.filter(matches)
1894 1894
1895 1895 def _stringmatcher(pattern):
1896 1896 """
1897 1897 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1898 1898 returns the matcher name, pattern, and matcher function.
1899 1899 missing or unknown prefixes are treated as literal matches.
1900 1900
1901 1901 helper for tests:
1902 1902 >>> def test(pattern, *tests):
1903 1903 ... kind, pattern, matcher = _stringmatcher(pattern)
1904 1904 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1905 1905
1906 1906 exact matching (no prefix):
1907 1907 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1908 1908 ('literal', 'abcdefg', [False, False, True])
1909 1909
1910 1910 regex matching ('re:' prefix)
1911 1911 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1912 1912 ('re', 'a.+b', [False, False, True])
1913 1913
1914 1914 force exact matches ('literal:' prefix)
1915 1915 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1916 1916 ('literal', 're:foobar', [False, True])
1917 1917
1918 1918 unknown prefixes are ignored and treated as literals
1919 1919 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1920 1920 ('literal', 'foo:bar', [False, False, True])
1921 1921 """
1922 1922 if pattern.startswith('re:'):
1923 1923 pattern = pattern[3:]
1924 1924 try:
1925 1925 regex = re.compile(pattern)
1926 1926 except re.error as e:
1927 1927 raise error.ParseError(_('invalid regular expression: %s')
1928 1928 % e)
1929 1929 return 're', pattern, regex.search
1930 1930 elif pattern.startswith('literal:'):
1931 1931 pattern = pattern[8:]
1932 1932 return 'literal', pattern, pattern.__eq__
1933 1933
1934 1934 def _substringmatcher(pattern):
1935 1935 kind, pattern, matcher = _stringmatcher(pattern)
1936 1936 if kind == 'literal':
1937 1937 matcher = lambda s: pattern in s
1938 1938 return kind, pattern, matcher
1939 1939
1940 1940 def tag(repo, subset, x):
1941 1941 """``tag([name])``
1942 1942 The specified tag by name, or all tagged revisions if no name is given.
1943 1943
1944 1944 If `name` starts with `re:`, the remainder of the name is treated as
1945 1945 a regular expression. To match a tag that actually starts with `re:`,
1946 1946 use the prefix `literal:`.
1947 1947 """
1948 1948 # i18n: "tag" is a keyword
1949 1949 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1950 1950 cl = repo.changelog
1951 1951 if args:
1952 1952 pattern = getstring(args[0],
1953 1953 # i18n: "tag" is a keyword
1954 1954 _('the argument to tag must be a string'))
1955 1955 kind, pattern, matcher = _stringmatcher(pattern)
1956 1956 if kind == 'literal':
1957 1957 # avoid resolving all tags
1958 1958 tn = repo._tagscache.tags.get(pattern, None)
1959 1959 if tn is None:
1960 1960 raise error.RepoLookupError(_("tag '%s' does not exist")
1961 1961 % pattern)
1962 1962 s = set([repo[tn].rev()])
1963 1963 else:
1964 1964 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1965 1965 else:
1966 1966 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1967 1967 return subset & s
1968 1968
1969 1969 def tagged(repo, subset, x):
1970 1970 return tag(repo, subset, x)
1971 1971
1972 1972 def unstable(repo, subset, x):
1973 1973 """``unstable()``
1974 1974 Non-obsolete changesets with obsolete ancestors.
1975 1975 """
1976 1976 # i18n: "unstable" is a keyword
1977 1977 getargs(x, 0, 0, _("unstable takes no arguments"))
1978 1978 unstables = obsmod.getrevs(repo, 'unstable')
1979 1979 return subset & unstables
1980 1980
1981 1981
1982 1982 def user(repo, subset, x):
1983 1983 """``user(string)``
1984 1984 User name contains string. The match is case-insensitive.
1985 1985
1986 1986 If `string` starts with `re:`, the remainder of the string is treated as
1987 1987 a regular expression. To match a user that actually contains `re:`, use
1988 1988 the prefix `literal:`.
1989 1989 """
1990 1990 return author(repo, subset, x)
1991 1991
1992 1992 # experimental
1993 1993 def wdir(repo, subset, x):
1994 1994 # i18n: "wdir" is a keyword
1995 1995 getargs(x, 0, 0, _("wdir takes no arguments"))
1996 1996 if node.wdirrev in subset or isinstance(subset, fullreposet):
1997 1997 return baseset([node.wdirrev])
1998 1998 return baseset()
1999 1999
2000 2000 # for internal use
2001 2001 def _list(repo, subset, x):
2002 2002 s = getstring(x, "internal error")
2003 2003 if not s:
2004 2004 return baseset()
2005 2005 # remove duplicates here. it's difficult for caller to deduplicate sets
2006 2006 # because different symbols can point to the same rev.
2007 2007 cl = repo.changelog
2008 2008 ls = []
2009 2009 seen = set()
2010 2010 for t in s.split('\0'):
2011 2011 try:
2012 2012 # fast path for integer revision
2013 2013 r = int(t)
2014 2014 if str(r) != t or r not in cl:
2015 2015 raise ValueError
2016 2016 except ValueError:
2017 2017 r = repo[t].rev()
2018 2018 if r in seen:
2019 2019 continue
2020 2020 if (r in subset
2021 2021 or r == node.nullrev and isinstance(subset, fullreposet)):
2022 2022 ls.append(r)
2023 2023 seen.add(r)
2024 2024 return baseset(ls)
2025 2025
2026 2026 # for internal use
2027 2027 def _intlist(repo, subset, x):
2028 2028 s = getstring(x, "internal error")
2029 2029 if not s:
2030 2030 return baseset()
2031 2031 ls = [int(r) for r in s.split('\0')]
2032 2032 s = subset
2033 2033 return baseset([r for r in ls if r in s])
2034 2034
2035 2035 # for internal use
2036 2036 def _hexlist(repo, subset, x):
2037 2037 s = getstring(x, "internal error")
2038 2038 if not s:
2039 2039 return baseset()
2040 2040 cl = repo.changelog
2041 2041 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
2042 2042 s = subset
2043 2043 return baseset([r for r in ls if r in s])
2044 2044
2045 2045 symbols = {
2046 2046 "adds": adds,
2047 2047 "all": getall,
2048 2048 "ancestor": ancestor,
2049 2049 "ancestors": ancestors,
2050 2050 "_firstancestors": _firstancestors,
2051 2051 "author": author,
2052 2052 "bisect": bisect,
2053 2053 "bisected": bisected,
2054 2054 "bookmark": bookmark,
2055 2055 "branch": branch,
2056 2056 "branchpoint": branchpoint,
2057 2057 "bumped": bumped,
2058 2058 "bundle": bundle,
2059 2059 "children": children,
2060 2060 "closed": closed,
2061 2061 "contains": contains,
2062 2062 "converted": converted,
2063 2063 "date": date,
2064 2064 "desc": desc,
2065 2065 "descendants": descendants,
2066 2066 "_firstdescendants": _firstdescendants,
2067 2067 "destination": destination,
2068 2068 "divergent": divergent,
2069 2069 "draft": draft,
2070 2070 "extinct": extinct,
2071 2071 "extra": extra,
2072 2072 "file": hasfile,
2073 2073 "filelog": filelog,
2074 2074 "first": first,
2075 2075 "follow": follow,
2076 2076 "_followfirst": _followfirst,
2077 2077 "grep": grep,
2078 2078 "head": head,
2079 2079 "heads": heads,
2080 2080 "hidden": hidden,
2081 2081 "id": node_,
2082 2082 "keyword": keyword,
2083 2083 "last": last,
2084 2084 "limit": limit,
2085 2085 "_matchfiles": _matchfiles,
2086 2086 "max": maxrev,
2087 2087 "merge": merge,
2088 2088 "min": minrev,
2089 2089 "modifies": modifies,
2090 2090 "named": named,
2091 2091 "obsolete": obsolete,
2092 2092 "only": only,
2093 2093 "origin": origin,
2094 2094 "outgoing": outgoing,
2095 2095 "p1": p1,
2096 2096 "p2": p2,
2097 2097 "parents": parents,
2098 2098 "present": present,
2099 2099 "public": public,
2100 2100 "_notpublic": _notpublic,
2101 2101 "remote": remote,
2102 2102 "removes": removes,
2103 2103 "rev": rev,
2104 2104 "reverse": reverse,
2105 2105 "roots": roots,
2106 2106 "sort": sort,
2107 2107 "secret": secret,
2108 2108 "subrepo": subrepo,
2109 2109 "matching": matching,
2110 2110 "tag": tag,
2111 2111 "tagged": tagged,
2112 2112 "user": user,
2113 2113 "unstable": unstable,
2114 2114 "wdir": wdir,
2115 2115 "_list": _list,
2116 2116 "_intlist": _intlist,
2117 2117 "_hexlist": _hexlist,
2118 2118 }
2119 2119
2120 2120 # symbols which can't be used for a DoS attack for any given input
2121 2121 # (e.g. those which accept regexes as plain strings shouldn't be included)
2122 2122 # functions that just return a lot of changesets (like all) don't count here
2123 2123 safesymbols = set([
2124 2124 "adds",
2125 2125 "all",
2126 2126 "ancestor",
2127 2127 "ancestors",
2128 2128 "_firstancestors",
2129 2129 "author",
2130 2130 "bisect",
2131 2131 "bisected",
2132 2132 "bookmark",
2133 2133 "branch",
2134 2134 "branchpoint",
2135 2135 "bumped",
2136 2136 "bundle",
2137 2137 "children",
2138 2138 "closed",
2139 2139 "converted",
2140 2140 "date",
2141 2141 "desc",
2142 2142 "descendants",
2143 2143 "_firstdescendants",
2144 2144 "destination",
2145 2145 "divergent",
2146 2146 "draft",
2147 2147 "extinct",
2148 2148 "extra",
2149 2149 "file",
2150 2150 "filelog",
2151 2151 "first",
2152 2152 "follow",
2153 2153 "_followfirst",
2154 2154 "head",
2155 2155 "heads",
2156 2156 "hidden",
2157 2157 "id",
2158 2158 "keyword",
2159 2159 "last",
2160 2160 "limit",
2161 2161 "_matchfiles",
2162 2162 "max",
2163 2163 "merge",
2164 2164 "min",
2165 2165 "modifies",
2166 2166 "obsolete",
2167 2167 "only",
2168 2168 "origin",
2169 2169 "outgoing",
2170 2170 "p1",
2171 2171 "p2",
2172 2172 "parents",
2173 2173 "present",
2174 2174 "public",
2175 2175 "_notpublic",
2176 2176 "remote",
2177 2177 "removes",
2178 2178 "rev",
2179 2179 "reverse",
2180 2180 "roots",
2181 2181 "sort",
2182 2182 "secret",
2183 2183 "matching",
2184 2184 "tag",
2185 2185 "tagged",
2186 2186 "user",
2187 2187 "unstable",
2188 2188 "wdir",
2189 2189 "_list",
2190 2190 "_intlist",
2191 2191 "_hexlist",
2192 2192 ])
2193 2193
2194 2194 methods = {
2195 2195 "range": rangeset,
2196 2196 "dagrange": dagrange,
2197 2197 "string": stringset,
2198 2198 "symbol": stringset,
2199 2199 "and": andset,
2200 2200 "or": orset,
2201 2201 "not": notset,
2202 2202 "list": listset,
2203 2203 "keyvalue": keyvaluepair,
2204 2204 "func": func,
2205 2205 "ancestor": ancestorspec,
2206 2206 "parent": parentspec,
2207 2207 "parentpost": p1,
2208 2208 }
2209 2209
2210 2210 def optimize(x, small):
2211 2211 if x is None:
2212 2212 return 0, x
2213 2213
2214 2214 smallbonus = 1
2215 2215 if small:
2216 2216 smallbonus = .5
2217 2217
2218 2218 op = x[0]
2219 2219 if op == 'minus':
2220 2220 return optimize(('and', x[1], ('not', x[2])), small)
2221 2221 elif op == 'only':
2222 2222 return optimize(('func', ('symbol', 'only'),
2223 2223 ('list', x[1], x[2])), small)
2224 2224 elif op == 'onlypost':
2225 2225 return optimize(('func', ('symbol', 'only'), x[1]), small)
2226 2226 elif op == 'dagrangepre':
2227 2227 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
2228 2228 elif op == 'dagrangepost':
2229 2229 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
2230 2230 elif op == 'rangeall':
2231 2231 return optimize(('range', ('string', '0'), ('string', 'tip')), small)
2232 2232 elif op == 'rangepre':
2233 2233 return optimize(('range', ('string', '0'), x[1]), small)
2234 2234 elif op == 'rangepost':
2235 2235 return optimize(('range', x[1], ('string', 'tip')), small)
2236 2236 elif op == 'negate':
2237 2237 return optimize(('string',
2238 2238 '-' + getstring(x[1], _("can't negate that"))), small)
2239 2239 elif op in 'string symbol negate':
2240 2240 return smallbonus, x # single revisions are small
2241 2241 elif op == 'and':
2242 2242 wa, ta = optimize(x[1], True)
2243 2243 wb, tb = optimize(x[2], True)
2244 2244
2245 2245 # (::x and not ::y)/(not ::y and ::x) have a fast path
2246 2246 def isonly(revs, bases):
2247 2247 return (
2248 revs[0] == 'func'
2248 revs is not None
2249 and revs[0] == 'func'
2249 2250 and getstring(revs[1], _('not a symbol')) == 'ancestors'
2251 and bases is not None
2250 2252 and bases[0] == 'not'
2251 2253 and bases[1][0] == 'func'
2252 2254 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
2253 2255
2254 2256 w = min(wa, wb)
2255 2257 if isonly(ta, tb):
2256 2258 return w, ('func', ('symbol', 'only'), ('list', ta[2], tb[1][2]))
2257 2259 if isonly(tb, ta):
2258 2260 return w, ('func', ('symbol', 'only'), ('list', tb[2], ta[1][2]))
2259 2261
2260 2262 if wa > wb:
2261 2263 return w, (op, tb, ta)
2262 2264 return w, (op, ta, tb)
2263 2265 elif op == 'or':
2264 2266 # fast path for machine-generated expression, that is likely to have
2265 2267 # lots of trivial revisions: 'a + b + c()' to '_list(a b) + c()'
2266 2268 ws, ts, ss = [], [], []
2267 2269 def flushss():
2268 2270 if not ss:
2269 2271 return
2270 2272 if len(ss) == 1:
2271 2273 w, t = ss[0]
2272 2274 else:
2273 2275 s = '\0'.join(t[1] for w, t in ss)
2274 2276 y = ('func', ('symbol', '_list'), ('string', s))
2275 2277 w, t = optimize(y, False)
2276 2278 ws.append(w)
2277 2279 ts.append(t)
2278 2280 del ss[:]
2279 2281 for y in x[1:]:
2280 2282 w, t = optimize(y, False)
2281 2283 if t[0] == 'string' or t[0] == 'symbol':
2282 2284 ss.append((w, t))
2283 2285 continue
2284 2286 flushss()
2285 2287 ws.append(w)
2286 2288 ts.append(t)
2287 2289 flushss()
2288 2290 if len(ts) == 1:
2289 2291 return ws[0], ts[0] # 'or' operation is fully optimized out
2290 2292 # we can't reorder trees by weight because it would change the order.
2291 2293 # ("sort(a + b)" == "sort(b + a)", but "a + b" != "b + a")
2292 2294 # ts = tuple(t for w, t in sorted(zip(ws, ts), key=lambda wt: wt[0]))
2293 2295 return max(ws), (op,) + tuple(ts)
2294 2296 elif op == 'not':
2295 2297 # Optimize not public() to _notpublic() because we have a fast version
2296 2298 if x[1] == ('func', ('symbol', 'public'), None):
2297 2299 newsym = ('func', ('symbol', '_notpublic'), None)
2298 2300 o = optimize(newsym, not small)
2299 2301 return o[0], o[1]
2300 2302 else:
2301 2303 o = optimize(x[1], not small)
2302 2304 return o[0], (op, o[1])
2303 2305 elif op == 'parentpost':
2304 2306 o = optimize(x[1], small)
2305 2307 return o[0], (op, o[1])
2306 2308 elif op == 'group':
2307 2309 return optimize(x[1], small)
2308 2310 elif op in 'dagrange range list parent ancestorspec':
2309 2311 if op == 'parent':
2310 2312 # x^:y means (x^) : y, not x ^ (:y)
2311 2313 post = ('parentpost', x[1])
2312 2314 if x[2][0] == 'dagrangepre':
2313 2315 return optimize(('dagrange', post, x[2][1]), small)
2314 2316 elif x[2][0] == 'rangepre':
2315 2317 return optimize(('range', post, x[2][1]), small)
2316 2318
2317 2319 wa, ta = optimize(x[1], small)
2318 2320 wb, tb = optimize(x[2], small)
2319 2321 return wa + wb, (op, ta, tb)
2320 2322 elif op == 'func':
2321 2323 f = getstring(x[1], _("not a symbol"))
2322 2324 wa, ta = optimize(x[2], small)
2323 2325 if f in ("author branch closed date desc file grep keyword "
2324 2326 "outgoing user"):
2325 2327 w = 10 # slow
2326 2328 elif f in "modifies adds removes":
2327 2329 w = 30 # slower
2328 2330 elif f == "contains":
2329 2331 w = 100 # very slow
2330 2332 elif f == "ancestor":
2331 2333 w = 1 * smallbonus
2332 2334 elif f in "reverse limit first _intlist":
2333 2335 w = 0
2334 2336 elif f in "sort":
2335 2337 w = 10 # assume most sorts look at changelog
2336 2338 else:
2337 2339 w = 1
2338 2340 return w + wa, (op, x[1], ta)
2339 2341 return 1, x
2340 2342
2341 2343 _aliasarg = ('func', ('symbol', '_aliasarg'))
2342 2344 def _getaliasarg(tree):
2343 2345 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
2344 2346 return X, None otherwise.
2345 2347 """
2346 2348 if (len(tree) == 3 and tree[:2] == _aliasarg
2347 2349 and tree[2][0] == 'string'):
2348 2350 return tree[2][1]
2349 2351 return None
2350 2352
2351 2353 def _checkaliasarg(tree, known=None):
2352 2354 """Check tree contains no _aliasarg construct or only ones which
2353 2355 value is in known. Used to avoid alias placeholders injection.
2354 2356 """
2355 2357 if isinstance(tree, tuple):
2356 2358 arg = _getaliasarg(tree)
2357 2359 if arg is not None and (not known or arg not in known):
2358 2360 raise error.UnknownIdentifier('_aliasarg', [])
2359 2361 for t in tree:
2360 2362 _checkaliasarg(t, known)
2361 2363
2362 2364 # the set of valid characters for the initial letter of symbols in
2363 2365 # alias declarations and definitions
2364 2366 _aliassyminitletters = set(c for c in [chr(i) for i in xrange(256)]
2365 2367 if c.isalnum() or c in '._@$' or ord(c) > 127)
2366 2368
2367 2369 def _tokenizealias(program, lookup=None):
2368 2370 """Parse alias declaration/definition into a stream of tokens
2369 2371
2370 2372 This allows symbol names to use also ``$`` as an initial letter
2371 2373 (for backward compatibility), and callers of this function should
2372 2374 examine whether ``$`` is used also for unexpected symbols or not.
2373 2375 """
2374 2376 return tokenize(program, lookup=lookup,
2375 2377 syminitletters=_aliassyminitletters)
2376 2378
2377 2379 def _parsealiasdecl(decl):
2378 2380 """Parse alias declaration ``decl``
2379 2381
2380 2382 This returns ``(name, tree, args, errorstr)`` tuple:
2381 2383
2382 2384 - ``name``: of declared alias (may be ``decl`` itself at error)
2383 2385 - ``tree``: parse result (or ``None`` at error)
2384 2386 - ``args``: list of alias argument names (or None for symbol declaration)
2385 2387 - ``errorstr``: detail about detected error (or None)
2386 2388
2387 2389 >>> _parsealiasdecl('foo')
2388 2390 ('foo', ('symbol', 'foo'), None, None)
2389 2391 >>> _parsealiasdecl('$foo')
2390 2392 ('$foo', None, None, "'$' not for alias arguments")
2391 2393 >>> _parsealiasdecl('foo::bar')
2392 2394 ('foo::bar', None, None, 'invalid format')
2393 2395 >>> _parsealiasdecl('foo bar')
2394 2396 ('foo bar', None, None, 'at 4: invalid token')
2395 2397 >>> _parsealiasdecl('foo()')
2396 2398 ('foo', ('func', ('symbol', 'foo')), [], None)
2397 2399 >>> _parsealiasdecl('$foo()')
2398 2400 ('$foo()', None, None, "'$' not for alias arguments")
2399 2401 >>> _parsealiasdecl('foo($1, $2)')
2400 2402 ('foo', ('func', ('symbol', 'foo')), ['$1', '$2'], None)
2401 2403 >>> _parsealiasdecl('foo(bar_bar, baz.baz)')
2402 2404 ('foo', ('func', ('symbol', 'foo')), ['bar_bar', 'baz.baz'], None)
2403 2405 >>> _parsealiasdecl('foo($1, $2, nested($1, $2))')
2404 2406 ('foo($1, $2, nested($1, $2))', None, None, 'invalid argument list')
2405 2407 >>> _parsealiasdecl('foo(bar($1, $2))')
2406 2408 ('foo(bar($1, $2))', None, None, 'invalid argument list')
2407 2409 >>> _parsealiasdecl('foo("string")')
2408 2410 ('foo("string")', None, None, 'invalid argument list')
2409 2411 >>> _parsealiasdecl('foo($1, $2')
2410 2412 ('foo($1, $2', None, None, 'at 10: unexpected token: end')
2411 2413 >>> _parsealiasdecl('foo("string')
2412 2414 ('foo("string', None, None, 'at 5: unterminated string')
2413 2415 >>> _parsealiasdecl('foo($1, $2, $1)')
2414 2416 ('foo', None, None, 'argument names collide with each other')
2415 2417 """
2416 2418 p = parser.parser(elements)
2417 2419 try:
2418 2420 tree, pos = p.parse(_tokenizealias(decl))
2419 2421 if (pos != len(decl)):
2420 2422 raise error.ParseError(_('invalid token'), pos)
2421 2423
2422 2424 if isvalidsymbol(tree):
2423 2425 # "name = ...." style
2424 2426 name = getsymbol(tree)
2425 2427 if name.startswith('$'):
2426 2428 return (decl, None, None, _("'$' not for alias arguments"))
2427 2429 return (name, ('symbol', name), None, None)
2428 2430
2429 2431 if isvalidfunc(tree):
2430 2432 # "name(arg, ....) = ...." style
2431 2433 name = getfuncname(tree)
2432 2434 if name.startswith('$'):
2433 2435 return (decl, None, None, _("'$' not for alias arguments"))
2434 2436 args = []
2435 2437 for arg in getfuncargs(tree):
2436 2438 if not isvalidsymbol(arg):
2437 2439 return (decl, None, None, _("invalid argument list"))
2438 2440 args.append(getsymbol(arg))
2439 2441 if len(args) != len(set(args)):
2440 2442 return (name, None, None,
2441 2443 _("argument names collide with each other"))
2442 2444 return (name, ('func', ('symbol', name)), args, None)
2443 2445
2444 2446 return (decl, None, None, _("invalid format"))
2445 2447 except error.ParseError as inst:
2446 2448 return (decl, None, None, parseerrordetail(inst))
2447 2449
2448 2450 def _parsealiasdefn(defn, args):
2449 2451 """Parse alias definition ``defn``
2450 2452
2451 2453 This function also replaces alias argument references in the
2452 2454 specified definition by ``_aliasarg(ARGNAME)``.
2453 2455
2454 2456 ``args`` is a list of alias argument names, or None if the alias
2455 2457 is declared as a symbol.
2456 2458
2457 2459 This returns "tree" as parsing result.
2458 2460
2459 2461 >>> args = ['$1', '$2', 'foo']
2460 2462 >>> print prettyformat(_parsealiasdefn('$1 or foo', args))
2461 2463 (or
2462 2464 (func
2463 2465 ('symbol', '_aliasarg')
2464 2466 ('string', '$1'))
2465 2467 (func
2466 2468 ('symbol', '_aliasarg')
2467 2469 ('string', 'foo')))
2468 2470 >>> try:
2469 2471 ... _parsealiasdefn('$1 or $bar', args)
2470 2472 ... except error.ParseError, inst:
2471 2473 ... print parseerrordetail(inst)
2472 2474 at 6: '$' not for alias arguments
2473 2475 >>> args = ['$1', '$10', 'foo']
2474 2476 >>> print prettyformat(_parsealiasdefn('$10 or foobar', args))
2475 2477 (or
2476 2478 (func
2477 2479 ('symbol', '_aliasarg')
2478 2480 ('string', '$10'))
2479 2481 ('symbol', 'foobar'))
2480 2482 >>> print prettyformat(_parsealiasdefn('"$1" or "foo"', args))
2481 2483 (or
2482 2484 ('string', '$1')
2483 2485 ('string', 'foo'))
2484 2486 """
2485 2487 def tokenizedefn(program, lookup=None):
2486 2488 if args:
2487 2489 argset = set(args)
2488 2490 else:
2489 2491 argset = set()
2490 2492
2491 2493 for t, value, pos in _tokenizealias(program, lookup=lookup):
2492 2494 if t == 'symbol':
2493 2495 if value in argset:
2494 2496 # emulate tokenization of "_aliasarg('ARGNAME')":
2495 2497 # "_aliasarg()" is an unknown symbol only used separate
2496 2498 # alias argument placeholders from regular strings.
2497 2499 yield ('symbol', '_aliasarg', pos)
2498 2500 yield ('(', None, pos)
2499 2501 yield ('string', value, pos)
2500 2502 yield (')', None, pos)
2501 2503 continue
2502 2504 elif value.startswith('$'):
2503 2505 raise error.ParseError(_("'$' not for alias arguments"),
2504 2506 pos)
2505 2507 yield (t, value, pos)
2506 2508
2507 2509 p = parser.parser(elements)
2508 2510 tree, pos = p.parse(tokenizedefn(defn))
2509 2511 if pos != len(defn):
2510 2512 raise error.ParseError(_('invalid token'), pos)
2511 2513 return parser.simplifyinfixops(tree, ('or',))
2512 2514
2513 2515 class revsetalias(object):
2514 2516 # whether own `error` information is already shown or not.
2515 2517 # this avoids showing same warning multiple times at each `findaliases`.
2516 2518 warned = False
2517 2519
2518 2520 def __init__(self, name, value):
2519 2521 '''Aliases like:
2520 2522
2521 2523 h = heads(default)
2522 2524 b($1) = ancestors($1) - ancestors(default)
2523 2525 '''
2524 2526 self.name, self.tree, self.args, self.error = _parsealiasdecl(name)
2525 2527 if self.error:
2526 2528 self.error = _('failed to parse the declaration of revset alias'
2527 2529 ' "%s": %s') % (self.name, self.error)
2528 2530 return
2529 2531
2530 2532 try:
2531 2533 self.replacement = _parsealiasdefn(value, self.args)
2532 2534 # Check for placeholder injection
2533 2535 _checkaliasarg(self.replacement, self.args)
2534 2536 except error.ParseError as inst:
2535 2537 self.error = _('failed to parse the definition of revset alias'
2536 2538 ' "%s": %s') % (self.name, parseerrordetail(inst))
2537 2539
2538 2540 def _getalias(aliases, tree):
2539 2541 """If tree looks like an unexpanded alias, return it. Return None
2540 2542 otherwise.
2541 2543 """
2542 2544 if isinstance(tree, tuple) and tree:
2543 2545 if tree[0] == 'symbol' and len(tree) == 2:
2544 2546 name = tree[1]
2545 2547 alias = aliases.get(name)
2546 2548 if alias and alias.args is None and alias.tree == tree:
2547 2549 return alias
2548 2550 if tree[0] == 'func' and len(tree) > 1:
2549 2551 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
2550 2552 name = tree[1][1]
2551 2553 alias = aliases.get(name)
2552 2554 if alias and alias.args is not None and alias.tree == tree[:2]:
2553 2555 return alias
2554 2556 return None
2555 2557
2556 2558 def _expandargs(tree, args):
2557 2559 """Replace _aliasarg instances with the substitution value of the
2558 2560 same name in args, recursively.
2559 2561 """
2560 2562 if not tree or not isinstance(tree, tuple):
2561 2563 return tree
2562 2564 arg = _getaliasarg(tree)
2563 2565 if arg is not None:
2564 2566 return args[arg]
2565 2567 return tuple(_expandargs(t, args) for t in tree)
2566 2568
2567 2569 def _expandaliases(aliases, tree, expanding, cache):
2568 2570 """Expand aliases in tree, recursively.
2569 2571
2570 2572 'aliases' is a dictionary mapping user defined aliases to
2571 2573 revsetalias objects.
2572 2574 """
2573 2575 if not isinstance(tree, tuple):
2574 2576 # Do not expand raw strings
2575 2577 return tree
2576 2578 alias = _getalias(aliases, tree)
2577 2579 if alias is not None:
2578 2580 if alias.error:
2579 2581 raise util.Abort(alias.error)
2580 2582 if alias in expanding:
2581 2583 raise error.ParseError(_('infinite expansion of revset alias "%s" '
2582 2584 'detected') % alias.name)
2583 2585 expanding.append(alias)
2584 2586 if alias.name not in cache:
2585 2587 cache[alias.name] = _expandaliases(aliases, alias.replacement,
2586 2588 expanding, cache)
2587 2589 result = cache[alias.name]
2588 2590 expanding.pop()
2589 2591 if alias.args is not None:
2590 2592 l = getlist(tree[2])
2591 2593 if len(l) != len(alias.args):
2592 2594 raise error.ParseError(
2593 2595 _('invalid number of arguments: %s') % len(l))
2594 2596 l = [_expandaliases(aliases, a, [], cache) for a in l]
2595 2597 result = _expandargs(result, dict(zip(alias.args, l)))
2596 2598 else:
2597 2599 result = tuple(_expandaliases(aliases, t, expanding, cache)
2598 2600 for t in tree)
2599 2601 return result
2600 2602
2601 2603 def findaliases(ui, tree, showwarning=None):
2602 2604 _checkaliasarg(tree)
2603 2605 aliases = {}
2604 2606 for k, v in ui.configitems('revsetalias'):
2605 2607 alias = revsetalias(k, v)
2606 2608 aliases[alias.name] = alias
2607 2609 tree = _expandaliases(aliases, tree, [], {})
2608 2610 if showwarning:
2609 2611 # warn about problematic (but not referred) aliases
2610 2612 for name, alias in sorted(aliases.iteritems()):
2611 2613 if alias.error and not alias.warned:
2612 2614 showwarning(_('warning: %s\n') % (alias.error))
2613 2615 alias.warned = True
2614 2616 return tree
2615 2617
2616 2618 def foldconcat(tree):
2617 2619 """Fold elements to be concatenated by `##`
2618 2620 """
2619 2621 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2620 2622 return tree
2621 2623 if tree[0] == '_concat':
2622 2624 pending = [tree]
2623 2625 l = []
2624 2626 while pending:
2625 2627 e = pending.pop()
2626 2628 if e[0] == '_concat':
2627 2629 pending.extend(reversed(e[1:]))
2628 2630 elif e[0] in ('string', 'symbol'):
2629 2631 l.append(e[1])
2630 2632 else:
2631 2633 msg = _("\"##\" can't concatenate \"%s\" element") % (e[0])
2632 2634 raise error.ParseError(msg)
2633 2635 return ('string', ''.join(l))
2634 2636 else:
2635 2637 return tuple(foldconcat(t) for t in tree)
2636 2638
2637 2639 def parse(spec, lookup=None):
2638 2640 p = parser.parser(elements)
2639 2641 tree, pos = p.parse(tokenize(spec, lookup=lookup))
2640 2642 if pos != len(spec):
2641 2643 raise error.ParseError(_("invalid token"), pos)
2642 2644 return parser.simplifyinfixops(tree, ('or',))
2643 2645
2644 2646 def posttreebuilthook(tree, repo):
2645 2647 # hook for extensions to execute code on the optimized tree
2646 2648 pass
2647 2649
2648 2650 def match(ui, spec, repo=None):
2649 2651 if not spec:
2650 2652 raise error.ParseError(_("empty query"))
2651 2653 lookup = None
2652 2654 if repo:
2653 2655 lookup = repo.__contains__
2654 2656 tree = parse(spec, lookup)
2655 2657 if ui:
2656 2658 tree = findaliases(ui, tree, showwarning=ui.warn)
2657 2659 tree = foldconcat(tree)
2658 2660 weight, tree = optimize(tree, True)
2659 2661 posttreebuilthook(tree, repo)
2660 2662 def mfunc(repo, subset=None):
2661 2663 if subset is None:
2662 2664 subset = fullreposet(repo)
2663 2665 if util.safehasattr(subset, 'isascending'):
2664 2666 result = getset(repo, subset, tree)
2665 2667 else:
2666 2668 result = getset(repo, baseset(subset), tree)
2667 2669 return result
2668 2670 return mfunc
2669 2671
2670 2672 def formatspec(expr, *args):
2671 2673 '''
2672 2674 This is a convenience function for using revsets internally, and
2673 2675 escapes arguments appropriately. Aliases are intentionally ignored
2674 2676 so that intended expression behavior isn't accidentally subverted.
2675 2677
2676 2678 Supported arguments:
2677 2679
2678 2680 %r = revset expression, parenthesized
2679 2681 %d = int(arg), no quoting
2680 2682 %s = string(arg), escaped and single-quoted
2681 2683 %b = arg.branch(), escaped and single-quoted
2682 2684 %n = hex(arg), single-quoted
2683 2685 %% = a literal '%'
2684 2686
2685 2687 Prefixing the type with 'l' specifies a parenthesized list of that type.
2686 2688
2687 2689 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
2688 2690 '(10 or 11):: and ((this()) or (that()))'
2689 2691 >>> formatspec('%d:: and not %d::', 10, 20)
2690 2692 '10:: and not 20::'
2691 2693 >>> formatspec('%ld or %ld', [], [1])
2692 2694 "_list('') or 1"
2693 2695 >>> formatspec('keyword(%s)', 'foo\\xe9')
2694 2696 "keyword('foo\\\\xe9')"
2695 2697 >>> b = lambda: 'default'
2696 2698 >>> b.branch = b
2697 2699 >>> formatspec('branch(%b)', b)
2698 2700 "branch('default')"
2699 2701 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
2700 2702 "root(_list('a\\x00b\\x00c\\x00d'))"
2701 2703 '''
2702 2704
2703 2705 def quote(s):
2704 2706 return repr(str(s))
2705 2707
2706 2708 def argtype(c, arg):
2707 2709 if c == 'd':
2708 2710 return str(int(arg))
2709 2711 elif c == 's':
2710 2712 return quote(arg)
2711 2713 elif c == 'r':
2712 2714 parse(arg) # make sure syntax errors are confined
2713 2715 return '(%s)' % arg
2714 2716 elif c == 'n':
2715 2717 return quote(node.hex(arg))
2716 2718 elif c == 'b':
2717 2719 return quote(arg.branch())
2718 2720
2719 2721 def listexp(s, t):
2720 2722 l = len(s)
2721 2723 if l == 0:
2722 2724 return "_list('')"
2723 2725 elif l == 1:
2724 2726 return argtype(t, s[0])
2725 2727 elif t == 'd':
2726 2728 return "_intlist('%s')" % "\0".join(str(int(a)) for a in s)
2727 2729 elif t == 's':
2728 2730 return "_list('%s')" % "\0".join(s)
2729 2731 elif t == 'n':
2730 2732 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
2731 2733 elif t == 'b':
2732 2734 return "_list('%s')" % "\0".join(a.branch() for a in s)
2733 2735
2734 2736 m = l // 2
2735 2737 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2736 2738
2737 2739 ret = ''
2738 2740 pos = 0
2739 2741 arg = 0
2740 2742 while pos < len(expr):
2741 2743 c = expr[pos]
2742 2744 if c == '%':
2743 2745 pos += 1
2744 2746 d = expr[pos]
2745 2747 if d == '%':
2746 2748 ret += d
2747 2749 elif d in 'dsnbr':
2748 2750 ret += argtype(d, args[arg])
2749 2751 arg += 1
2750 2752 elif d == 'l':
2751 2753 # a list of some type
2752 2754 pos += 1
2753 2755 d = expr[pos]
2754 2756 ret += listexp(list(args[arg]), d)
2755 2757 arg += 1
2756 2758 else:
2757 2759 raise util.Abort('unexpected revspec format character %s' % d)
2758 2760 else:
2759 2761 ret += c
2760 2762 pos += 1
2761 2763
2762 2764 return ret
2763 2765
2764 2766 def prettyformat(tree):
2765 2767 return parser.prettyformat(tree, ('string', 'symbol'))
2766 2768
2767 2769 def depth(tree):
2768 2770 if isinstance(tree, tuple):
2769 2771 return max(map(depth, tree)) + 1
2770 2772 else:
2771 2773 return 0
2772 2774
2773 2775 def funcsused(tree):
2774 2776 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2775 2777 return set()
2776 2778 else:
2777 2779 funcs = set()
2778 2780 for s in tree[1:]:
2779 2781 funcs |= funcsused(s)
2780 2782 if tree[0] == 'func':
2781 2783 funcs.add(tree[1][1])
2782 2784 return funcs
2783 2785
2784 2786 class abstractsmartset(object):
2785 2787
2786 2788 def __nonzero__(self):
2787 2789 """True if the smartset is not empty"""
2788 2790 raise NotImplementedError()
2789 2791
2790 2792 def __contains__(self, rev):
2791 2793 """provide fast membership testing"""
2792 2794 raise NotImplementedError()
2793 2795
2794 2796 def __iter__(self):
2795 2797 """iterate the set in the order it is supposed to be iterated"""
2796 2798 raise NotImplementedError()
2797 2799
2798 2800 # Attributes containing a function to perform a fast iteration in a given
2799 2801 # direction. A smartset can have none, one, or both defined.
2800 2802 #
2801 2803 # Default value is None instead of a function returning None to avoid
2802 2804 # initializing an iterator just for testing if a fast method exists.
2803 2805 fastasc = None
2804 2806 fastdesc = None
2805 2807
2806 2808 def isascending(self):
2807 2809 """True if the set will iterate in ascending order"""
2808 2810 raise NotImplementedError()
2809 2811
2810 2812 def isdescending(self):
2811 2813 """True if the set will iterate in descending order"""
2812 2814 raise NotImplementedError()
2813 2815
2814 2816 def min(self):
2815 2817 """return the minimum element in the set"""
2816 2818 if self.fastasc is not None:
2817 2819 for r in self.fastasc():
2818 2820 return r
2819 2821 raise ValueError('arg is an empty sequence')
2820 2822 return min(self)
2821 2823
2822 2824 def max(self):
2823 2825 """return the maximum element in the set"""
2824 2826 if self.fastdesc is not None:
2825 2827 for r in self.fastdesc():
2826 2828 return r
2827 2829 raise ValueError('arg is an empty sequence')
2828 2830 return max(self)
2829 2831
2830 2832 def first(self):
2831 2833 """return the first element in the set (user iteration perspective)
2832 2834
2833 2835 Return None if the set is empty"""
2834 2836 raise NotImplementedError()
2835 2837
2836 2838 def last(self):
2837 2839 """return the last element in the set (user iteration perspective)
2838 2840
2839 2841 Return None if the set is empty"""
2840 2842 raise NotImplementedError()
2841 2843
2842 2844 def __len__(self):
2843 2845 """return the length of the smartsets
2844 2846
2845 2847 This can be expensive on smartset that could be lazy otherwise."""
2846 2848 raise NotImplementedError()
2847 2849
2848 2850 def reverse(self):
2849 2851 """reverse the expected iteration order"""
2850 2852 raise NotImplementedError()
2851 2853
2852 2854 def sort(self, reverse=True):
2853 2855 """get the set to iterate in an ascending or descending order"""
2854 2856 raise NotImplementedError()
2855 2857
2856 2858 def __and__(self, other):
2857 2859 """Returns a new object with the intersection of the two collections.
2858 2860
2859 2861 This is part of the mandatory API for smartset."""
2860 2862 if isinstance(other, fullreposet):
2861 2863 return self
2862 2864 return self.filter(other.__contains__, cache=False)
2863 2865
2864 2866 def __add__(self, other):
2865 2867 """Returns a new object with the union of the two collections.
2866 2868
2867 2869 This is part of the mandatory API for smartset."""
2868 2870 return addset(self, other)
2869 2871
2870 2872 def __sub__(self, other):
2871 2873 """Returns a new object with the substraction of the two collections.
2872 2874
2873 2875 This is part of the mandatory API for smartset."""
2874 2876 c = other.__contains__
2875 2877 return self.filter(lambda r: not c(r), cache=False)
2876 2878
2877 2879 def filter(self, condition, cache=True):
2878 2880 """Returns this smartset filtered by condition as a new smartset.
2879 2881
2880 2882 `condition` is a callable which takes a revision number and returns a
2881 2883 boolean.
2882 2884
2883 2885 This is part of the mandatory API for smartset."""
2884 2886 # builtin cannot be cached. but do not needs to
2885 2887 if cache and util.safehasattr(condition, 'func_code'):
2886 2888 condition = util.cachefunc(condition)
2887 2889 return filteredset(self, condition)
2888 2890
2889 2891 class baseset(abstractsmartset):
2890 2892 """Basic data structure that represents a revset and contains the basic
2891 2893 operation that it should be able to perform.
2892 2894
2893 2895 Every method in this class should be implemented by any smartset class.
2894 2896 """
2895 2897 def __init__(self, data=()):
2896 2898 if not isinstance(data, list):
2897 2899 data = list(data)
2898 2900 self._list = data
2899 2901 self._ascending = None
2900 2902
2901 2903 @util.propertycache
2902 2904 def _set(self):
2903 2905 return set(self._list)
2904 2906
2905 2907 @util.propertycache
2906 2908 def _asclist(self):
2907 2909 asclist = self._list[:]
2908 2910 asclist.sort()
2909 2911 return asclist
2910 2912
2911 2913 def __iter__(self):
2912 2914 if self._ascending is None:
2913 2915 return iter(self._list)
2914 2916 elif self._ascending:
2915 2917 return iter(self._asclist)
2916 2918 else:
2917 2919 return reversed(self._asclist)
2918 2920
2919 2921 def fastasc(self):
2920 2922 return iter(self._asclist)
2921 2923
2922 2924 def fastdesc(self):
2923 2925 return reversed(self._asclist)
2924 2926
2925 2927 @util.propertycache
2926 2928 def __contains__(self):
2927 2929 return self._set.__contains__
2928 2930
2929 2931 def __nonzero__(self):
2930 2932 return bool(self._list)
2931 2933
2932 2934 def sort(self, reverse=False):
2933 2935 self._ascending = not bool(reverse)
2934 2936
2935 2937 def reverse(self):
2936 2938 if self._ascending is None:
2937 2939 self._list.reverse()
2938 2940 else:
2939 2941 self._ascending = not self._ascending
2940 2942
2941 2943 def __len__(self):
2942 2944 return len(self._list)
2943 2945
2944 2946 def isascending(self):
2945 2947 """Returns True if the collection is ascending order, False if not.
2946 2948
2947 2949 This is part of the mandatory API for smartset."""
2948 2950 if len(self) <= 1:
2949 2951 return True
2950 2952 return self._ascending is not None and self._ascending
2951 2953
2952 2954 def isdescending(self):
2953 2955 """Returns True if the collection is descending order, False if not.
2954 2956
2955 2957 This is part of the mandatory API for smartset."""
2956 2958 if len(self) <= 1:
2957 2959 return True
2958 2960 return self._ascending is not None and not self._ascending
2959 2961
2960 2962 def first(self):
2961 2963 if self:
2962 2964 if self._ascending is None:
2963 2965 return self._list[0]
2964 2966 elif self._ascending:
2965 2967 return self._asclist[0]
2966 2968 else:
2967 2969 return self._asclist[-1]
2968 2970 return None
2969 2971
2970 2972 def last(self):
2971 2973 if self:
2972 2974 if self._ascending is None:
2973 2975 return self._list[-1]
2974 2976 elif self._ascending:
2975 2977 return self._asclist[-1]
2976 2978 else:
2977 2979 return self._asclist[0]
2978 2980 return None
2979 2981
2980 2982 def __repr__(self):
2981 2983 d = {None: '', False: '-', True: '+'}[self._ascending]
2982 2984 return '<%s%s %r>' % (type(self).__name__, d, self._list)
2983 2985
2984 2986 class filteredset(abstractsmartset):
2985 2987 """Duck type for baseset class which iterates lazily over the revisions in
2986 2988 the subset and contains a function which tests for membership in the
2987 2989 revset
2988 2990 """
2989 2991 def __init__(self, subset, condition=lambda x: True):
2990 2992 """
2991 2993 condition: a function that decide whether a revision in the subset
2992 2994 belongs to the revset or not.
2993 2995 """
2994 2996 self._subset = subset
2995 2997 self._condition = condition
2996 2998 self._cache = {}
2997 2999
2998 3000 def __contains__(self, x):
2999 3001 c = self._cache
3000 3002 if x not in c:
3001 3003 v = c[x] = x in self._subset and self._condition(x)
3002 3004 return v
3003 3005 return c[x]
3004 3006
3005 3007 def __iter__(self):
3006 3008 return self._iterfilter(self._subset)
3007 3009
3008 3010 def _iterfilter(self, it):
3009 3011 cond = self._condition
3010 3012 for x in it:
3011 3013 if cond(x):
3012 3014 yield x
3013 3015
3014 3016 @property
3015 3017 def fastasc(self):
3016 3018 it = self._subset.fastasc
3017 3019 if it is None:
3018 3020 return None
3019 3021 return lambda: self._iterfilter(it())
3020 3022
3021 3023 @property
3022 3024 def fastdesc(self):
3023 3025 it = self._subset.fastdesc
3024 3026 if it is None:
3025 3027 return None
3026 3028 return lambda: self._iterfilter(it())
3027 3029
3028 3030 def __nonzero__(self):
3029 3031 for r in self:
3030 3032 return True
3031 3033 return False
3032 3034
3033 3035 def __len__(self):
3034 3036 # Basic implementation to be changed in future patches.
3035 3037 l = baseset([r for r in self])
3036 3038 return len(l)
3037 3039
3038 3040 def sort(self, reverse=False):
3039 3041 self._subset.sort(reverse=reverse)
3040 3042
3041 3043 def reverse(self):
3042 3044 self._subset.reverse()
3043 3045
3044 3046 def isascending(self):
3045 3047 return self._subset.isascending()
3046 3048
3047 3049 def isdescending(self):
3048 3050 return self._subset.isdescending()
3049 3051
3050 3052 def first(self):
3051 3053 for x in self:
3052 3054 return x
3053 3055 return None
3054 3056
3055 3057 def last(self):
3056 3058 it = None
3057 3059 if self.isascending():
3058 3060 it = self.fastdesc
3059 3061 elif self.isdescending():
3060 3062 it = self.fastasc
3061 3063 if it is not None:
3062 3064 for x in it():
3063 3065 return x
3064 3066 return None #empty case
3065 3067 else:
3066 3068 x = None
3067 3069 for x in self:
3068 3070 pass
3069 3071 return x
3070 3072
3071 3073 def __repr__(self):
3072 3074 return '<%s %r>' % (type(self).__name__, self._subset)
3073 3075
3074 3076 # this function will be removed, or merged to addset or orset, when
3075 3077 # - scmutil.revrange() can be rewritten to not combine calculated smartsets
3076 3078 # - or addset can handle more than two sets without balanced tree
3077 3079 def _combinesets(subsets):
3078 3080 """Create balanced tree of addsets representing union of given sets"""
3079 3081 if not subsets:
3080 3082 return baseset()
3081 3083 if len(subsets) == 1:
3082 3084 return subsets[0]
3083 3085 p = len(subsets) // 2
3084 3086 xs = _combinesets(subsets[:p])
3085 3087 ys = _combinesets(subsets[p:])
3086 3088 return addset(xs, ys)
3087 3089
3088 3090 def _iterordered(ascending, iter1, iter2):
3089 3091 """produce an ordered iteration from two iterators with the same order
3090 3092
3091 3093 The ascending is used to indicated the iteration direction.
3092 3094 """
3093 3095 choice = max
3094 3096 if ascending:
3095 3097 choice = min
3096 3098
3097 3099 val1 = None
3098 3100 val2 = None
3099 3101 try:
3100 3102 # Consume both iterators in an ordered way until one is empty
3101 3103 while True:
3102 3104 if val1 is None:
3103 3105 val1 = iter1.next()
3104 3106 if val2 is None:
3105 3107 val2 = iter2.next()
3106 3108 next = choice(val1, val2)
3107 3109 yield next
3108 3110 if val1 == next:
3109 3111 val1 = None
3110 3112 if val2 == next:
3111 3113 val2 = None
3112 3114 except StopIteration:
3113 3115 # Flush any remaining values and consume the other one
3114 3116 it = iter2
3115 3117 if val1 is not None:
3116 3118 yield val1
3117 3119 it = iter1
3118 3120 elif val2 is not None:
3119 3121 # might have been equality and both are empty
3120 3122 yield val2
3121 3123 for val in it:
3122 3124 yield val
3123 3125
3124 3126 class addset(abstractsmartset):
3125 3127 """Represent the addition of two sets
3126 3128
3127 3129 Wrapper structure for lazily adding two structures without losing much
3128 3130 performance on the __contains__ method
3129 3131
3130 3132 If the ascending attribute is set, that means the two structures are
3131 3133 ordered in either an ascending or descending way. Therefore, we can add
3132 3134 them maintaining the order by iterating over both at the same time
3133 3135
3134 3136 >>> xs = baseset([0, 3, 2])
3135 3137 >>> ys = baseset([5, 2, 4])
3136 3138
3137 3139 >>> rs = addset(xs, ys)
3138 3140 >>> bool(rs), 0 in rs, 1 in rs, 5 in rs, rs.first(), rs.last()
3139 3141 (True, True, False, True, 0, 4)
3140 3142 >>> rs = addset(xs, baseset([]))
3141 3143 >>> bool(rs), 0 in rs, 1 in rs, rs.first(), rs.last()
3142 3144 (True, True, False, 0, 2)
3143 3145 >>> rs = addset(baseset([]), baseset([]))
3144 3146 >>> bool(rs), 0 in rs, rs.first(), rs.last()
3145 3147 (False, False, None, None)
3146 3148
3147 3149 iterate unsorted:
3148 3150 >>> rs = addset(xs, ys)
3149 3151 >>> [x for x in rs] # without _genlist
3150 3152 [0, 3, 2, 5, 4]
3151 3153 >>> assert not rs._genlist
3152 3154 >>> len(rs)
3153 3155 5
3154 3156 >>> [x for x in rs] # with _genlist
3155 3157 [0, 3, 2, 5, 4]
3156 3158 >>> assert rs._genlist
3157 3159
3158 3160 iterate ascending:
3159 3161 >>> rs = addset(xs, ys, ascending=True)
3160 3162 >>> [x for x in rs], [x for x in rs.fastasc()] # without _asclist
3161 3163 ([0, 2, 3, 4, 5], [0, 2, 3, 4, 5])
3162 3164 >>> assert not rs._asclist
3163 3165 >>> len(rs)
3164 3166 5
3165 3167 >>> [x for x in rs], [x for x in rs.fastasc()]
3166 3168 ([0, 2, 3, 4, 5], [0, 2, 3, 4, 5])
3167 3169 >>> assert rs._asclist
3168 3170
3169 3171 iterate descending:
3170 3172 >>> rs = addset(xs, ys, ascending=False)
3171 3173 >>> [x for x in rs], [x for x in rs.fastdesc()] # without _asclist
3172 3174 ([5, 4, 3, 2, 0], [5, 4, 3, 2, 0])
3173 3175 >>> assert not rs._asclist
3174 3176 >>> len(rs)
3175 3177 5
3176 3178 >>> [x for x in rs], [x for x in rs.fastdesc()]
3177 3179 ([5, 4, 3, 2, 0], [5, 4, 3, 2, 0])
3178 3180 >>> assert rs._asclist
3179 3181
3180 3182 iterate ascending without fastasc:
3181 3183 >>> rs = addset(xs, generatorset(ys), ascending=True)
3182 3184 >>> assert rs.fastasc is None
3183 3185 >>> [x for x in rs]
3184 3186 [0, 2, 3, 4, 5]
3185 3187
3186 3188 iterate descending without fastdesc:
3187 3189 >>> rs = addset(generatorset(xs), ys, ascending=False)
3188 3190 >>> assert rs.fastdesc is None
3189 3191 >>> [x for x in rs]
3190 3192 [5, 4, 3, 2, 0]
3191 3193 """
3192 3194 def __init__(self, revs1, revs2, ascending=None):
3193 3195 self._r1 = revs1
3194 3196 self._r2 = revs2
3195 3197 self._iter = None
3196 3198 self._ascending = ascending
3197 3199 self._genlist = None
3198 3200 self._asclist = None
3199 3201
3200 3202 def __len__(self):
3201 3203 return len(self._list)
3202 3204
3203 3205 def __nonzero__(self):
3204 3206 return bool(self._r1) or bool(self._r2)
3205 3207
3206 3208 @util.propertycache
3207 3209 def _list(self):
3208 3210 if not self._genlist:
3209 3211 self._genlist = baseset(iter(self))
3210 3212 return self._genlist
3211 3213
3212 3214 def __iter__(self):
3213 3215 """Iterate over both collections without repeating elements
3214 3216
3215 3217 If the ascending attribute is not set, iterate over the first one and
3216 3218 then over the second one checking for membership on the first one so we
3217 3219 dont yield any duplicates.
3218 3220
3219 3221 If the ascending attribute is set, iterate over both collections at the
3220 3222 same time, yielding only one value at a time in the given order.
3221 3223 """
3222 3224 if self._ascending is None:
3223 3225 if self._genlist:
3224 3226 return iter(self._genlist)
3225 3227 def arbitraryordergen():
3226 3228 for r in self._r1:
3227 3229 yield r
3228 3230 inr1 = self._r1.__contains__
3229 3231 for r in self._r2:
3230 3232 if not inr1(r):
3231 3233 yield r
3232 3234 return arbitraryordergen()
3233 3235 # try to use our own fast iterator if it exists
3234 3236 self._trysetasclist()
3235 3237 if self._ascending:
3236 3238 attr = 'fastasc'
3237 3239 else:
3238 3240 attr = 'fastdesc'
3239 3241 it = getattr(self, attr)
3240 3242 if it is not None:
3241 3243 return it()
3242 3244 # maybe half of the component supports fast
3243 3245 # get iterator for _r1
3244 3246 iter1 = getattr(self._r1, attr)
3245 3247 if iter1 is None:
3246 3248 # let's avoid side effect (not sure it matters)
3247 3249 iter1 = iter(sorted(self._r1, reverse=not self._ascending))
3248 3250 else:
3249 3251 iter1 = iter1()
3250 3252 # get iterator for _r2
3251 3253 iter2 = getattr(self._r2, attr)
3252 3254 if iter2 is None:
3253 3255 # let's avoid side effect (not sure it matters)
3254 3256 iter2 = iter(sorted(self._r2, reverse=not self._ascending))
3255 3257 else:
3256 3258 iter2 = iter2()
3257 3259 return _iterordered(self._ascending, iter1, iter2)
3258 3260
3259 3261 def _trysetasclist(self):
3260 3262 """populate the _asclist attribute if possible and necessary"""
3261 3263 if self._genlist is not None and self._asclist is None:
3262 3264 self._asclist = sorted(self._genlist)
3263 3265
3264 3266 @property
3265 3267 def fastasc(self):
3266 3268 self._trysetasclist()
3267 3269 if self._asclist is not None:
3268 3270 return self._asclist.__iter__
3269 3271 iter1 = self._r1.fastasc
3270 3272 iter2 = self._r2.fastasc
3271 3273 if None in (iter1, iter2):
3272 3274 return None
3273 3275 return lambda: _iterordered(True, iter1(), iter2())
3274 3276
3275 3277 @property
3276 3278 def fastdesc(self):
3277 3279 self._trysetasclist()
3278 3280 if self._asclist is not None:
3279 3281 return self._asclist.__reversed__
3280 3282 iter1 = self._r1.fastdesc
3281 3283 iter2 = self._r2.fastdesc
3282 3284 if None in (iter1, iter2):
3283 3285 return None
3284 3286 return lambda: _iterordered(False, iter1(), iter2())
3285 3287
3286 3288 def __contains__(self, x):
3287 3289 return x in self._r1 or x in self._r2
3288 3290
3289 3291 def sort(self, reverse=False):
3290 3292 """Sort the added set
3291 3293
3292 3294 For this we use the cached list with all the generated values and if we
3293 3295 know they are ascending or descending we can sort them in a smart way.
3294 3296 """
3295 3297 self._ascending = not reverse
3296 3298
3297 3299 def isascending(self):
3298 3300 return self._ascending is not None and self._ascending
3299 3301
3300 3302 def isdescending(self):
3301 3303 return self._ascending is not None and not self._ascending
3302 3304
3303 3305 def reverse(self):
3304 3306 if self._ascending is None:
3305 3307 self._list.reverse()
3306 3308 else:
3307 3309 self._ascending = not self._ascending
3308 3310
3309 3311 def first(self):
3310 3312 for x in self:
3311 3313 return x
3312 3314 return None
3313 3315
3314 3316 def last(self):
3315 3317 self.reverse()
3316 3318 val = self.first()
3317 3319 self.reverse()
3318 3320 return val
3319 3321
3320 3322 def __repr__(self):
3321 3323 d = {None: '', False: '-', True: '+'}[self._ascending]
3322 3324 return '<%s%s %r, %r>' % (type(self).__name__, d, self._r1, self._r2)
3323 3325
3324 3326 class generatorset(abstractsmartset):
3325 3327 """Wrap a generator for lazy iteration
3326 3328
3327 3329 Wrapper structure for generators that provides lazy membership and can
3328 3330 be iterated more than once.
3329 3331 When asked for membership it generates values until either it finds the
3330 3332 requested one or has gone through all the elements in the generator
3331 3333 """
3332 3334 def __init__(self, gen, iterasc=None):
3333 3335 """
3334 3336 gen: a generator producing the values for the generatorset.
3335 3337 """
3336 3338 self._gen = gen
3337 3339 self._asclist = None
3338 3340 self._cache = {}
3339 3341 self._genlist = []
3340 3342 self._finished = False
3341 3343 self._ascending = True
3342 3344 if iterasc is not None:
3343 3345 if iterasc:
3344 3346 self.fastasc = self._iterator
3345 3347 self.__contains__ = self._asccontains
3346 3348 else:
3347 3349 self.fastdesc = self._iterator
3348 3350 self.__contains__ = self._desccontains
3349 3351
3350 3352 def __nonzero__(self):
3351 3353 # Do not use 'for r in self' because it will enforce the iteration
3352 3354 # order (default ascending), possibly unrolling a whole descending
3353 3355 # iterator.
3354 3356 if self._genlist:
3355 3357 return True
3356 3358 for r in self._consumegen():
3357 3359 return True
3358 3360 return False
3359 3361
3360 3362 def __contains__(self, x):
3361 3363 if x in self._cache:
3362 3364 return self._cache[x]
3363 3365
3364 3366 # Use new values only, as existing values would be cached.
3365 3367 for l in self._consumegen():
3366 3368 if l == x:
3367 3369 return True
3368 3370
3369 3371 self._cache[x] = False
3370 3372 return False
3371 3373
3372 3374 def _asccontains(self, x):
3373 3375 """version of contains optimised for ascending generator"""
3374 3376 if x in self._cache:
3375 3377 return self._cache[x]
3376 3378
3377 3379 # Use new values only, as existing values would be cached.
3378 3380 for l in self._consumegen():
3379 3381 if l == x:
3380 3382 return True
3381 3383 if l > x:
3382 3384 break
3383 3385
3384 3386 self._cache[x] = False
3385 3387 return False
3386 3388
3387 3389 def _desccontains(self, x):
3388 3390 """version of contains optimised for descending generator"""
3389 3391 if x in self._cache:
3390 3392 return self._cache[x]
3391 3393
3392 3394 # Use new values only, as existing values would be cached.
3393 3395 for l in self._consumegen():
3394 3396 if l == x:
3395 3397 return True
3396 3398 if l < x:
3397 3399 break
3398 3400
3399 3401 self._cache[x] = False
3400 3402 return False
3401 3403
3402 3404 def __iter__(self):
3403 3405 if self._ascending:
3404 3406 it = self.fastasc
3405 3407 else:
3406 3408 it = self.fastdesc
3407 3409 if it is not None:
3408 3410 return it()
3409 3411 # we need to consume the iterator
3410 3412 for x in self._consumegen():
3411 3413 pass
3412 3414 # recall the same code
3413 3415 return iter(self)
3414 3416
3415 3417 def _iterator(self):
3416 3418 if self._finished:
3417 3419 return iter(self._genlist)
3418 3420
3419 3421 # We have to use this complex iteration strategy to allow multiple
3420 3422 # iterations at the same time. We need to be able to catch revision
3421 3423 # removed from _consumegen and added to genlist in another instance.
3422 3424 #
3423 3425 # Getting rid of it would provide an about 15% speed up on this
3424 3426 # iteration.
3425 3427 genlist = self._genlist
3426 3428 nextrev = self._consumegen().next
3427 3429 _len = len # cache global lookup
3428 3430 def gen():
3429 3431 i = 0
3430 3432 while True:
3431 3433 if i < _len(genlist):
3432 3434 yield genlist[i]
3433 3435 else:
3434 3436 yield nextrev()
3435 3437 i += 1
3436 3438 return gen()
3437 3439
3438 3440 def _consumegen(self):
3439 3441 cache = self._cache
3440 3442 genlist = self._genlist.append
3441 3443 for item in self._gen:
3442 3444 cache[item] = True
3443 3445 genlist(item)
3444 3446 yield item
3445 3447 if not self._finished:
3446 3448 self._finished = True
3447 3449 asc = self._genlist[:]
3448 3450 asc.sort()
3449 3451 self._asclist = asc
3450 3452 self.fastasc = asc.__iter__
3451 3453 self.fastdesc = asc.__reversed__
3452 3454
3453 3455 def __len__(self):
3454 3456 for x in self._consumegen():
3455 3457 pass
3456 3458 return len(self._genlist)
3457 3459
3458 3460 def sort(self, reverse=False):
3459 3461 self._ascending = not reverse
3460 3462
3461 3463 def reverse(self):
3462 3464 self._ascending = not self._ascending
3463 3465
3464 3466 def isascending(self):
3465 3467 return self._ascending
3466 3468
3467 3469 def isdescending(self):
3468 3470 return not self._ascending
3469 3471
3470 3472 def first(self):
3471 3473 if self._ascending:
3472 3474 it = self.fastasc
3473 3475 else:
3474 3476 it = self.fastdesc
3475 3477 if it is None:
3476 3478 # we need to consume all and try again
3477 3479 for x in self._consumegen():
3478 3480 pass
3479 3481 return self.first()
3480 3482 return next(it(), None)
3481 3483
3482 3484 def last(self):
3483 3485 if self._ascending:
3484 3486 it = self.fastdesc
3485 3487 else:
3486 3488 it = self.fastasc
3487 3489 if it is None:
3488 3490 # we need to consume all and try again
3489 3491 for x in self._consumegen():
3490 3492 pass
3491 3493 return self.first()
3492 3494 return next(it(), None)
3493 3495
3494 3496 def __repr__(self):
3495 3497 d = {False: '-', True: '+'}[self._ascending]
3496 3498 return '<%s%s>' % (type(self).__name__, d)
3497 3499
3498 3500 class spanset(abstractsmartset):
3499 3501 """Duck type for baseset class which represents a range of revisions and
3500 3502 can work lazily and without having all the range in memory
3501 3503
3502 3504 Note that spanset(x, y) behave almost like xrange(x, y) except for two
3503 3505 notable points:
3504 3506 - when x < y it will be automatically descending,
3505 3507 - revision filtered with this repoview will be skipped.
3506 3508
3507 3509 """
3508 3510 def __init__(self, repo, start=0, end=None):
3509 3511 """
3510 3512 start: first revision included the set
3511 3513 (default to 0)
3512 3514 end: first revision excluded (last+1)
3513 3515 (default to len(repo)
3514 3516
3515 3517 Spanset will be descending if `end` < `start`.
3516 3518 """
3517 3519 if end is None:
3518 3520 end = len(repo)
3519 3521 self._ascending = start <= end
3520 3522 if not self._ascending:
3521 3523 start, end = end + 1, start +1
3522 3524 self._start = start
3523 3525 self._end = end
3524 3526 self._hiddenrevs = repo.changelog.filteredrevs
3525 3527
3526 3528 def sort(self, reverse=False):
3527 3529 self._ascending = not reverse
3528 3530
3529 3531 def reverse(self):
3530 3532 self._ascending = not self._ascending
3531 3533
3532 3534 def _iterfilter(self, iterrange):
3533 3535 s = self._hiddenrevs
3534 3536 for r in iterrange:
3535 3537 if r not in s:
3536 3538 yield r
3537 3539
3538 3540 def __iter__(self):
3539 3541 if self._ascending:
3540 3542 return self.fastasc()
3541 3543 else:
3542 3544 return self.fastdesc()
3543 3545
3544 3546 def fastasc(self):
3545 3547 iterrange = xrange(self._start, self._end)
3546 3548 if self._hiddenrevs:
3547 3549 return self._iterfilter(iterrange)
3548 3550 return iter(iterrange)
3549 3551
3550 3552 def fastdesc(self):
3551 3553 iterrange = xrange(self._end - 1, self._start - 1, -1)
3552 3554 if self._hiddenrevs:
3553 3555 return self._iterfilter(iterrange)
3554 3556 return iter(iterrange)
3555 3557
3556 3558 def __contains__(self, rev):
3557 3559 hidden = self._hiddenrevs
3558 3560 return ((self._start <= rev < self._end)
3559 3561 and not (hidden and rev in hidden))
3560 3562
3561 3563 def __nonzero__(self):
3562 3564 for r in self:
3563 3565 return True
3564 3566 return False
3565 3567
3566 3568 def __len__(self):
3567 3569 if not self._hiddenrevs:
3568 3570 return abs(self._end - self._start)
3569 3571 else:
3570 3572 count = 0
3571 3573 start = self._start
3572 3574 end = self._end
3573 3575 for rev in self._hiddenrevs:
3574 3576 if (end < rev <= start) or (start <= rev < end):
3575 3577 count += 1
3576 3578 return abs(self._end - self._start) - count
3577 3579
3578 3580 def isascending(self):
3579 3581 return self._ascending
3580 3582
3581 3583 def isdescending(self):
3582 3584 return not self._ascending
3583 3585
3584 3586 def first(self):
3585 3587 if self._ascending:
3586 3588 it = self.fastasc
3587 3589 else:
3588 3590 it = self.fastdesc
3589 3591 for x in it():
3590 3592 return x
3591 3593 return None
3592 3594
3593 3595 def last(self):
3594 3596 if self._ascending:
3595 3597 it = self.fastdesc
3596 3598 else:
3597 3599 it = self.fastasc
3598 3600 for x in it():
3599 3601 return x
3600 3602 return None
3601 3603
3602 3604 def __repr__(self):
3603 3605 d = {False: '-', True: '+'}[self._ascending]
3604 3606 return '<%s%s %d:%d>' % (type(self).__name__, d,
3605 3607 self._start, self._end - 1)
3606 3608
3607 3609 class fullreposet(spanset):
3608 3610 """a set containing all revisions in the repo
3609 3611
3610 3612 This class exists to host special optimization and magic to handle virtual
3611 3613 revisions such as "null".
3612 3614 """
3613 3615
3614 3616 def __init__(self, repo):
3615 3617 super(fullreposet, self).__init__(repo)
3616 3618
3617 3619 def __and__(self, other):
3618 3620 """As self contains the whole repo, all of the other set should also be
3619 3621 in self. Therefore `self & other = other`.
3620 3622
3621 3623 This boldly assumes the other contains valid revs only.
3622 3624 """
3623 3625 # other not a smartset, make is so
3624 3626 if not util.safehasattr(other, 'isascending'):
3625 3627 # filter out hidden revision
3626 3628 # (this boldly assumes all smartset are pure)
3627 3629 #
3628 3630 # `other` was used with "&", let's assume this is a set like
3629 3631 # object.
3630 3632 other = baseset(other - self._hiddenrevs)
3631 3633
3632 3634 # XXX As fullreposet is also used as bootstrap, this is wrong.
3633 3635 #
3634 3636 # With a giveme312() revset returning [3,1,2], this makes
3635 3637 # 'hg log -r "giveme312()"' -> 1, 2, 3 (wrong)
3636 3638 # We cannot just drop it because other usage still need to sort it:
3637 3639 # 'hg log -r "all() and giveme312()"' -> 1, 2, 3 (right)
3638 3640 #
3639 3641 # There is also some faulty revset implementations that rely on it
3640 3642 # (eg: children as of its state in e8075329c5fb)
3641 3643 #
3642 3644 # When we fix the two points above we can move this into the if clause
3643 3645 other.sort(reverse=self.isdescending())
3644 3646 return other
3645 3647
3646 3648 def prettyformatset(revs):
3647 3649 lines = []
3648 3650 rs = repr(revs)
3649 3651 p = 0
3650 3652 while p < len(rs):
3651 3653 q = rs.find('<', p + 1)
3652 3654 if q < 0:
3653 3655 q = len(rs)
3654 3656 l = rs.count('<', 0, p) - rs.count('>', 0, p)
3655 3657 assert l >= 0
3656 3658 lines.append((l, rs[p:q].rstrip()))
3657 3659 p = q
3658 3660 return '\n'.join(' ' * l + s for l, s in lines)
3659 3661
3660 3662 # tell hggettext to extract docstrings from these functions:
3661 3663 i18nfunctions = symbols.values()
@@ -1,2090 +1,2107
1 1 $ HGENCODING=utf-8
2 2 $ export HGENCODING
3 3 $ cat > testrevset.py << EOF
4 4 > import mercurial.revset
5 5 >
6 6 > baseset = mercurial.revset.baseset
7 7 >
8 8 > def r3232(repo, subset, x):
9 9 > """"simple revset that return [3,2,3,2]
10 10 >
11 11 > revisions duplicated on purpose.
12 12 > """
13 13 > if 3 not in subset:
14 14 > if 2 in subset:
15 15 > return baseset([2,2])
16 16 > return baseset()
17 17 > return baseset([3,3,2,2])
18 18 >
19 19 > mercurial.revset.symbols['r3232'] = r3232
20 20 > EOF
21 21 $ cat >> $HGRCPATH << EOF
22 22 > [extensions]
23 23 > testrevset=$TESTTMP/testrevset.py
24 24 > EOF
25 25
26 26 $ try() {
27 27 > hg debugrevspec --debug "$@"
28 28 > }
29 29
30 30 $ log() {
31 31 > hg log --template '{rev}\n' -r "$1"
32 32 > }
33 33
34 34 $ hg init repo
35 35 $ cd repo
36 36
37 37 $ echo a > a
38 38 $ hg branch a
39 39 marked working directory as branch a
40 40 (branches are permanent and global, did you want a bookmark?)
41 41 $ hg ci -Aqm0
42 42
43 43 $ echo b > b
44 44 $ hg branch b
45 45 marked working directory as branch b
46 46 $ hg ci -Aqm1
47 47
48 48 $ rm a
49 49 $ hg branch a-b-c-
50 50 marked working directory as branch a-b-c-
51 51 $ hg ci -Aqm2 -u Bob
52 52
53 53 $ hg log -r "extra('branch', 'a-b-c-')" --template '{rev}\n'
54 54 2
55 55 $ hg log -r "extra('branch')" --template '{rev}\n'
56 56 0
57 57 1
58 58 2
59 59 $ hg log -r "extra('branch', 're:a')" --template '{rev} {branch}\n'
60 60 0 a
61 61 2 a-b-c-
62 62
63 63 $ hg co 1
64 64 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
65 65 $ hg branch +a+b+c+
66 66 marked working directory as branch +a+b+c+
67 67 $ hg ci -Aqm3
68 68
69 69 $ hg co 2 # interleave
70 70 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
71 71 $ echo bb > b
72 72 $ hg branch -- -a-b-c-
73 73 marked working directory as branch -a-b-c-
74 74 $ hg ci -Aqm4 -d "May 12 2005"
75 75
76 76 $ hg co 3
77 77 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
78 78 $ hg branch !a/b/c/
79 79 marked working directory as branch !a/b/c/
80 80 $ hg ci -Aqm"5 bug"
81 81
82 82 $ hg merge 4
83 83 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
84 84 (branch merge, don't forget to commit)
85 85 $ hg branch _a_b_c_
86 86 marked working directory as branch _a_b_c_
87 87 $ hg ci -Aqm"6 issue619"
88 88
89 89 $ hg branch .a.b.c.
90 90 marked working directory as branch .a.b.c.
91 91 $ hg ci -Aqm7
92 92
93 93 $ hg branch all
94 94 marked working directory as branch all
95 95
96 96 $ hg co 4
97 97 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
98 98 $ hg branch Γ©
99 99 marked working directory as branch \xc3\xa9 (esc)
100 100 $ hg ci -Aqm9
101 101
102 102 $ hg tag -r6 1.0
103 103 $ hg bookmark -r6 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
104 104
105 105 $ hg clone --quiet -U -r 7 . ../remote1
106 106 $ hg clone --quiet -U -r 8 . ../remote2
107 107 $ echo "[paths]" >> .hg/hgrc
108 108 $ echo "default = ../remote1" >> .hg/hgrc
109 109
110 110 trivial
111 111
112 112 $ try 0:1
113 113 (range
114 114 ('symbol', '0')
115 115 ('symbol', '1'))
116 116 * set:
117 117 <spanset+ 0:1>
118 118 0
119 119 1
120 120 $ try --optimize :
121 121 (rangeall
122 122 None)
123 123 * optimized:
124 124 (range
125 125 ('string', '0')
126 126 ('string', 'tip'))
127 127 * set:
128 128 <spanset+ 0:9>
129 129 0
130 130 1
131 131 2
132 132 3
133 133 4
134 134 5
135 135 6
136 136 7
137 137 8
138 138 9
139 139 $ try 3::6
140 140 (dagrange
141 141 ('symbol', '3')
142 142 ('symbol', '6'))
143 143 * set:
144 144 <baseset [3, 5, 6]>
145 145 3
146 146 5
147 147 6
148 148 $ try '0|1|2'
149 149 (or
150 150 ('symbol', '0')
151 151 ('symbol', '1')
152 152 ('symbol', '2'))
153 153 * set:
154 154 <baseset [0, 1, 2]>
155 155 0
156 156 1
157 157 2
158 158
159 159 names that should work without quoting
160 160
161 161 $ try a
162 162 ('symbol', 'a')
163 163 * set:
164 164 <baseset [0]>
165 165 0
166 166 $ try b-a
167 167 (minus
168 168 ('symbol', 'b')
169 169 ('symbol', 'a'))
170 170 * set:
171 171 <filteredset
172 172 <baseset [1]>>
173 173 1
174 174 $ try _a_b_c_
175 175 ('symbol', '_a_b_c_')
176 176 * set:
177 177 <baseset [6]>
178 178 6
179 179 $ try _a_b_c_-a
180 180 (minus
181 181 ('symbol', '_a_b_c_')
182 182 ('symbol', 'a'))
183 183 * set:
184 184 <filteredset
185 185 <baseset [6]>>
186 186 6
187 187 $ try .a.b.c.
188 188 ('symbol', '.a.b.c.')
189 189 * set:
190 190 <baseset [7]>
191 191 7
192 192 $ try .a.b.c.-a
193 193 (minus
194 194 ('symbol', '.a.b.c.')
195 195 ('symbol', 'a'))
196 196 * set:
197 197 <filteredset
198 198 <baseset [7]>>
199 199 7
200 200 $ try -- '-a-b-c-' # complains
201 201 hg: parse error at 7: not a prefix: end
202 202 [255]
203 203 $ log -a-b-c- # succeeds with fallback
204 204 4
205 205
206 206 $ try -- -a-b-c--a # complains
207 207 (minus
208 208 (minus
209 209 (minus
210 210 (negate
211 211 ('symbol', 'a'))
212 212 ('symbol', 'b'))
213 213 ('symbol', 'c'))
214 214 (negate
215 215 ('symbol', 'a')))
216 216 abort: unknown revision '-a'!
217 217 [255]
218 218 $ try Γ©
219 219 ('symbol', '\xc3\xa9')
220 220 * set:
221 221 <baseset [9]>
222 222 9
223 223
224 224 no quoting needed
225 225
226 226 $ log ::a-b-c-
227 227 0
228 228 1
229 229 2
230 230
231 231 quoting needed
232 232
233 233 $ try '"-a-b-c-"-a'
234 234 (minus
235 235 ('string', '-a-b-c-')
236 236 ('symbol', 'a'))
237 237 * set:
238 238 <filteredset
239 239 <baseset [4]>>
240 240 4
241 241
242 242 $ log '1 or 2'
243 243 1
244 244 2
245 245 $ log '1|2'
246 246 1
247 247 2
248 248 $ log '1 and 2'
249 249 $ log '1&2'
250 250 $ try '1&2|3' # precedence - and is higher
251 251 (or
252 252 (and
253 253 ('symbol', '1')
254 254 ('symbol', '2'))
255 255 ('symbol', '3'))
256 256 * set:
257 257 <addset
258 258 <baseset []>,
259 259 <baseset [3]>>
260 260 3
261 261 $ try '1|2&3'
262 262 (or
263 263 ('symbol', '1')
264 264 (and
265 265 ('symbol', '2')
266 266 ('symbol', '3')))
267 267 * set:
268 268 <addset
269 269 <baseset [1]>,
270 270 <baseset []>>
271 271 1
272 272 $ try '1&2&3' # associativity
273 273 (and
274 274 (and
275 275 ('symbol', '1')
276 276 ('symbol', '2'))
277 277 ('symbol', '3'))
278 278 * set:
279 279 <baseset []>
280 280 $ try '1|(2|3)'
281 281 (or
282 282 ('symbol', '1')
283 283 (group
284 284 (or
285 285 ('symbol', '2')
286 286 ('symbol', '3'))))
287 287 * set:
288 288 <addset
289 289 <baseset [1]>,
290 290 <baseset [2, 3]>>
291 291 1
292 292 2
293 293 3
294 294 $ log '1.0' # tag
295 295 6
296 296 $ log 'a' # branch
297 297 0
298 298 $ log '2785f51ee'
299 299 0
300 300 $ log 'date(2005)'
301 301 4
302 302 $ log 'date(this is a test)'
303 303 hg: parse error at 10: unexpected token: symbol
304 304 [255]
305 305 $ log 'date()'
306 306 hg: parse error: date requires a string
307 307 [255]
308 308 $ log 'date'
309 309 abort: unknown revision 'date'!
310 310 [255]
311 311 $ log 'date('
312 312 hg: parse error at 5: not a prefix: end
313 313 [255]
314 314 $ log 'date(tip)'
315 315 abort: invalid date: 'tip'
316 316 [255]
317 317 $ log '0:date'
318 318 abort: unknown revision 'date'!
319 319 [255]
320 320 $ log '::"date"'
321 321 abort: unknown revision 'date'!
322 322 [255]
323 323 $ hg book date -r 4
324 324 $ log '0:date'
325 325 0
326 326 1
327 327 2
328 328 3
329 329 4
330 330 $ log '::date'
331 331 0
332 332 1
333 333 2
334 334 4
335 335 $ log '::"date"'
336 336 0
337 337 1
338 338 2
339 339 4
340 340 $ log 'date(2005) and 1::'
341 341 4
342 342 $ hg book -d date
343 343
344 344 keyword arguments
345 345
346 346 $ log 'extra(branch, value=a)'
347 347 0
348 348
349 349 $ log 'extra(branch, a, b)'
350 350 hg: parse error: extra takes at most 2 arguments
351 351 [255]
352 352 $ log 'extra(a, label=b)'
353 353 hg: parse error: extra got multiple values for keyword argument 'label'
354 354 [255]
355 355 $ log 'extra(label=branch, default)'
356 356 hg: parse error: extra got an invalid argument
357 357 [255]
358 358 $ log 'extra(branch, foo+bar=baz)'
359 359 hg: parse error: extra got an invalid argument
360 360 [255]
361 361 $ log 'extra(unknown=branch)'
362 362 hg: parse error: extra got an unexpected keyword argument 'unknown'
363 363 [255]
364 364
365 365 $ try 'foo=bar|baz'
366 366 (keyvalue
367 367 ('symbol', 'foo')
368 368 (or
369 369 ('symbol', 'bar')
370 370 ('symbol', 'baz')))
371 371 hg: parse error: can't use a key-value pair in this context
372 372 [255]
373 373
374 374 Test that symbols only get parsed as functions if there's an opening
375 375 parenthesis.
376 376
377 377 $ hg book only -r 9
378 378 $ log 'only(only)' # Outer "only" is a function, inner "only" is the bookmark
379 379 8
380 380 9
381 381
382 382 ancestor can accept 0 or more arguments
383 383
384 384 $ log 'ancestor()'
385 385 $ log 'ancestor(1)'
386 386 1
387 387 $ log 'ancestor(4,5)'
388 388 1
389 389 $ log 'ancestor(4,5) and 4'
390 390 $ log 'ancestor(0,0,1,3)'
391 391 0
392 392 $ log 'ancestor(3,1,5,3,5,1)'
393 393 1
394 394 $ log 'ancestor(0,1,3,5)'
395 395 0
396 396 $ log 'ancestor(1,2,3,4,5)'
397 397 1
398 398
399 399 test ancestors
400 400
401 401 $ log 'ancestors(5)'
402 402 0
403 403 1
404 404 3
405 405 5
406 406 $ log 'ancestor(ancestors(5))'
407 407 0
408 408 $ log '::r3232()'
409 409 0
410 410 1
411 411 2
412 412 3
413 413
414 414 $ log 'author(bob)'
415 415 2
416 416 $ log 'author("re:bob|test")'
417 417 0
418 418 1
419 419 2
420 420 3
421 421 4
422 422 5
423 423 6
424 424 7
425 425 8
426 426 9
427 427 $ log 'branch(Γ©)'
428 428 8
429 429 9
430 430 $ log 'branch(a)'
431 431 0
432 432 $ hg log -r 'branch("re:a")' --template '{rev} {branch}\n'
433 433 0 a
434 434 2 a-b-c-
435 435 3 +a+b+c+
436 436 4 -a-b-c-
437 437 5 !a/b/c/
438 438 6 _a_b_c_
439 439 7 .a.b.c.
440 440 $ log 'children(ancestor(4,5))'
441 441 2
442 442 3
443 443 $ log 'closed()'
444 444 $ log 'contains(a)'
445 445 0
446 446 1
447 447 3
448 448 5
449 449 $ log 'contains("../repo/a")'
450 450 0
451 451 1
452 452 3
453 453 5
454 454 $ log 'desc(B)'
455 455 5
456 456 $ log 'descendants(2 or 3)'
457 457 2
458 458 3
459 459 4
460 460 5
461 461 6
462 462 7
463 463 8
464 464 9
465 465 $ log 'file("b*")'
466 466 1
467 467 4
468 468 $ log 'filelog("b")'
469 469 1
470 470 4
471 471 $ log 'filelog("../repo/b")'
472 472 1
473 473 4
474 474 $ log 'follow()'
475 475 0
476 476 1
477 477 2
478 478 4
479 479 8
480 480 9
481 481 $ log 'grep("issue\d+")'
482 482 6
483 483 $ try 'grep("(")' # invalid regular expression
484 484 (func
485 485 ('symbol', 'grep')
486 486 ('string', '('))
487 487 hg: parse error: invalid match pattern: unbalanced parenthesis
488 488 [255]
489 489 $ try 'grep("\bissue\d+")'
490 490 (func
491 491 ('symbol', 'grep')
492 492 ('string', '\x08issue\\d+'))
493 493 * set:
494 494 <filteredset
495 495 <fullreposet+ 0:9>>
496 496 $ try 'grep(r"\bissue\d+")'
497 497 (func
498 498 ('symbol', 'grep')
499 499 ('string', '\\bissue\\d+'))
500 500 * set:
501 501 <filteredset
502 502 <fullreposet+ 0:9>>
503 503 6
504 504 $ try 'grep(r"\")'
505 505 hg: parse error at 7: unterminated string
506 506 [255]
507 507 $ log 'head()'
508 508 0
509 509 1
510 510 2
511 511 3
512 512 4
513 513 5
514 514 6
515 515 7
516 516 9
517 517 $ log 'heads(6::)'
518 518 7
519 519 $ log 'keyword(issue)'
520 520 6
521 521 $ log 'keyword("test a")'
522 522 $ log 'limit(head(), 1)'
523 523 0
524 524 $ log 'matching(6)'
525 525 6
526 526 $ log 'matching(6:7, "phase parents user date branch summary files description substate")'
527 527 6
528 528 7
529 529
530 530 Testing min and max
531 531
532 532 max: simple
533 533
534 534 $ log 'max(contains(a))'
535 535 5
536 536
537 537 max: simple on unordered set)
538 538
539 539 $ log 'max((4+0+2+5+7) and contains(a))'
540 540 5
541 541
542 542 max: no result
543 543
544 544 $ log 'max(contains(stringthatdoesnotappearanywhere))'
545 545
546 546 max: no result on unordered set
547 547
548 548 $ log 'max((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
549 549
550 550 min: simple
551 551
552 552 $ log 'min(contains(a))'
553 553 0
554 554
555 555 min: simple on unordered set
556 556
557 557 $ log 'min((4+0+2+5+7) and contains(a))'
558 558 0
559 559
560 560 min: empty
561 561
562 562 $ log 'min(contains(stringthatdoesnotappearanywhere))'
563 563
564 564 min: empty on unordered set
565 565
566 566 $ log 'min((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
567 567
568 568
569 569 $ log 'merge()'
570 570 6
571 571 $ log 'branchpoint()'
572 572 1
573 573 4
574 574 $ log 'modifies(b)'
575 575 4
576 576 $ log 'modifies("path:b")'
577 577 4
578 578 $ log 'modifies("*")'
579 579 4
580 580 6
581 581 $ log 'modifies("set:modified()")'
582 582 4
583 583 $ log 'id(5)'
584 584 2
585 585 $ log 'only(9)'
586 586 8
587 587 9
588 588 $ log 'only(8)'
589 589 8
590 590 $ log 'only(9, 5)'
591 591 2
592 592 4
593 593 8
594 594 9
595 595 $ log 'only(7 + 9, 5 + 2)'
596 596 4
597 597 6
598 598 7
599 599 8
600 600 9
601 601
602 602 Test empty set input
603 603 $ log 'only(p2())'
604 604 $ log 'only(p1(), p2())'
605 605 0
606 606 1
607 607 2
608 608 4
609 609 8
610 610 9
611 611
612 612 Test '%' operator
613 613
614 614 $ log '9%'
615 615 8
616 616 9
617 617 $ log '9%5'
618 618 2
619 619 4
620 620 8
621 621 9
622 622 $ log '(7 + 9)%(5 + 2)'
623 623 4
624 624 6
625 625 7
626 626 8
627 627 9
628 628
629 629 Test opreand of '%' is optimized recursively (issue4670)
630 630
631 631 $ try --optimize '8:9-8%'
632 632 (onlypost
633 633 (minus
634 634 (range
635 635 ('symbol', '8')
636 636 ('symbol', '9'))
637 637 ('symbol', '8')))
638 638 * optimized:
639 639 (func
640 640 ('symbol', 'only')
641 641 (and
642 642 (range
643 643 ('symbol', '8')
644 644 ('symbol', '9'))
645 645 (not
646 646 ('symbol', '8'))))
647 647 * set:
648 648 <baseset+ [8, 9]>
649 649 8
650 650 9
651 651 $ try --optimize '(9)%(5)'
652 652 (only
653 653 (group
654 654 ('symbol', '9'))
655 655 (group
656 656 ('symbol', '5')))
657 657 * optimized:
658 658 (func
659 659 ('symbol', 'only')
660 660 (list
661 661 ('symbol', '9')
662 662 ('symbol', '5')))
663 663 * set:
664 664 <baseset+ [8, 9, 2, 4]>
665 665 2
666 666 4
667 667 8
668 668 9
669 669
670 670 Test the order of operations
671 671
672 672 $ log '7 + 9%5 + 2'
673 673 7
674 674 2
675 675 4
676 676 8
677 677 9
678 678
679 679 Test explicit numeric revision
680 680 $ log 'rev(-2)'
681 681 $ log 'rev(-1)'
682 682 -1
683 683 $ log 'rev(0)'
684 684 0
685 685 $ log 'rev(9)'
686 686 9
687 687 $ log 'rev(10)'
688 688 $ log 'rev(tip)'
689 689 hg: parse error: rev expects a number
690 690 [255]
691 691
692 692 Test hexadecimal revision
693 693 $ log 'id(2)'
694 694 abort: 00changelog.i@2: ambiguous identifier!
695 695 [255]
696 696 $ log 'id(23268)'
697 697 4
698 698 $ log 'id(2785f51eece)'
699 699 0
700 700 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532c)'
701 701 8
702 702 $ log 'id(d5d0dcbdc4a)'
703 703 $ log 'id(d5d0dcbdc4w)'
704 704 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532d)'
705 705 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532q)'
706 706 $ log 'id(1.0)'
707 707 $ log 'id(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)'
708 708
709 709 Test null revision
710 710 $ log '(null)'
711 711 -1
712 712 $ log '(null:0)'
713 713 -1
714 714 0
715 715 $ log '(0:null)'
716 716 0
717 717 -1
718 718 $ log 'null::0'
719 719 -1
720 720 0
721 721 $ log 'null:tip - 0:'
722 722 -1
723 723 $ log 'null: and null::' | head -1
724 724 -1
725 725 $ log 'null: or 0:' | head -2
726 726 -1
727 727 0
728 728 $ log 'ancestors(null)'
729 729 -1
730 730 $ log 'reverse(null:)' | tail -2
731 731 0
732 732 -1
733 733 BROKEN: should be '-1'
734 734 $ log 'first(null:)'
735 735 BROKEN: should be '-1'
736 736 $ log 'min(null:)'
737 737 $ log 'tip:null and all()' | tail -2
738 738 1
739 739 0
740 740
741 741 Test working-directory revision
742 742 $ hg debugrevspec 'wdir()'
743 743 2147483647
744 744 $ hg debugrevspec 'tip or wdir()'
745 745 9
746 746 2147483647
747 747 $ hg debugrevspec '0:tip and wdir()'
748 748 $ log '0:wdir()' | tail -3
749 749 8
750 750 9
751 751 2147483647
752 752 $ log 'wdir():0' | head -3
753 753 2147483647
754 754 9
755 755 8
756 756 $ log 'wdir():wdir()'
757 757 2147483647
758 758 $ log '(all() + wdir()) & min(. + wdir())'
759 759 9
760 760 $ log '(all() + wdir()) & max(. + wdir())'
761 761 2147483647
762 762 $ log '(all() + wdir()) & first(wdir() + .)'
763 763 2147483647
764 764 $ log '(all() + wdir()) & last(. + wdir())'
765 765 2147483647
766 766
767 767 $ log 'outgoing()'
768 768 8
769 769 9
770 770 $ log 'outgoing("../remote1")'
771 771 8
772 772 9
773 773 $ log 'outgoing("../remote2")'
774 774 3
775 775 5
776 776 6
777 777 7
778 778 9
779 779 $ log 'p1(merge())'
780 780 5
781 781 $ log 'p2(merge())'
782 782 4
783 783 $ log 'parents(merge())'
784 784 4
785 785 5
786 786 $ log 'p1(branchpoint())'
787 787 0
788 788 2
789 789 $ log 'p2(branchpoint())'
790 790 $ log 'parents(branchpoint())'
791 791 0
792 792 2
793 793 $ log 'removes(a)'
794 794 2
795 795 6
796 796 $ log 'roots(all())'
797 797 0
798 798 $ log 'reverse(2 or 3 or 4 or 5)'
799 799 5
800 800 4
801 801 3
802 802 2
803 803 $ log 'reverse(all())'
804 804 9
805 805 8
806 806 7
807 807 6
808 808 5
809 809 4
810 810 3
811 811 2
812 812 1
813 813 0
814 814 $ log 'reverse(all()) & filelog(b)'
815 815 4
816 816 1
817 817 $ log 'rev(5)'
818 818 5
819 819 $ log 'sort(limit(reverse(all()), 3))'
820 820 7
821 821 8
822 822 9
823 823 $ log 'sort(2 or 3 or 4 or 5, date)'
824 824 2
825 825 3
826 826 5
827 827 4
828 828 $ log 'tagged()'
829 829 6
830 830 $ log 'tag()'
831 831 6
832 832 $ log 'tag(1.0)'
833 833 6
834 834 $ log 'tag(tip)'
835 835 9
836 836
837 837 test sort revset
838 838 --------------------------------------------
839 839
840 840 test when adding two unordered revsets
841 841
842 842 $ log 'sort(keyword(issue) or modifies(b))'
843 843 4
844 844 6
845 845
846 846 test when sorting a reversed collection in the same way it is
847 847
848 848 $ log 'sort(reverse(all()), -rev)'
849 849 9
850 850 8
851 851 7
852 852 6
853 853 5
854 854 4
855 855 3
856 856 2
857 857 1
858 858 0
859 859
860 860 test when sorting a reversed collection
861 861
862 862 $ log 'sort(reverse(all()), rev)'
863 863 0
864 864 1
865 865 2
866 866 3
867 867 4
868 868 5
869 869 6
870 870 7
871 871 8
872 872 9
873 873
874 874
875 875 test sorting two sorted collections in different orders
876 876
877 877 $ log 'sort(outgoing() or reverse(removes(a)), rev)'
878 878 2
879 879 6
880 880 8
881 881 9
882 882
883 883 test sorting two sorted collections in different orders backwards
884 884
885 885 $ log 'sort(outgoing() or reverse(removes(a)), -rev)'
886 886 9
887 887 8
888 888 6
889 889 2
890 890
891 891 test subtracting something from an addset
892 892
893 893 $ log '(outgoing() or removes(a)) - removes(a)'
894 894 8
895 895 9
896 896
897 897 test intersecting something with an addset
898 898
899 899 $ log 'parents(outgoing() or removes(a))'
900 900 1
901 901 4
902 902 5
903 903 8
904 904
905 905 test that `or` operation combines elements in the right order:
906 906
907 907 $ log '3:4 or 2:5'
908 908 3
909 909 4
910 910 2
911 911 5
912 912 $ log '3:4 or 5:2'
913 913 3
914 914 4
915 915 5
916 916 2
917 917 $ log 'sort(3:4 or 2:5)'
918 918 2
919 919 3
920 920 4
921 921 5
922 922 $ log 'sort(3:4 or 5:2)'
923 923 2
924 924 3
925 925 4
926 926 5
927 927
928 928 test that more than one `-r`s are combined in the right order and deduplicated:
929 929
930 930 $ hg log -T '{rev}\n' -r 3 -r 3 -r 4 -r 5:2 -r 'ancestors(4)'
931 931 3
932 932 4
933 933 5
934 934 2
935 935 0
936 936 1
937 937
938 938 test that `or` operation skips duplicated revisions from right-hand side
939 939
940 940 $ try 'reverse(1::5) or ancestors(4)'
941 941 (or
942 942 (func
943 943 ('symbol', 'reverse')
944 944 (dagrange
945 945 ('symbol', '1')
946 946 ('symbol', '5')))
947 947 (func
948 948 ('symbol', 'ancestors')
949 949 ('symbol', '4')))
950 950 * set:
951 951 <addset
952 952 <baseset [5, 3, 1]>,
953 953 <generatorset+>>
954 954 5
955 955 3
956 956 1
957 957 0
958 958 2
959 959 4
960 960 $ try 'sort(ancestors(4) or reverse(1::5))'
961 961 (func
962 962 ('symbol', 'sort')
963 963 (or
964 964 (func
965 965 ('symbol', 'ancestors')
966 966 ('symbol', '4'))
967 967 (func
968 968 ('symbol', 'reverse')
969 969 (dagrange
970 970 ('symbol', '1')
971 971 ('symbol', '5')))))
972 972 * set:
973 973 <addset+
974 974 <generatorset+>,
975 975 <baseset [5, 3, 1]>>
976 976 0
977 977 1
978 978 2
979 979 3
980 980 4
981 981 5
982 982
983 983 test optimization of trivial `or` operation
984 984
985 985 $ try --optimize '0|(1)|"2"|-2|tip|null'
986 986 (or
987 987 ('symbol', '0')
988 988 (group
989 989 ('symbol', '1'))
990 990 ('string', '2')
991 991 (negate
992 992 ('symbol', '2'))
993 993 ('symbol', 'tip')
994 994 ('symbol', 'null'))
995 995 * optimized:
996 996 (func
997 997 ('symbol', '_list')
998 998 ('string', '0\x001\x002\x00-2\x00tip\x00null'))
999 999 * set:
1000 1000 <baseset [0, 1, 2, 8, 9, -1]>
1001 1001 0
1002 1002 1
1003 1003 2
1004 1004 8
1005 1005 9
1006 1006 -1
1007 1007
1008 1008 $ try --optimize '0|1|2:3'
1009 1009 (or
1010 1010 ('symbol', '0')
1011 1011 ('symbol', '1')
1012 1012 (range
1013 1013 ('symbol', '2')
1014 1014 ('symbol', '3')))
1015 1015 * optimized:
1016 1016 (or
1017 1017 (func
1018 1018 ('symbol', '_list')
1019 1019 ('string', '0\x001'))
1020 1020 (range
1021 1021 ('symbol', '2')
1022 1022 ('symbol', '3')))
1023 1023 * set:
1024 1024 <addset
1025 1025 <baseset [0, 1]>,
1026 1026 <spanset+ 2:3>>
1027 1027 0
1028 1028 1
1029 1029 2
1030 1030 3
1031 1031
1032 1032 $ try --optimize '0:1|2|3:4|5|6'
1033 1033 (or
1034 1034 (range
1035 1035 ('symbol', '0')
1036 1036 ('symbol', '1'))
1037 1037 ('symbol', '2')
1038 1038 (range
1039 1039 ('symbol', '3')
1040 1040 ('symbol', '4'))
1041 1041 ('symbol', '5')
1042 1042 ('symbol', '6'))
1043 1043 * optimized:
1044 1044 (or
1045 1045 (range
1046 1046 ('symbol', '0')
1047 1047 ('symbol', '1'))
1048 1048 ('symbol', '2')
1049 1049 (range
1050 1050 ('symbol', '3')
1051 1051 ('symbol', '4'))
1052 1052 (func
1053 1053 ('symbol', '_list')
1054 1054 ('string', '5\x006')))
1055 1055 * set:
1056 1056 <addset
1057 1057 <addset
1058 1058 <spanset+ 0:1>,
1059 1059 <baseset [2]>>,
1060 1060 <addset
1061 1061 <spanset+ 3:4>,
1062 1062 <baseset [5, 6]>>>
1063 1063 0
1064 1064 1
1065 1065 2
1066 1066 3
1067 1067 4
1068 1068 5
1069 1069 6
1070 1070
1071 1071 test that `_list` should be narrowed by provided `subset`
1072 1072
1073 1073 $ log '0:2 and (null|1|2|3)'
1074 1074 1
1075 1075 2
1076 1076
1077 1077 test that `_list` should remove duplicates
1078 1078
1079 1079 $ log '0|1|2|1|2|-1|tip'
1080 1080 0
1081 1081 1
1082 1082 2
1083 1083 9
1084 1084
1085 1085 test unknown revision in `_list`
1086 1086
1087 1087 $ log '0|unknown'
1088 1088 abort: unknown revision 'unknown'!
1089 1089 [255]
1090 1090
1091 1091 test integer range in `_list`
1092 1092
1093 1093 $ log '-1|-10'
1094 1094 9
1095 1095 0
1096 1096
1097 1097 $ log '-10|-11'
1098 1098 abort: unknown revision '-11'!
1099 1099 [255]
1100 1100
1101 1101 $ log '9|10'
1102 1102 abort: unknown revision '10'!
1103 1103 [255]
1104 1104
1105 1105 test '0000' != '0' in `_list`
1106 1106
1107 1107 $ log '0|0000'
1108 1108 0
1109 1109 -1
1110 1110
1111 1111 test that chained `or` operations make balanced addsets
1112 1112
1113 1113 $ try '0:1|1:2|2:3|3:4|4:5'
1114 1114 (or
1115 1115 (range
1116 1116 ('symbol', '0')
1117 1117 ('symbol', '1'))
1118 1118 (range
1119 1119 ('symbol', '1')
1120 1120 ('symbol', '2'))
1121 1121 (range
1122 1122 ('symbol', '2')
1123 1123 ('symbol', '3'))
1124 1124 (range
1125 1125 ('symbol', '3')
1126 1126 ('symbol', '4'))
1127 1127 (range
1128 1128 ('symbol', '4')
1129 1129 ('symbol', '5')))
1130 1130 * set:
1131 1131 <addset
1132 1132 <addset
1133 1133 <spanset+ 0:1>,
1134 1134 <spanset+ 1:2>>,
1135 1135 <addset
1136 1136 <spanset+ 2:3>,
1137 1137 <addset
1138 1138 <spanset+ 3:4>,
1139 1139 <spanset+ 4:5>>>>
1140 1140 0
1141 1141 1
1142 1142 2
1143 1143 3
1144 1144 4
1145 1145 5
1146 1146
1147 1147 test that chained `or` operations never eat up stack (issue4624)
1148 1148 (uses `0:1` instead of `0` to avoid future optimization of trivial revisions)
1149 1149
1150 1150 $ hg log -T '{rev}\n' -r "`python -c "print '|'.join(['0:1'] * 500)"`"
1151 1151 0
1152 1152 1
1153 1153
1154 1154 test that repeated `-r` options never eat up stack (issue4565)
1155 1155 (uses `-r 0::1` to avoid possible optimization at old-style parser)
1156 1156
1157 1157 $ hg log -T '{rev}\n' `python -c "for i in xrange(500): print '-r 0::1 ',"`
1158 1158 0
1159 1159 1
1160 1160
1161 1161 check that conversion to only works
1162 1162 $ try --optimize '::3 - ::1'
1163 1163 (minus
1164 1164 (dagrangepre
1165 1165 ('symbol', '3'))
1166 1166 (dagrangepre
1167 1167 ('symbol', '1')))
1168 1168 * optimized:
1169 1169 (func
1170 1170 ('symbol', 'only')
1171 1171 (list
1172 1172 ('symbol', '3')
1173 1173 ('symbol', '1')))
1174 1174 * set:
1175 1175 <baseset+ [3]>
1176 1176 3
1177 1177 $ try --optimize 'ancestors(1) - ancestors(3)'
1178 1178 (minus
1179 1179 (func
1180 1180 ('symbol', 'ancestors')
1181 1181 ('symbol', '1'))
1182 1182 (func
1183 1183 ('symbol', 'ancestors')
1184 1184 ('symbol', '3')))
1185 1185 * optimized:
1186 1186 (func
1187 1187 ('symbol', 'only')
1188 1188 (list
1189 1189 ('symbol', '1')
1190 1190 ('symbol', '3')))
1191 1191 * set:
1192 1192 <baseset+ []>
1193 1193 $ try --optimize 'not ::2 and ::6'
1194 1194 (and
1195 1195 (not
1196 1196 (dagrangepre
1197 1197 ('symbol', '2')))
1198 1198 (dagrangepre
1199 1199 ('symbol', '6')))
1200 1200 * optimized:
1201 1201 (func
1202 1202 ('symbol', 'only')
1203 1203 (list
1204 1204 ('symbol', '6')
1205 1205 ('symbol', '2')))
1206 1206 * set:
1207 1207 <baseset+ [3, 4, 5, 6]>
1208 1208 3
1209 1209 4
1210 1210 5
1211 1211 6
1212 1212 $ try --optimize 'ancestors(6) and not ancestors(4)'
1213 1213 (and
1214 1214 (func
1215 1215 ('symbol', 'ancestors')
1216 1216 ('symbol', '6'))
1217 1217 (not
1218 1218 (func
1219 1219 ('symbol', 'ancestors')
1220 1220 ('symbol', '4'))))
1221 1221 * optimized:
1222 1222 (func
1223 1223 ('symbol', 'only')
1224 1224 (list
1225 1225 ('symbol', '6')
1226 1226 ('symbol', '4')))
1227 1227 * set:
1228 1228 <baseset+ [3, 5, 6]>
1229 1229 3
1230 1230 5
1231 1231 6
1232 1232
1233 no crash by empty group "()" while optimizing to "only()"
1234
1235 $ try --optimize '::1 and ()'
1236 (and
1237 (dagrangepre
1238 ('symbol', '1'))
1239 (group
1240 None))
1241 * optimized:
1242 (and
1243 None
1244 (func
1245 ('symbol', 'ancestors')
1246 ('symbol', '1')))
1247 hg: parse error: missing argument
1248 [255]
1249
1233 1250 we can use patterns when searching for tags
1234 1251
1235 1252 $ log 'tag("1..*")'
1236 1253 abort: tag '1..*' does not exist!
1237 1254 [255]
1238 1255 $ log 'tag("re:1..*")'
1239 1256 6
1240 1257 $ log 'tag("re:[0-9].[0-9]")'
1241 1258 6
1242 1259 $ log 'tag("literal:1.0")'
1243 1260 6
1244 1261 $ log 'tag("re:0..*")'
1245 1262
1246 1263 $ log 'tag(unknown)'
1247 1264 abort: tag 'unknown' does not exist!
1248 1265 [255]
1249 1266 $ log 'tag("re:unknown")'
1250 1267 $ log 'present(tag("unknown"))'
1251 1268 $ log 'present(tag("re:unknown"))'
1252 1269 $ log 'branch(unknown)'
1253 1270 abort: unknown revision 'unknown'!
1254 1271 [255]
1255 1272 $ log 'branch("re:unknown")'
1256 1273 $ log 'present(branch("unknown"))'
1257 1274 $ log 'present(branch("re:unknown"))'
1258 1275 $ log 'user(bob)'
1259 1276 2
1260 1277
1261 1278 $ log '4::8'
1262 1279 4
1263 1280 8
1264 1281 $ log '4:8'
1265 1282 4
1266 1283 5
1267 1284 6
1268 1285 7
1269 1286 8
1270 1287
1271 1288 $ log 'sort(!merge() & (modifies(b) | user(bob) | keyword(bug) | keyword(issue) & 1::9), "-date")'
1272 1289 4
1273 1290 2
1274 1291 5
1275 1292
1276 1293 $ log 'not 0 and 0:2'
1277 1294 1
1278 1295 2
1279 1296 $ log 'not 1 and 0:2'
1280 1297 0
1281 1298 2
1282 1299 $ log 'not 2 and 0:2'
1283 1300 0
1284 1301 1
1285 1302 $ log '(1 and 2)::'
1286 1303 $ log '(1 and 2):'
1287 1304 $ log '(1 and 2):3'
1288 1305 $ log 'sort(head(), -rev)'
1289 1306 9
1290 1307 7
1291 1308 6
1292 1309 5
1293 1310 4
1294 1311 3
1295 1312 2
1296 1313 1
1297 1314 0
1298 1315 $ log '4::8 - 8'
1299 1316 4
1300 1317 $ log 'matching(1 or 2 or 3) and (2 or 3 or 1)'
1301 1318 2
1302 1319 3
1303 1320 1
1304 1321
1305 1322 $ log 'named("unknown")'
1306 1323 abort: namespace 'unknown' does not exist!
1307 1324 [255]
1308 1325 $ log 'named("re:unknown")'
1309 1326 abort: no namespace exists that match 'unknown'!
1310 1327 [255]
1311 1328 $ log 'present(named("unknown"))'
1312 1329 $ log 'present(named("re:unknown"))'
1313 1330
1314 1331 $ log 'tag()'
1315 1332 6
1316 1333 $ log 'named("tags")'
1317 1334 6
1318 1335
1319 1336 issue2437
1320 1337
1321 1338 $ log '3 and p1(5)'
1322 1339 3
1323 1340 $ log '4 and p2(6)'
1324 1341 4
1325 1342 $ log '1 and parents(:2)'
1326 1343 1
1327 1344 $ log '2 and children(1:)'
1328 1345 2
1329 1346 $ log 'roots(all()) or roots(all())'
1330 1347 0
1331 1348 $ hg debugrevspec 'roots(all()) or roots(all())'
1332 1349 0
1333 1350 $ log 'heads(branch(Γ©)) or heads(branch(Γ©))'
1334 1351 9
1335 1352 $ log 'ancestors(8) and (heads(branch("-a-b-c-")) or heads(branch(Γ©)))'
1336 1353 4
1337 1354
1338 1355 issue2654: report a parse error if the revset was not completely parsed
1339 1356
1340 1357 $ log '1 OR 2'
1341 1358 hg: parse error at 2: invalid token
1342 1359 [255]
1343 1360
1344 1361 or operator should preserve ordering:
1345 1362 $ log 'reverse(2::4) or tip'
1346 1363 4
1347 1364 2
1348 1365 9
1349 1366
1350 1367 parentrevspec
1351 1368
1352 1369 $ log 'merge()^0'
1353 1370 6
1354 1371 $ log 'merge()^'
1355 1372 5
1356 1373 $ log 'merge()^1'
1357 1374 5
1358 1375 $ log 'merge()^2'
1359 1376 4
1360 1377 $ log 'merge()^^'
1361 1378 3
1362 1379 $ log 'merge()^1^'
1363 1380 3
1364 1381 $ log 'merge()^^^'
1365 1382 1
1366 1383
1367 1384 $ log 'merge()~0'
1368 1385 6
1369 1386 $ log 'merge()~1'
1370 1387 5
1371 1388 $ log 'merge()~2'
1372 1389 3
1373 1390 $ log 'merge()~2^1'
1374 1391 1
1375 1392 $ log 'merge()~3'
1376 1393 1
1377 1394
1378 1395 $ log '(-3:tip)^'
1379 1396 4
1380 1397 6
1381 1398 8
1382 1399
1383 1400 $ log 'tip^foo'
1384 1401 hg: parse error: ^ expects a number 0, 1, or 2
1385 1402 [255]
1386 1403
1387 1404 Bogus function gets suggestions
1388 1405 $ log 'add()'
1389 1406 hg: parse error: unknown identifier: add
1390 1407 (did you mean 'adds'?)
1391 1408 [255]
1392 1409 $ log 'added()'
1393 1410 hg: parse error: unknown identifier: added
1394 1411 (did you mean 'adds'?)
1395 1412 [255]
1396 1413 $ log 'remo()'
1397 1414 hg: parse error: unknown identifier: remo
1398 1415 (did you mean one of remote, removes?)
1399 1416 [255]
1400 1417 $ log 'babar()'
1401 1418 hg: parse error: unknown identifier: babar
1402 1419 [255]
1403 1420
1404 1421 Bogus function with a similar internal name doesn't suggest the internal name
1405 1422 $ log 'matches()'
1406 1423 hg: parse error: unknown identifier: matches
1407 1424 (did you mean 'matching'?)
1408 1425 [255]
1409 1426
1410 1427 Undocumented functions aren't suggested as similar either
1411 1428 $ log 'wdir2()'
1412 1429 hg: parse error: unknown identifier: wdir2
1413 1430 [255]
1414 1431
1415 1432 multiple revspecs
1416 1433
1417 1434 $ hg log -r 'tip~1:tip' -r 'tip~2:tip~1' --template '{rev}\n'
1418 1435 8
1419 1436 9
1420 1437 4
1421 1438 5
1422 1439 6
1423 1440 7
1424 1441
1425 1442 test usage in revpair (with "+")
1426 1443
1427 1444 (real pair)
1428 1445
1429 1446 $ hg diff -r 'tip^^' -r 'tip'
1430 1447 diff -r 2326846efdab -r 24286f4ae135 .hgtags
1431 1448 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1432 1449 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
1433 1450 @@ -0,0 +1,1 @@
1434 1451 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
1435 1452 $ hg diff -r 'tip^^::tip'
1436 1453 diff -r 2326846efdab -r 24286f4ae135 .hgtags
1437 1454 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1438 1455 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
1439 1456 @@ -0,0 +1,1 @@
1440 1457 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
1441 1458
1442 1459 (single rev)
1443 1460
1444 1461 $ hg diff -r 'tip^' -r 'tip^'
1445 1462 $ hg diff -r 'tip^::tip^ or tip^'
1446 1463
1447 1464 (single rev that does not looks like a range)
1448 1465
1449 1466 $ hg diff -r 'tip^ or tip^'
1450 1467 diff -r d5d0dcbdc4d9 .hgtags
1451 1468 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1452 1469 +++ b/.hgtags * (glob)
1453 1470 @@ -0,0 +1,1 @@
1454 1471 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
1455 1472
1456 1473 (no rev)
1457 1474
1458 1475 $ hg diff -r 'author("babar") or author("celeste")'
1459 1476 abort: empty revision range
1460 1477 [255]
1461 1478
1462 1479 aliases:
1463 1480
1464 1481 $ echo '[revsetalias]' >> .hg/hgrc
1465 1482 $ echo 'm = merge()' >> .hg/hgrc
1466 1483 (revset aliases can override builtin revsets)
1467 1484 $ echo 'p2($1) = p1($1)' >> .hg/hgrc
1468 1485 $ echo 'sincem = descendants(m)' >> .hg/hgrc
1469 1486 $ echo 'd($1) = reverse(sort($1, date))' >> .hg/hgrc
1470 1487 $ echo 'rs(ARG1, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
1471 1488 $ echo 'rs4(ARG1, ARGA, ARGB, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
1472 1489
1473 1490 $ try m
1474 1491 ('symbol', 'm')
1475 1492 (func
1476 1493 ('symbol', 'merge')
1477 1494 None)
1478 1495 * set:
1479 1496 <filteredset
1480 1497 <fullreposet+ 0:9>>
1481 1498 6
1482 1499
1483 1500 $ HGPLAIN=1
1484 1501 $ export HGPLAIN
1485 1502 $ try m
1486 1503 ('symbol', 'm')
1487 1504 abort: unknown revision 'm'!
1488 1505 [255]
1489 1506
1490 1507 $ HGPLAINEXCEPT=revsetalias
1491 1508 $ export HGPLAINEXCEPT
1492 1509 $ try m
1493 1510 ('symbol', 'm')
1494 1511 (func
1495 1512 ('symbol', 'merge')
1496 1513 None)
1497 1514 * set:
1498 1515 <filteredset
1499 1516 <fullreposet+ 0:9>>
1500 1517 6
1501 1518
1502 1519 $ unset HGPLAIN
1503 1520 $ unset HGPLAINEXCEPT
1504 1521
1505 1522 $ try 'p2(.)'
1506 1523 (func
1507 1524 ('symbol', 'p2')
1508 1525 ('symbol', '.'))
1509 1526 (func
1510 1527 ('symbol', 'p1')
1511 1528 ('symbol', '.'))
1512 1529 * set:
1513 1530 <baseset+ [8]>
1514 1531 8
1515 1532
1516 1533 $ HGPLAIN=1
1517 1534 $ export HGPLAIN
1518 1535 $ try 'p2(.)'
1519 1536 (func
1520 1537 ('symbol', 'p2')
1521 1538 ('symbol', '.'))
1522 1539 * set:
1523 1540 <baseset+ []>
1524 1541
1525 1542 $ HGPLAINEXCEPT=revsetalias
1526 1543 $ export HGPLAINEXCEPT
1527 1544 $ try 'p2(.)'
1528 1545 (func
1529 1546 ('symbol', 'p2')
1530 1547 ('symbol', '.'))
1531 1548 (func
1532 1549 ('symbol', 'p1')
1533 1550 ('symbol', '.'))
1534 1551 * set:
1535 1552 <baseset+ [8]>
1536 1553 8
1537 1554
1538 1555 $ unset HGPLAIN
1539 1556 $ unset HGPLAINEXCEPT
1540 1557
1541 1558 test alias recursion
1542 1559
1543 1560 $ try sincem
1544 1561 ('symbol', 'sincem')
1545 1562 (func
1546 1563 ('symbol', 'descendants')
1547 1564 (func
1548 1565 ('symbol', 'merge')
1549 1566 None))
1550 1567 * set:
1551 1568 <addset+
1552 1569 <filteredset
1553 1570 <fullreposet+ 0:9>>,
1554 1571 <generatorset+>>
1555 1572 6
1556 1573 7
1557 1574
1558 1575 test infinite recursion
1559 1576
1560 1577 $ echo 'recurse1 = recurse2' >> .hg/hgrc
1561 1578 $ echo 'recurse2 = recurse1' >> .hg/hgrc
1562 1579 $ try recurse1
1563 1580 ('symbol', 'recurse1')
1564 1581 hg: parse error: infinite expansion of revset alias "recurse1" detected
1565 1582 [255]
1566 1583
1567 1584 $ echo 'level1($1, $2) = $1 or $2' >> .hg/hgrc
1568 1585 $ echo 'level2($1, $2) = level1($2, $1)' >> .hg/hgrc
1569 1586 $ try "level2(level1(1, 2), 3)"
1570 1587 (func
1571 1588 ('symbol', 'level2')
1572 1589 (list
1573 1590 (func
1574 1591 ('symbol', 'level1')
1575 1592 (list
1576 1593 ('symbol', '1')
1577 1594 ('symbol', '2')))
1578 1595 ('symbol', '3')))
1579 1596 (or
1580 1597 ('symbol', '3')
1581 1598 (or
1582 1599 ('symbol', '1')
1583 1600 ('symbol', '2')))
1584 1601 * set:
1585 1602 <addset
1586 1603 <baseset [3]>,
1587 1604 <baseset [1, 2]>>
1588 1605 3
1589 1606 1
1590 1607 2
1591 1608
1592 1609 test nesting and variable passing
1593 1610
1594 1611 $ echo 'nested($1) = nested2($1)' >> .hg/hgrc
1595 1612 $ echo 'nested2($1) = nested3($1)' >> .hg/hgrc
1596 1613 $ echo 'nested3($1) = max($1)' >> .hg/hgrc
1597 1614 $ try 'nested(2:5)'
1598 1615 (func
1599 1616 ('symbol', 'nested')
1600 1617 (range
1601 1618 ('symbol', '2')
1602 1619 ('symbol', '5')))
1603 1620 (func
1604 1621 ('symbol', 'max')
1605 1622 (range
1606 1623 ('symbol', '2')
1607 1624 ('symbol', '5')))
1608 1625 * set:
1609 1626 <baseset [5]>
1610 1627 5
1611 1628
1612 1629 test chained `or` operations are flattened at parsing phase
1613 1630
1614 1631 $ echo 'chainedorops($1, $2, $3) = $1|$2|$3' >> .hg/hgrc
1615 1632 $ try 'chainedorops(0:1, 1:2, 2:3)'
1616 1633 (func
1617 1634 ('symbol', 'chainedorops')
1618 1635 (list
1619 1636 (list
1620 1637 (range
1621 1638 ('symbol', '0')
1622 1639 ('symbol', '1'))
1623 1640 (range
1624 1641 ('symbol', '1')
1625 1642 ('symbol', '2')))
1626 1643 (range
1627 1644 ('symbol', '2')
1628 1645 ('symbol', '3'))))
1629 1646 (or
1630 1647 (range
1631 1648 ('symbol', '0')
1632 1649 ('symbol', '1'))
1633 1650 (range
1634 1651 ('symbol', '1')
1635 1652 ('symbol', '2'))
1636 1653 (range
1637 1654 ('symbol', '2')
1638 1655 ('symbol', '3')))
1639 1656 * set:
1640 1657 <addset
1641 1658 <spanset+ 0:1>,
1642 1659 <addset
1643 1660 <spanset+ 1:2>,
1644 1661 <spanset+ 2:3>>>
1645 1662 0
1646 1663 1
1647 1664 2
1648 1665 3
1649 1666
1650 1667 test variable isolation, variable placeholders are rewritten as string
1651 1668 then parsed and matched again as string. Check they do not leak too
1652 1669 far away.
1653 1670
1654 1671 $ echo 'injectparamasstring = max("$1")' >> .hg/hgrc
1655 1672 $ echo 'callinjection($1) = descendants(injectparamasstring)' >> .hg/hgrc
1656 1673 $ try 'callinjection(2:5)'
1657 1674 (func
1658 1675 ('symbol', 'callinjection')
1659 1676 (range
1660 1677 ('symbol', '2')
1661 1678 ('symbol', '5')))
1662 1679 (func
1663 1680 ('symbol', 'descendants')
1664 1681 (func
1665 1682 ('symbol', 'max')
1666 1683 ('string', '$1')))
1667 1684 abort: unknown revision '$1'!
1668 1685 [255]
1669 1686
1670 1687 $ echo 'injectparamasstring2 = max(_aliasarg("$1"))' >> .hg/hgrc
1671 1688 $ echo 'callinjection2($1) = descendants(injectparamasstring2)' >> .hg/hgrc
1672 1689 $ try 'callinjection2(2:5)'
1673 1690 (func
1674 1691 ('symbol', 'callinjection2')
1675 1692 (range
1676 1693 ('symbol', '2')
1677 1694 ('symbol', '5')))
1678 1695 abort: failed to parse the definition of revset alias "injectparamasstring2": unknown identifier: _aliasarg
1679 1696 [255]
1680 1697 $ hg debugrevspec --debug --config revsetalias.anotherbadone='branch(' "tip"
1681 1698 ('symbol', 'tip')
1682 1699 warning: failed to parse the definition of revset alias "anotherbadone": at 7: not a prefix: end
1683 1700 warning: failed to parse the definition of revset alias "injectparamasstring2": unknown identifier: _aliasarg
1684 1701 * set:
1685 1702 <baseset [9]>
1686 1703 9
1687 1704 >>> data = file('.hg/hgrc', 'rb').read()
1688 1705 >>> file('.hg/hgrc', 'wb').write(data.replace('_aliasarg', ''))
1689 1706
1690 1707 $ try 'tip'
1691 1708 ('symbol', 'tip')
1692 1709 * set:
1693 1710 <baseset [9]>
1694 1711 9
1695 1712
1696 1713 $ hg debugrevspec --debug --config revsetalias.'bad name'='tip' "tip"
1697 1714 ('symbol', 'tip')
1698 1715 warning: failed to parse the declaration of revset alias "bad name": at 4: invalid token
1699 1716 * set:
1700 1717 <baseset [9]>
1701 1718 9
1702 1719 $ echo 'strictreplacing($1, $10) = $10 or desc("$1")' >> .hg/hgrc
1703 1720 $ try 'strictreplacing("foo", tip)'
1704 1721 (func
1705 1722 ('symbol', 'strictreplacing')
1706 1723 (list
1707 1724 ('string', 'foo')
1708 1725 ('symbol', 'tip')))
1709 1726 (or
1710 1727 ('symbol', 'tip')
1711 1728 (func
1712 1729 ('symbol', 'desc')
1713 1730 ('string', '$1')))
1714 1731 * set:
1715 1732 <addset
1716 1733 <baseset [9]>,
1717 1734 <filteredset
1718 1735 <fullreposet+ 0:9>>>
1719 1736 9
1720 1737
1721 1738 $ try 'd(2:5)'
1722 1739 (func
1723 1740 ('symbol', 'd')
1724 1741 (range
1725 1742 ('symbol', '2')
1726 1743 ('symbol', '5')))
1727 1744 (func
1728 1745 ('symbol', 'reverse')
1729 1746 (func
1730 1747 ('symbol', 'sort')
1731 1748 (list
1732 1749 (range
1733 1750 ('symbol', '2')
1734 1751 ('symbol', '5'))
1735 1752 ('symbol', 'date'))))
1736 1753 * set:
1737 1754 <baseset [4, 5, 3, 2]>
1738 1755 4
1739 1756 5
1740 1757 3
1741 1758 2
1742 1759 $ try 'rs(2 or 3, date)'
1743 1760 (func
1744 1761 ('symbol', 'rs')
1745 1762 (list
1746 1763 (or
1747 1764 ('symbol', '2')
1748 1765 ('symbol', '3'))
1749 1766 ('symbol', 'date')))
1750 1767 (func
1751 1768 ('symbol', 'reverse')
1752 1769 (func
1753 1770 ('symbol', 'sort')
1754 1771 (list
1755 1772 (or
1756 1773 ('symbol', '2')
1757 1774 ('symbol', '3'))
1758 1775 ('symbol', 'date'))))
1759 1776 * set:
1760 1777 <baseset [3, 2]>
1761 1778 3
1762 1779 2
1763 1780 $ try 'rs()'
1764 1781 (func
1765 1782 ('symbol', 'rs')
1766 1783 None)
1767 1784 hg: parse error: invalid number of arguments: 0
1768 1785 [255]
1769 1786 $ try 'rs(2)'
1770 1787 (func
1771 1788 ('symbol', 'rs')
1772 1789 ('symbol', '2'))
1773 1790 hg: parse error: invalid number of arguments: 1
1774 1791 [255]
1775 1792 $ try 'rs(2, data, 7)'
1776 1793 (func
1777 1794 ('symbol', 'rs')
1778 1795 (list
1779 1796 (list
1780 1797 ('symbol', '2')
1781 1798 ('symbol', 'data'))
1782 1799 ('symbol', '7')))
1783 1800 hg: parse error: invalid number of arguments: 3
1784 1801 [255]
1785 1802 $ try 'rs4(2 or 3, x, x, date)'
1786 1803 (func
1787 1804 ('symbol', 'rs4')
1788 1805 (list
1789 1806 (list
1790 1807 (list
1791 1808 (or
1792 1809 ('symbol', '2')
1793 1810 ('symbol', '3'))
1794 1811 ('symbol', 'x'))
1795 1812 ('symbol', 'x'))
1796 1813 ('symbol', 'date')))
1797 1814 (func
1798 1815 ('symbol', 'reverse')
1799 1816 (func
1800 1817 ('symbol', 'sort')
1801 1818 (list
1802 1819 (or
1803 1820 ('symbol', '2')
1804 1821 ('symbol', '3'))
1805 1822 ('symbol', 'date'))))
1806 1823 * set:
1807 1824 <baseset [3, 2]>
1808 1825 3
1809 1826 2
1810 1827
1811 1828 issue4553: check that revset aliases override existing hash prefix
1812 1829
1813 1830 $ hg log -qr e
1814 1831 6:e0cc66ef77e8
1815 1832
1816 1833 $ hg log -qr e --config revsetalias.e="all()"
1817 1834 0:2785f51eece5
1818 1835 1:d75937da8da0
1819 1836 2:5ed5505e9f1c
1820 1837 3:8528aa5637f2
1821 1838 4:2326846efdab
1822 1839 5:904fa392b941
1823 1840 6:e0cc66ef77e8
1824 1841 7:013af1973af4
1825 1842 8:d5d0dcbdc4d9
1826 1843 9:24286f4ae135
1827 1844
1828 1845 $ hg log -qr e: --config revsetalias.e="0"
1829 1846 0:2785f51eece5
1830 1847 1:d75937da8da0
1831 1848 2:5ed5505e9f1c
1832 1849 3:8528aa5637f2
1833 1850 4:2326846efdab
1834 1851 5:904fa392b941
1835 1852 6:e0cc66ef77e8
1836 1853 7:013af1973af4
1837 1854 8:d5d0dcbdc4d9
1838 1855 9:24286f4ae135
1839 1856
1840 1857 $ hg log -qr :e --config revsetalias.e="9"
1841 1858 0:2785f51eece5
1842 1859 1:d75937da8da0
1843 1860 2:5ed5505e9f1c
1844 1861 3:8528aa5637f2
1845 1862 4:2326846efdab
1846 1863 5:904fa392b941
1847 1864 6:e0cc66ef77e8
1848 1865 7:013af1973af4
1849 1866 8:d5d0dcbdc4d9
1850 1867 9:24286f4ae135
1851 1868
1852 1869 $ hg log -qr e:
1853 1870 6:e0cc66ef77e8
1854 1871 7:013af1973af4
1855 1872 8:d5d0dcbdc4d9
1856 1873 9:24286f4ae135
1857 1874
1858 1875 $ hg log -qr :e
1859 1876 0:2785f51eece5
1860 1877 1:d75937da8da0
1861 1878 2:5ed5505e9f1c
1862 1879 3:8528aa5637f2
1863 1880 4:2326846efdab
1864 1881 5:904fa392b941
1865 1882 6:e0cc66ef77e8
1866 1883
1867 1884 issue2549 - correct optimizations
1868 1885
1869 1886 $ log 'limit(1 or 2 or 3, 2) and not 2'
1870 1887 1
1871 1888 $ log 'max(1 or 2) and not 2'
1872 1889 $ log 'min(1 or 2) and not 1'
1873 1890 $ log 'last(1 or 2, 1) and not 2'
1874 1891
1875 1892 issue4289 - ordering of built-ins
1876 1893 $ hg log -M -q -r 3:2
1877 1894 3:8528aa5637f2
1878 1895 2:5ed5505e9f1c
1879 1896
1880 1897 test revsets started with 40-chars hash (issue3669)
1881 1898
1882 1899 $ ISSUE3669_TIP=`hg tip --template '{node}'`
1883 1900 $ hg log -r "${ISSUE3669_TIP}" --template '{rev}\n'
1884 1901 9
1885 1902 $ hg log -r "${ISSUE3669_TIP}^" --template '{rev}\n'
1886 1903 8
1887 1904
1888 1905 test or-ed indirect predicates (issue3775)
1889 1906
1890 1907 $ log '6 or 6^1' | sort
1891 1908 5
1892 1909 6
1893 1910 $ log '6^1 or 6' | sort
1894 1911 5
1895 1912 6
1896 1913 $ log '4 or 4~1' | sort
1897 1914 2
1898 1915 4
1899 1916 $ log '4~1 or 4' | sort
1900 1917 2
1901 1918 4
1902 1919 $ log '(0 or 2):(4 or 6) or 0 or 6' | sort
1903 1920 0
1904 1921 1
1905 1922 2
1906 1923 3
1907 1924 4
1908 1925 5
1909 1926 6
1910 1927 $ log '0 or 6 or (0 or 2):(4 or 6)' | sort
1911 1928 0
1912 1929 1
1913 1930 2
1914 1931 3
1915 1932 4
1916 1933 5
1917 1934 6
1918 1935
1919 1936 tests for 'remote()' predicate:
1920 1937 #. (csets in remote) (id) (remote)
1921 1938 1. less than local current branch "default"
1922 1939 2. same with local specified "default"
1923 1940 3. more than local specified specified
1924 1941
1925 1942 $ hg clone --quiet -U . ../remote3
1926 1943 $ cd ../remote3
1927 1944 $ hg update -q 7
1928 1945 $ echo r > r
1929 1946 $ hg ci -Aqm 10
1930 1947 $ log 'remote()'
1931 1948 7
1932 1949 $ log 'remote("a-b-c-")'
1933 1950 2
1934 1951 $ cd ../repo
1935 1952 $ log 'remote(".a.b.c.", "../remote3")'
1936 1953
1937 1954 tests for concatenation of strings/symbols by "##"
1938 1955
1939 1956 $ try "278 ## '5f5' ## 1ee ## 'ce5'"
1940 1957 (_concat
1941 1958 (_concat
1942 1959 (_concat
1943 1960 ('symbol', '278')
1944 1961 ('string', '5f5'))
1945 1962 ('symbol', '1ee'))
1946 1963 ('string', 'ce5'))
1947 1964 ('string', '2785f51eece5')
1948 1965 * set:
1949 1966 <baseset [0]>
1950 1967 0
1951 1968
1952 1969 $ echo 'cat4($1, $2, $3, $4) = $1 ## $2 ## $3 ## $4' >> .hg/hgrc
1953 1970 $ try "cat4(278, '5f5', 1ee, 'ce5')"
1954 1971 (func
1955 1972 ('symbol', 'cat4')
1956 1973 (list
1957 1974 (list
1958 1975 (list
1959 1976 ('symbol', '278')
1960 1977 ('string', '5f5'))
1961 1978 ('symbol', '1ee'))
1962 1979 ('string', 'ce5')))
1963 1980 (_concat
1964 1981 (_concat
1965 1982 (_concat
1966 1983 ('symbol', '278')
1967 1984 ('string', '5f5'))
1968 1985 ('symbol', '1ee'))
1969 1986 ('string', 'ce5'))
1970 1987 ('string', '2785f51eece5')
1971 1988 * set:
1972 1989 <baseset [0]>
1973 1990 0
1974 1991
1975 1992 (check concatenation in alias nesting)
1976 1993
1977 1994 $ echo 'cat2($1, $2) = $1 ## $2' >> .hg/hgrc
1978 1995 $ echo 'cat2x2($1, $2, $3, $4) = cat2($1 ## $2, $3 ## $4)' >> .hg/hgrc
1979 1996 $ log "cat2x2(278, '5f5', 1ee, 'ce5')"
1980 1997 0
1981 1998
1982 1999 (check operator priority)
1983 2000
1984 2001 $ echo 'cat2n2($1, $2, $3, $4) = $1 ## $2 or $3 ## $4~2' >> .hg/hgrc
1985 2002 $ log "cat2n2(2785f5, 1eece5, 24286f, 4ae135)"
1986 2003 0
1987 2004 4
1988 2005
1989 2006 $ cd ..
1990 2007
1991 2008 prepare repository that has "default" branches of multiple roots
1992 2009
1993 2010 $ hg init namedbranch
1994 2011 $ cd namedbranch
1995 2012
1996 2013 $ echo default0 >> a
1997 2014 $ hg ci -Aqm0
1998 2015 $ echo default1 >> a
1999 2016 $ hg ci -m1
2000 2017
2001 2018 $ hg branch -q stable
2002 2019 $ echo stable2 >> a
2003 2020 $ hg ci -m2
2004 2021 $ echo stable3 >> a
2005 2022 $ hg ci -m3
2006 2023
2007 2024 $ hg update -q null
2008 2025 $ echo default4 >> a
2009 2026 $ hg ci -Aqm4
2010 2027 $ echo default5 >> a
2011 2028 $ hg ci -m5
2012 2029
2013 2030 "null" revision belongs to "default" branch (issue4683)
2014 2031
2015 2032 $ log 'branch(null)'
2016 2033 0
2017 2034 1
2018 2035 4
2019 2036 5
2020 2037
2021 2038 "null" revision belongs to "default" branch, but it shouldn't appear in set
2022 2039 unless explicitly specified (issue4682)
2023 2040
2024 2041 $ log 'children(branch(default))'
2025 2042 1
2026 2043 2
2027 2044 5
2028 2045
2029 2046 $ cd ..
2030 2047
2031 2048 test author/desc/keyword in problematic encoding
2032 2049 # unicode: cp932:
2033 2050 # u30A2 0x83 0x41(= 'A')
2034 2051 # u30C2 0x83 0x61(= 'a')
2035 2052
2036 2053 $ hg init problematicencoding
2037 2054 $ cd problematicencoding
2038 2055
2039 2056 $ python > setup.sh <<EOF
2040 2057 > print u'''
2041 2058 > echo a > text
2042 2059 > hg add text
2043 2060 > hg --encoding utf-8 commit -u '\u30A2' -m none
2044 2061 > echo b > text
2045 2062 > hg --encoding utf-8 commit -u '\u30C2' -m none
2046 2063 > echo c > text
2047 2064 > hg --encoding utf-8 commit -u none -m '\u30A2'
2048 2065 > echo d > text
2049 2066 > hg --encoding utf-8 commit -u none -m '\u30C2'
2050 2067 > '''.encode('utf-8')
2051 2068 > EOF
2052 2069 $ sh < setup.sh
2053 2070
2054 2071 test in problematic encoding
2055 2072 $ python > test.sh <<EOF
2056 2073 > print u'''
2057 2074 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30A2)'
2058 2075 > echo ====
2059 2076 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30C2)'
2060 2077 > echo ====
2061 2078 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30A2)'
2062 2079 > echo ====
2063 2080 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30C2)'
2064 2081 > echo ====
2065 2082 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30A2)'
2066 2083 > echo ====
2067 2084 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30C2)'
2068 2085 > '''.encode('cp932')
2069 2086 > EOF
2070 2087 $ sh < test.sh
2071 2088 0
2072 2089 ====
2073 2090 1
2074 2091 ====
2075 2092 2
2076 2093 ====
2077 2094 3
2078 2095 ====
2079 2096 0
2080 2097 2
2081 2098 ====
2082 2099 1
2083 2100 3
2084 2101
2085 2102 test error message of bad revset
2086 2103 $ hg log -r 'foo\\'
2087 2104 hg: parse error at 3: syntax error in revset 'foo\\'
2088 2105 [255]
2089 2106
2090 2107 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now