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