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