##// END OF EJS Templates
revset: use nullrev constant in merge()
Yuya Nishihara -
r42633:d279e4f4 default
parent child Browse files
Show More
@@ -1,2414 +1,2415
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 from __future__ import absolute_import
9 9
10 10 import re
11 11
12 12 from .i18n import _
13 13 from . import (
14 14 dagop,
15 15 destutil,
16 16 diffutil,
17 17 encoding,
18 18 error,
19 19 hbisect,
20 20 match as matchmod,
21 21 node,
22 22 obsolete as obsmod,
23 23 obsutil,
24 24 pathutil,
25 25 phases,
26 26 pycompat,
27 27 registrar,
28 28 repoview,
29 29 revsetlang,
30 30 scmutil,
31 31 smartset,
32 32 stack as stackmod,
33 33 util,
34 34 )
35 35 from .utils import (
36 36 dateutil,
37 37 stringutil,
38 38 )
39 39
40 40 # helpers for processing parsed tree
41 41 getsymbol = revsetlang.getsymbol
42 42 getstring = revsetlang.getstring
43 43 getinteger = revsetlang.getinteger
44 44 getboolean = revsetlang.getboolean
45 45 getlist = revsetlang.getlist
46 46 getintrange = revsetlang.getintrange
47 47 getargs = revsetlang.getargs
48 48 getargsdict = revsetlang.getargsdict
49 49
50 50 baseset = smartset.baseset
51 51 generatorset = smartset.generatorset
52 52 spanset = smartset.spanset
53 53 fullreposet = smartset.fullreposet
54 54
55 55 # revisions not included in all(), but populated if specified
56 56 _virtualrevs = (node.nullrev, node.wdirrev)
57 57
58 58 # Constants for ordering requirement, used in getset():
59 59 #
60 60 # If 'define', any nested functions and operations MAY change the ordering of
61 61 # the entries in the set (but if changes the ordering, it MUST ALWAYS change
62 62 # it). If 'follow', any nested functions and operations MUST take the ordering
63 63 # specified by the first operand to the '&' operator.
64 64 #
65 65 # For instance,
66 66 #
67 67 # X & (Y | Z)
68 68 # ^ ^^^^^^^
69 69 # | follow
70 70 # define
71 71 #
72 72 # will be evaluated as 'or(y(x()), z(x()))', where 'x()' can change the order
73 73 # of the entries in the set, but 'y()', 'z()' and 'or()' shouldn't.
74 74 #
75 75 # 'any' means the order doesn't matter. For instance,
76 76 #
77 77 # (X & !Y) | ancestors(Z)
78 78 # ^ ^
79 79 # any any
80 80 #
81 81 # For 'X & !Y', 'X' decides the order and 'Y' is subtracted from 'X', so the
82 82 # order of 'Y' does not matter. For 'ancestors(Z)', Z's order does not matter
83 83 # since 'ancestors' does not care about the order of its argument.
84 84 #
85 85 # Currently, most revsets do not care about the order, so 'define' is
86 86 # equivalent to 'follow' for them, and the resulting order is based on the
87 87 # 'subset' parameter passed down to them:
88 88 #
89 89 # m = revset.match(...)
90 90 # m(repo, subset, order=defineorder)
91 91 # ^^^^^^
92 92 # For most revsets, 'define' means using the order this subset provides
93 93 #
94 94 # There are a few revsets that always redefine the order if 'define' is
95 95 # specified: 'sort(X)', 'reverse(X)', 'x:y'.
96 96 anyorder = 'any' # don't care the order, could be even random-shuffled
97 97 defineorder = 'define' # ALWAYS redefine, or ALWAYS follow the current order
98 98 followorder = 'follow' # MUST follow the current order
99 99
100 100 # helpers
101 101
102 102 def getset(repo, subset, x, order=defineorder):
103 103 if not x:
104 104 raise error.ParseError(_("missing argument"))
105 105 return methods[x[0]](repo, subset, *x[1:], order=order)
106 106
107 107 def _getrevsource(repo, r):
108 108 extra = repo[r].extra()
109 109 for label in ('source', 'transplant_source', 'rebase_source'):
110 110 if label in extra:
111 111 try:
112 112 return repo[extra[label]].rev()
113 113 except error.RepoLookupError:
114 114 pass
115 115 return None
116 116
117 117 def _sortedb(xs):
118 118 return sorted(pycompat.rapply(pycompat.maybebytestr, xs))
119 119
120 120 # operator methods
121 121
122 122 def stringset(repo, subset, x, order):
123 123 if not x:
124 124 raise error.ParseError(_("empty string is not a valid revision"))
125 125 x = scmutil.intrev(scmutil.revsymbol(repo, x))
126 126 if x in subset or x in _virtualrevs and isinstance(subset, fullreposet):
127 127 return baseset([x])
128 128 return baseset()
129 129
130 130 def rawsmartset(repo, subset, x, order):
131 131 """argument is already a smartset, use that directly"""
132 132 if order == followorder:
133 133 return subset & x
134 134 else:
135 135 return x & subset
136 136
137 137 def rangeset(repo, subset, x, y, order):
138 138 m = getset(repo, fullreposet(repo), x)
139 139 n = getset(repo, fullreposet(repo), y)
140 140
141 141 if not m or not n:
142 142 return baseset()
143 143 return _makerangeset(repo, subset, m.first(), n.last(), order)
144 144
145 145 def rangeall(repo, subset, x, order):
146 146 assert x is None
147 147 return _makerangeset(repo, subset, 0, repo.changelog.tiprev(), order)
148 148
149 149 def rangepre(repo, subset, y, order):
150 150 # ':y' can't be rewritten to '0:y' since '0' may be hidden
151 151 n = getset(repo, fullreposet(repo), y)
152 152 if not n:
153 153 return baseset()
154 154 return _makerangeset(repo, subset, 0, n.last(), order)
155 155
156 156 def rangepost(repo, subset, x, order):
157 157 m = getset(repo, fullreposet(repo), x)
158 158 if not m:
159 159 return baseset()
160 160 return _makerangeset(repo, subset, m.first(), repo.changelog.tiprev(),
161 161 order)
162 162
163 163 def _makerangeset(repo, subset, m, n, order):
164 164 if m == n:
165 165 r = baseset([m])
166 166 elif n == node.wdirrev:
167 167 r = spanset(repo, m, len(repo)) + baseset([n])
168 168 elif m == node.wdirrev:
169 169 r = baseset([m]) + spanset(repo, repo.changelog.tiprev(), n - 1)
170 170 elif m < n:
171 171 r = spanset(repo, m, n + 1)
172 172 else:
173 173 r = spanset(repo, m, n - 1)
174 174
175 175 if order == defineorder:
176 176 return r & subset
177 177 else:
178 178 # carrying the sorting over when possible would be more efficient
179 179 return subset & r
180 180
181 181 def dagrange(repo, subset, x, y, order):
182 182 r = fullreposet(repo)
183 183 xs = dagop.reachableroots(repo, getset(repo, r, x), getset(repo, r, y),
184 184 includepath=True)
185 185 return subset & xs
186 186
187 187 def andset(repo, subset, x, y, order):
188 188 if order == anyorder:
189 189 yorder = anyorder
190 190 else:
191 191 yorder = followorder
192 192 return getset(repo, getset(repo, subset, x, order), y, yorder)
193 193
194 194 def andsmallyset(repo, subset, x, y, order):
195 195 # 'andsmally(x, y)' is equivalent to 'and(x, y)', but faster when y is small
196 196 if order == anyorder:
197 197 yorder = anyorder
198 198 else:
199 199 yorder = followorder
200 200 return getset(repo, getset(repo, subset, y, yorder), x, order)
201 201
202 202 def differenceset(repo, subset, x, y, order):
203 203 return getset(repo, subset, x, order) - getset(repo, subset, y, anyorder)
204 204
205 205 def _orsetlist(repo, subset, xs, order):
206 206 assert xs
207 207 if len(xs) == 1:
208 208 return getset(repo, subset, xs[0], order)
209 209 p = len(xs) // 2
210 210 a = _orsetlist(repo, subset, xs[:p], order)
211 211 b = _orsetlist(repo, subset, xs[p:], order)
212 212 return a + b
213 213
214 214 def orset(repo, subset, x, order):
215 215 xs = getlist(x)
216 216 if not xs:
217 217 return baseset()
218 218 if order == followorder:
219 219 # slow path to take the subset order
220 220 return subset & _orsetlist(repo, fullreposet(repo), xs, anyorder)
221 221 else:
222 222 return _orsetlist(repo, subset, xs, order)
223 223
224 224 def notset(repo, subset, x, order):
225 225 return subset - getset(repo, subset, x, anyorder)
226 226
227 227 def relationset(repo, subset, x, y, order):
228 228 raise error.ParseError(_("can't use a relation in this context"))
229 229
230 230 def _splitrange(a, b):
231 231 """Split range with bounds a and b into two ranges at 0 and return two
232 232 tuples of numbers for use as startdepth and stopdepth arguments of
233 233 revancestors and revdescendants.
234 234
235 235 >>> _splitrange(-10, -5) # [-10:-5]
236 236 ((5, 11), (None, None))
237 237 >>> _splitrange(5, 10) # [5:10]
238 238 ((None, None), (5, 11))
239 239 >>> _splitrange(-10, 10) # [-10:10]
240 240 ((0, 11), (0, 11))
241 241 >>> _splitrange(-10, 0) # [-10:0]
242 242 ((0, 11), (None, None))
243 243 >>> _splitrange(0, 10) # [0:10]
244 244 ((None, None), (0, 11))
245 245 >>> _splitrange(0, 0) # [0:0]
246 246 ((0, 1), (None, None))
247 247 >>> _splitrange(1, -1) # [1:-1]
248 248 ((None, None), (None, None))
249 249 """
250 250 ancdepths = (None, None)
251 251 descdepths = (None, None)
252 252 if a == b == 0:
253 253 ancdepths = (0, 1)
254 254 if a < 0:
255 255 ancdepths = (-min(b, 0), -a + 1)
256 256 if b > 0:
257 257 descdepths = (max(a, 0), b + 1)
258 258 return ancdepths, descdepths
259 259
260 260 def generationsrel(repo, subset, x, rel, z, order):
261 261 # TODO: rewrite tests, and drop startdepth argument from ancestors() and
262 262 # descendants() predicates
263 263 a, b = getintrange(z,
264 264 _('relation subscript must be an integer or a range'),
265 265 _('relation subscript bounds must be integers'),
266 266 deffirst=-(dagop.maxlogdepth - 1),
267 267 deflast=+(dagop.maxlogdepth - 1))
268 268 (ancstart, ancstop), (descstart, descstop) = _splitrange(a, b)
269 269
270 270 if ancstart is None and descstart is None:
271 271 return baseset()
272 272
273 273 revs = getset(repo, fullreposet(repo), x)
274 274 if not revs:
275 275 return baseset()
276 276
277 277 if ancstart is not None and descstart is not None:
278 278 s = dagop.revancestors(repo, revs, False, ancstart, ancstop)
279 279 s += dagop.revdescendants(repo, revs, False, descstart, descstop)
280 280 elif ancstart is not None:
281 281 s = dagop.revancestors(repo, revs, False, ancstart, ancstop)
282 282 elif descstart is not None:
283 283 s = dagop.revdescendants(repo, revs, False, descstart, descstop)
284 284
285 285 return subset & s
286 286
287 287 def relsubscriptset(repo, subset, x, y, z, order):
288 288 # this is pretty basic implementation of 'x#y[z]' operator, still
289 289 # experimental so undocumented. see the wiki for further ideas.
290 290 # https://www.mercurial-scm.org/wiki/RevsetOperatorPlan
291 291 rel = getsymbol(y)
292 292 if rel in subscriptrelations:
293 293 return subscriptrelations[rel](repo, subset, x, rel, z, order)
294 294
295 295 relnames = [r for r in subscriptrelations.keys() if len(r) > 1]
296 296 raise error.UnknownIdentifier(rel, relnames)
297 297
298 298 def subscriptset(repo, subset, x, y, order):
299 299 raise error.ParseError(_("can't use a subscript in this context"))
300 300
301 301 def listset(repo, subset, *xs, **opts):
302 302 raise error.ParseError(_("can't use a list in this context"),
303 303 hint=_('see \'hg help "revsets.x or y"\''))
304 304
305 305 def keyvaluepair(repo, subset, k, v, order):
306 306 raise error.ParseError(_("can't use a key-value pair in this context"))
307 307
308 308 def func(repo, subset, a, b, order):
309 309 f = getsymbol(a)
310 310 if f in symbols:
311 311 func = symbols[f]
312 312 if getattr(func, '_takeorder', False):
313 313 return func(repo, subset, b, order)
314 314 return func(repo, subset, b)
315 315
316 316 keep = lambda fn: getattr(fn, '__doc__', None) is not None
317 317
318 318 syms = [s for (s, fn) in symbols.items() if keep(fn)]
319 319 raise error.UnknownIdentifier(f, syms)
320 320
321 321 # functions
322 322
323 323 # symbols are callables like:
324 324 # fn(repo, subset, x)
325 325 # with:
326 326 # repo - current repository instance
327 327 # subset - of revisions to be examined
328 328 # x - argument in tree form
329 329 symbols = revsetlang.symbols
330 330
331 331 # symbols which can't be used for a DoS attack for any given input
332 332 # (e.g. those which accept regexes as plain strings shouldn't be included)
333 333 # functions that just return a lot of changesets (like all) don't count here
334 334 safesymbols = set()
335 335
336 336 predicate = registrar.revsetpredicate()
337 337
338 338 @predicate('_destupdate')
339 339 def _destupdate(repo, subset, x):
340 340 # experimental revset for update destination
341 341 args = getargsdict(x, 'limit', 'clean')
342 342 return subset & baseset([destutil.destupdate(repo,
343 343 **pycompat.strkwargs(args))[0]])
344 344
345 345 @predicate('_destmerge')
346 346 def _destmerge(repo, subset, x):
347 347 # experimental revset for merge destination
348 348 sourceset = None
349 349 if x is not None:
350 350 sourceset = getset(repo, fullreposet(repo), x)
351 351 return subset & baseset([destutil.destmerge(repo, sourceset=sourceset)])
352 352
353 353 @predicate('adds(pattern)', safe=True, weight=30)
354 354 def adds(repo, subset, x):
355 355 """Changesets that add a file matching pattern.
356 356
357 357 The pattern without explicit kind like ``glob:`` is expected to be
358 358 relative to the current directory and match against a file or a
359 359 directory.
360 360 """
361 361 # i18n: "adds" is a keyword
362 362 pat = getstring(x, _("adds requires a pattern"))
363 363 return checkstatus(repo, subset, pat, 1)
364 364
365 365 @predicate('ancestor(*changeset)', safe=True, weight=0.5)
366 366 def ancestor(repo, subset, x):
367 367 """A greatest common ancestor of the changesets.
368 368
369 369 Accepts 0 or more changesets.
370 370 Will return empty list when passed no args.
371 371 Greatest common ancestor of a single changeset is that changeset.
372 372 """
373 373 reviter = iter(orset(repo, fullreposet(repo), x, order=anyorder))
374 374 try:
375 375 anc = repo[next(reviter)]
376 376 except StopIteration:
377 377 return baseset()
378 378 for r in reviter:
379 379 anc = anc.ancestor(repo[r])
380 380
381 381 r = scmutil.intrev(anc)
382 382 if r in subset:
383 383 return baseset([r])
384 384 return baseset()
385 385
386 386 def _ancestors(repo, subset, x, followfirst=False, startdepth=None,
387 387 stopdepth=None):
388 388 heads = getset(repo, fullreposet(repo), x)
389 389 if not heads:
390 390 return baseset()
391 391 s = dagop.revancestors(repo, heads, followfirst, startdepth, stopdepth)
392 392 return subset & s
393 393
394 394 @predicate('ancestors(set[, depth])', safe=True)
395 395 def ancestors(repo, subset, x):
396 396 """Changesets that are ancestors of changesets in set, including the
397 397 given changesets themselves.
398 398
399 399 If depth is specified, the result only includes changesets up to
400 400 the specified generation.
401 401 """
402 402 # startdepth is for internal use only until we can decide the UI
403 403 args = getargsdict(x, 'ancestors', 'set depth startdepth')
404 404 if 'set' not in args:
405 405 # i18n: "ancestors" is a keyword
406 406 raise error.ParseError(_('ancestors takes at least 1 argument'))
407 407 startdepth = stopdepth = None
408 408 if 'startdepth' in args:
409 409 n = getinteger(args['startdepth'],
410 410 "ancestors expects an integer startdepth")
411 411 if n < 0:
412 412 raise error.ParseError("negative startdepth")
413 413 startdepth = n
414 414 if 'depth' in args:
415 415 # i18n: "ancestors" is a keyword
416 416 n = getinteger(args['depth'], _("ancestors expects an integer depth"))
417 417 if n < 0:
418 418 raise error.ParseError(_("negative depth"))
419 419 stopdepth = n + 1
420 420 return _ancestors(repo, subset, args['set'],
421 421 startdepth=startdepth, stopdepth=stopdepth)
422 422
423 423 @predicate('_firstancestors', safe=True)
424 424 def _firstancestors(repo, subset, x):
425 425 # ``_firstancestors(set)``
426 426 # Like ``ancestors(set)`` but follows only the first parents.
427 427 return _ancestors(repo, subset, x, followfirst=True)
428 428
429 429 def _childrenspec(repo, subset, x, n, order):
430 430 """Changesets that are the Nth child of a changeset
431 431 in set.
432 432 """
433 433 cs = set()
434 434 for r in getset(repo, fullreposet(repo), x):
435 435 for i in range(n):
436 436 c = repo[r].children()
437 437 if len(c) == 0:
438 438 break
439 439 if len(c) > 1:
440 440 raise error.RepoLookupError(
441 441 _("revision in set has more than one child"))
442 442 r = c[0].rev()
443 443 else:
444 444 cs.add(r)
445 445 return subset & cs
446 446
447 447 def ancestorspec(repo, subset, x, n, order):
448 448 """``set~n``
449 449 Changesets that are the Nth ancestor (first parents only) of a changeset
450 450 in set.
451 451 """
452 452 n = getinteger(n, _("~ expects a number"))
453 453 if n < 0:
454 454 # children lookup
455 455 return _childrenspec(repo, subset, x, -n, order)
456 456 ps = set()
457 457 cl = repo.changelog
458 458 for r in getset(repo, fullreposet(repo), x):
459 459 for i in range(n):
460 460 try:
461 461 r = cl.parentrevs(r)[0]
462 462 except error.WdirUnsupported:
463 463 r = repo[r].p1().rev()
464 464 ps.add(r)
465 465 return subset & ps
466 466
467 467 @predicate('author(string)', safe=True, weight=10)
468 468 def author(repo, subset, x):
469 469 """Alias for ``user(string)``.
470 470 """
471 471 # i18n: "author" is a keyword
472 472 n = getstring(x, _("author requires a string"))
473 473 kind, pattern, matcher = _substringmatcher(n, casesensitive=False)
474 474 return subset.filter(lambda x: matcher(repo[x].user()),
475 475 condrepr=('<user %r>', n))
476 476
477 477 @predicate('bisect(string)', safe=True)
478 478 def bisect(repo, subset, x):
479 479 """Changesets marked in the specified bisect status:
480 480
481 481 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
482 482 - ``goods``, ``bads`` : csets topologically good/bad
483 483 - ``range`` : csets taking part in the bisection
484 484 - ``pruned`` : csets that are goods, bads or skipped
485 485 - ``untested`` : csets whose fate is yet unknown
486 486 - ``ignored`` : csets ignored due to DAG topology
487 487 - ``current`` : the cset currently being bisected
488 488 """
489 489 # i18n: "bisect" is a keyword
490 490 status = getstring(x, _("bisect requires a string")).lower()
491 491 state = set(hbisect.get(repo, status))
492 492 return subset & state
493 493
494 494 # Backward-compatibility
495 495 # - no help entry so that we do not advertise it any more
496 496 @predicate('bisected', safe=True)
497 497 def bisected(repo, subset, x):
498 498 return bisect(repo, subset, x)
499 499
500 500 @predicate('bookmark([name])', safe=True)
501 501 def bookmark(repo, subset, x):
502 502 """The named bookmark or all bookmarks.
503 503
504 504 Pattern matching is supported for `name`. See :hg:`help revisions.patterns`.
505 505 """
506 506 # i18n: "bookmark" is a keyword
507 507 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
508 508 if args:
509 509 bm = getstring(args[0],
510 510 # i18n: "bookmark" is a keyword
511 511 _('the argument to bookmark must be a string'))
512 512 kind, pattern, matcher = stringutil.stringmatcher(bm)
513 513 bms = set()
514 514 if kind == 'literal':
515 515 if bm == pattern:
516 516 pattern = repo._bookmarks.expandname(pattern)
517 517 bmrev = repo._bookmarks.get(pattern, None)
518 518 if not bmrev:
519 519 raise error.RepoLookupError(_("bookmark '%s' does not exist")
520 520 % pattern)
521 521 bms.add(repo[bmrev].rev())
522 522 else:
523 523 matchrevs = set()
524 524 for name, bmrev in repo._bookmarks.iteritems():
525 525 if matcher(name):
526 526 matchrevs.add(bmrev)
527 527 for bmrev in matchrevs:
528 528 bms.add(repo[bmrev].rev())
529 529 else:
530 530 bms = {repo[r].rev() for r in repo._bookmarks.values()}
531 531 bms -= {node.nullrev}
532 532 return subset & bms
533 533
534 534 @predicate('branch(string or set)', safe=True, weight=10)
535 535 def branch(repo, subset, x):
536 536 """
537 537 All changesets belonging to the given branch or the branches of the given
538 538 changesets.
539 539
540 540 Pattern matching is supported for `string`. See
541 541 :hg:`help revisions.patterns`.
542 542 """
543 543 getbi = repo.revbranchcache().branchinfo
544 544 def getbranch(r):
545 545 try:
546 546 return getbi(r)[0]
547 547 except error.WdirUnsupported:
548 548 return repo[r].branch()
549 549
550 550 try:
551 551 b = getstring(x, '')
552 552 except error.ParseError:
553 553 # not a string, but another revspec, e.g. tip()
554 554 pass
555 555 else:
556 556 kind, pattern, matcher = stringutil.stringmatcher(b)
557 557 if kind == 'literal':
558 558 # note: falls through to the revspec case if no branch with
559 559 # this name exists and pattern kind is not specified explicitly
560 560 if repo.branchmap().hasbranch(pattern):
561 561 return subset.filter(lambda r: matcher(getbranch(r)),
562 562 condrepr=('<branch %r>', b))
563 563 if b.startswith('literal:'):
564 564 raise error.RepoLookupError(_("branch '%s' does not exist")
565 565 % pattern)
566 566 else:
567 567 return subset.filter(lambda r: matcher(getbranch(r)),
568 568 condrepr=('<branch %r>', b))
569 569
570 570 s = getset(repo, fullreposet(repo), x)
571 571 b = set()
572 572 for r in s:
573 573 b.add(getbranch(r))
574 574 c = s.__contains__
575 575 return subset.filter(lambda r: c(r) or getbranch(r) in b,
576 576 condrepr=lambda: '<branch %r>' % _sortedb(b))
577 577
578 578 @predicate('phasedivergent()', safe=True)
579 579 def phasedivergent(repo, subset, x):
580 580 """Mutable changesets marked as successors of public changesets.
581 581
582 582 Only non-public and non-obsolete changesets can be `phasedivergent`.
583 583 (EXPERIMENTAL)
584 584 """
585 585 # i18n: "phasedivergent" is a keyword
586 586 getargs(x, 0, 0, _("phasedivergent takes no arguments"))
587 587 phasedivergent = obsmod.getrevs(repo, 'phasedivergent')
588 588 return subset & phasedivergent
589 589
590 590 @predicate('bundle()', safe=True)
591 591 def bundle(repo, subset, x):
592 592 """Changesets in the bundle.
593 593
594 594 Bundle must be specified by the -R option."""
595 595
596 596 try:
597 597 bundlerevs = repo.changelog.bundlerevs
598 598 except AttributeError:
599 599 raise error.Abort(_("no bundle provided - specify with -R"))
600 600 return subset & bundlerevs
601 601
602 602 def checkstatus(repo, subset, pat, field):
603 603 """Helper for status-related revsets (adds, removes, modifies).
604 604 The field parameter says which kind is desired:
605 605 0: modified
606 606 1: added
607 607 2: removed
608 608 """
609 609 hasset = matchmod.patkind(pat) == 'set'
610 610
611 611 mcache = [None]
612 612 def matches(x):
613 613 c = repo[x]
614 614 if not mcache[0] or hasset:
615 615 mcache[0] = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
616 616 m = mcache[0]
617 617 fname = None
618 618 if not m.anypats() and len(m.files()) == 1:
619 619 fname = m.files()[0]
620 620 if fname is not None:
621 621 if fname not in c.files():
622 622 return False
623 623 else:
624 624 for f in c.files():
625 625 if m(f):
626 626 break
627 627 else:
628 628 return False
629 629 files = repo.status(c.p1().node(), c.node())[field]
630 630 if fname is not None:
631 631 if fname in files:
632 632 return True
633 633 else:
634 634 for f in files:
635 635 if m(f):
636 636 return True
637 637
638 638 return subset.filter(matches, condrepr=('<status[%r] %r>', field, pat))
639 639
640 640 def _children(repo, subset, parentset):
641 641 if not parentset:
642 642 return baseset()
643 643 cs = set()
644 644 pr = repo.changelog.parentrevs
645 645 minrev = parentset.min()
646 646 nullrev = node.nullrev
647 647 for r in subset:
648 648 if r <= minrev:
649 649 continue
650 650 p1, p2 = pr(r)
651 651 if p1 in parentset:
652 652 cs.add(r)
653 653 if p2 != nullrev and p2 in parentset:
654 654 cs.add(r)
655 655 return baseset(cs)
656 656
657 657 @predicate('children(set)', safe=True)
658 658 def children(repo, subset, x):
659 659 """Child changesets of changesets in set.
660 660 """
661 661 s = getset(repo, fullreposet(repo), x)
662 662 cs = _children(repo, subset, s)
663 663 return subset & cs
664 664
665 665 @predicate('closed()', safe=True, weight=10)
666 666 def closed(repo, subset, x):
667 667 """Changeset is closed.
668 668 """
669 669 # i18n: "closed" is a keyword
670 670 getargs(x, 0, 0, _("closed takes no arguments"))
671 671 return subset.filter(lambda r: repo[r].closesbranch(),
672 672 condrepr='<branch closed>')
673 673
674 674 # for internal use
675 675 @predicate('_commonancestorheads(set)', safe=True)
676 676 def _commonancestorheads(repo, subset, x):
677 677 # This is an internal method is for quickly calculating "heads(::x and
678 678 # ::y)"
679 679
680 680 # These greatest common ancestors are the same ones that the consensus bid
681 681 # merge will find.
682 682 startrevs = getset(repo, fullreposet(repo), x, order=anyorder)
683 683
684 684 ancs = repo.changelog._commonancestorsheads(*list(startrevs))
685 685 return subset & baseset(ancs)
686 686
687 687 @predicate('commonancestors(set)', safe=True)
688 688 def commonancestors(repo, subset, x):
689 689 """Changesets that are ancestors of every changeset in set.
690 690 """
691 691 startrevs = getset(repo, fullreposet(repo), x, order=anyorder)
692 692 if not startrevs:
693 693 return baseset()
694 694 for r in startrevs:
695 695 subset &= dagop.revancestors(repo, baseset([r]))
696 696 return subset
697 697
698 698 @predicate('contains(pattern)', weight=100)
699 699 def contains(repo, subset, x):
700 700 """The revision's manifest contains a file matching pattern (but might not
701 701 modify it). See :hg:`help patterns` for information about file patterns.
702 702
703 703 The pattern without explicit kind like ``glob:`` is expected to be
704 704 relative to the current directory and match against a file exactly
705 705 for efficiency.
706 706 """
707 707 # i18n: "contains" is a keyword
708 708 pat = getstring(x, _("contains requires a pattern"))
709 709
710 710 def matches(x):
711 711 if not matchmod.patkind(pat):
712 712 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
713 713 if pats in repo[x]:
714 714 return True
715 715 else:
716 716 c = repo[x]
717 717 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
718 718 for f in c.manifest():
719 719 if m(f):
720 720 return True
721 721 return False
722 722
723 723 return subset.filter(matches, condrepr=('<contains %r>', pat))
724 724
725 725 @predicate('converted([id])', safe=True)
726 726 def converted(repo, subset, x):
727 727 """Changesets converted from the given identifier in the old repository if
728 728 present, or all converted changesets if no identifier is specified.
729 729 """
730 730
731 731 # There is exactly no chance of resolving the revision, so do a simple
732 732 # string compare and hope for the best
733 733
734 734 rev = None
735 735 # i18n: "converted" is a keyword
736 736 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
737 737 if l:
738 738 # i18n: "converted" is a keyword
739 739 rev = getstring(l[0], _('converted requires a revision'))
740 740
741 741 def _matchvalue(r):
742 742 source = repo[r].extra().get('convert_revision', None)
743 743 return source is not None and (rev is None or source.startswith(rev))
744 744
745 745 return subset.filter(lambda r: _matchvalue(r),
746 746 condrepr=('<converted %r>', rev))
747 747
748 748 @predicate('date(interval)', safe=True, weight=10)
749 749 def date(repo, subset, x):
750 750 """Changesets within the interval, see :hg:`help dates`.
751 751 """
752 752 # i18n: "date" is a keyword
753 753 ds = getstring(x, _("date requires a string"))
754 754 dm = dateutil.matchdate(ds)
755 755 return subset.filter(lambda x: dm(repo[x].date()[0]),
756 756 condrepr=('<date %r>', ds))
757 757
758 758 @predicate('desc(string)', safe=True, weight=10)
759 759 def desc(repo, subset, x):
760 760 """Search commit message for string. The match is case-insensitive.
761 761
762 762 Pattern matching is supported for `string`. See
763 763 :hg:`help revisions.patterns`.
764 764 """
765 765 # i18n: "desc" is a keyword
766 766 ds = getstring(x, _("desc requires a string"))
767 767
768 768 kind, pattern, matcher = _substringmatcher(ds, casesensitive=False)
769 769
770 770 return subset.filter(lambda r: matcher(repo[r].description()),
771 771 condrepr=('<desc %r>', ds))
772 772
773 773 def _descendants(repo, subset, x, followfirst=False, startdepth=None,
774 774 stopdepth=None):
775 775 roots = getset(repo, fullreposet(repo), x)
776 776 if not roots:
777 777 return baseset()
778 778 s = dagop.revdescendants(repo, roots, followfirst, startdepth, stopdepth)
779 779 return subset & s
780 780
781 781 @predicate('descendants(set[, depth])', safe=True)
782 782 def descendants(repo, subset, x):
783 783 """Changesets which are descendants of changesets in set, including the
784 784 given changesets themselves.
785 785
786 786 If depth is specified, the result only includes changesets up to
787 787 the specified generation.
788 788 """
789 789 # startdepth is for internal use only until we can decide the UI
790 790 args = getargsdict(x, 'descendants', 'set depth startdepth')
791 791 if 'set' not in args:
792 792 # i18n: "descendants" is a keyword
793 793 raise error.ParseError(_('descendants takes at least 1 argument'))
794 794 startdepth = stopdepth = None
795 795 if 'startdepth' in args:
796 796 n = getinteger(args['startdepth'],
797 797 "descendants expects an integer startdepth")
798 798 if n < 0:
799 799 raise error.ParseError("negative startdepth")
800 800 startdepth = n
801 801 if 'depth' in args:
802 802 # i18n: "descendants" is a keyword
803 803 n = getinteger(args['depth'], _("descendants expects an integer depth"))
804 804 if n < 0:
805 805 raise error.ParseError(_("negative depth"))
806 806 stopdepth = n + 1
807 807 return _descendants(repo, subset, args['set'],
808 808 startdepth=startdepth, stopdepth=stopdepth)
809 809
810 810 @predicate('_firstdescendants', safe=True)
811 811 def _firstdescendants(repo, subset, x):
812 812 # ``_firstdescendants(set)``
813 813 # Like ``descendants(set)`` but follows only the first parents.
814 814 return _descendants(repo, subset, x, followfirst=True)
815 815
816 816 @predicate('destination([set])', safe=True, weight=10)
817 817 def destination(repo, subset, x):
818 818 """Changesets that were created by a graft, transplant or rebase operation,
819 819 with the given revisions specified as the source. Omitting the optional set
820 820 is the same as passing all().
821 821 """
822 822 if x is not None:
823 823 sources = getset(repo, fullreposet(repo), x)
824 824 else:
825 825 sources = fullreposet(repo)
826 826
827 827 dests = set()
828 828
829 829 # subset contains all of the possible destinations that can be returned, so
830 830 # iterate over them and see if their source(s) were provided in the arg set.
831 831 # Even if the immediate src of r is not in the arg set, src's source (or
832 832 # further back) may be. Scanning back further than the immediate src allows
833 833 # transitive transplants and rebases to yield the same results as transitive
834 834 # grafts.
835 835 for r in subset:
836 836 src = _getrevsource(repo, r)
837 837 lineage = None
838 838
839 839 while src is not None:
840 840 if lineage is None:
841 841 lineage = list()
842 842
843 843 lineage.append(r)
844 844
845 845 # The visited lineage is a match if the current source is in the arg
846 846 # set. Since every candidate dest is visited by way of iterating
847 847 # subset, any dests further back in the lineage will be tested by a
848 848 # different iteration over subset. Likewise, if the src was already
849 849 # selected, the current lineage can be selected without going back
850 850 # further.
851 851 if src in sources or src in dests:
852 852 dests.update(lineage)
853 853 break
854 854
855 855 r = src
856 856 src = _getrevsource(repo, r)
857 857
858 858 return subset.filter(dests.__contains__,
859 859 condrepr=lambda: '<destination %r>' % _sortedb(dests))
860 860
861 861 @predicate('contentdivergent()', safe=True)
862 862 def contentdivergent(repo, subset, x):
863 863 """
864 864 Final successors of changesets with an alternative set of final
865 865 successors. (EXPERIMENTAL)
866 866 """
867 867 # i18n: "contentdivergent" is a keyword
868 868 getargs(x, 0, 0, _("contentdivergent takes no arguments"))
869 869 contentdivergent = obsmod.getrevs(repo, 'contentdivergent')
870 870 return subset & contentdivergent
871 871
872 872 @predicate('expectsize(set[, size])', safe=True, takeorder=True)
873 873 def expectsize(repo, subset, x, order):
874 874 """Return the given revset if size matches the revset size.
875 875 Abort if the revset doesn't expect given size.
876 876 size can either be an integer range or an integer.
877 877
878 878 For example, ``expectsize(0:1, 3:5)`` will abort as revset size is 2 and
879 879 2 is not between 3 and 5 inclusive."""
880 880
881 881 args = getargsdict(x, 'expectsize', 'set size')
882 882 minsize = 0
883 883 maxsize = len(repo) + 1
884 884 err = ''
885 885 if 'size' not in args or 'set' not in args:
886 886 raise error.ParseError(_('invalid set of arguments'))
887 887 minsize, maxsize = getintrange(args['size'],
888 888 _('expectsize requires a size range'
889 889 ' or a positive integer'),
890 890 _('size range bounds must be integers'),
891 891 minsize, maxsize)
892 892 if minsize < 0 or maxsize < 0:
893 893 raise error.ParseError(_('negative size'))
894 894 rev = getset(repo, fullreposet(repo), args['set'], order=order)
895 895 if minsize != maxsize and (len(rev) < minsize or len(rev) > maxsize):
896 896 err = _('revset size mismatch.'
897 897 ' expected between %d and %d, got %d') % (minsize, maxsize,
898 898 len(rev))
899 899 elif minsize == maxsize and len(rev) != minsize:
900 900 err = _('revset size mismatch.'
901 901 ' expected %d, got %d') % (minsize, len(rev))
902 902 if err:
903 903 raise error.RepoLookupError(err)
904 904 if order == followorder:
905 905 return subset & rev
906 906 else:
907 907 return rev & subset
908 908
909 909 @predicate('extdata(source)', safe=False, weight=100)
910 910 def extdata(repo, subset, x):
911 911 """Changesets in the specified extdata source. (EXPERIMENTAL)"""
912 912 # i18n: "extdata" is a keyword
913 913 args = getargsdict(x, 'extdata', 'source')
914 914 source = getstring(args.get('source'),
915 915 # i18n: "extdata" is a keyword
916 916 _('extdata takes at least 1 string argument'))
917 917 data = scmutil.extdatasource(repo, source)
918 918 return subset & baseset(data)
919 919
920 920 @predicate('extinct()', safe=True)
921 921 def extinct(repo, subset, x):
922 922 """Obsolete changesets with obsolete descendants only.
923 923 """
924 924 # i18n: "extinct" is a keyword
925 925 getargs(x, 0, 0, _("extinct takes no arguments"))
926 926 extincts = obsmod.getrevs(repo, 'extinct')
927 927 return subset & extincts
928 928
929 929 @predicate('extra(label, [value])', safe=True)
930 930 def extra(repo, subset, x):
931 931 """Changesets with the given label in the extra metadata, with the given
932 932 optional value.
933 933
934 934 Pattern matching is supported for `value`. See
935 935 :hg:`help revisions.patterns`.
936 936 """
937 937 args = getargsdict(x, 'extra', 'label value')
938 938 if 'label' not in args:
939 939 # i18n: "extra" is a keyword
940 940 raise error.ParseError(_('extra takes at least 1 argument'))
941 941 # i18n: "extra" is a keyword
942 942 label = getstring(args['label'], _('first argument to extra must be '
943 943 'a string'))
944 944 value = None
945 945
946 946 if 'value' in args:
947 947 # i18n: "extra" is a keyword
948 948 value = getstring(args['value'], _('second argument to extra must be '
949 949 'a string'))
950 950 kind, value, matcher = stringutil.stringmatcher(value)
951 951
952 952 def _matchvalue(r):
953 953 extra = repo[r].extra()
954 954 return label in extra and (value is None or matcher(extra[label]))
955 955
956 956 return subset.filter(lambda r: _matchvalue(r),
957 957 condrepr=('<extra[%r] %r>', label, value))
958 958
959 959 @predicate('filelog(pattern)', safe=True)
960 960 def filelog(repo, subset, x):
961 961 """Changesets connected to the specified filelog.
962 962
963 963 For performance reasons, visits only revisions mentioned in the file-level
964 964 filelog, rather than filtering through all changesets (much faster, but
965 965 doesn't include deletes or duplicate changes). For a slower, more accurate
966 966 result, use ``file()``.
967 967
968 968 The pattern without explicit kind like ``glob:`` is expected to be
969 969 relative to the current directory and match against a file exactly
970 970 for efficiency.
971 971 """
972 972
973 973 # i18n: "filelog" is a keyword
974 974 pat = getstring(x, _("filelog requires a pattern"))
975 975 s = set()
976 976 cl = repo.changelog
977 977
978 978 if not matchmod.patkind(pat):
979 979 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
980 980 files = [f]
981 981 else:
982 982 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
983 983 files = (f for f in repo[None] if m(f))
984 984
985 985 for f in files:
986 986 fl = repo.file(f)
987 987 known = {}
988 988 scanpos = 0
989 989 for fr in list(fl):
990 990 fn = fl.node(fr)
991 991 if fn in known:
992 992 s.add(known[fn])
993 993 continue
994 994
995 995 lr = fl.linkrev(fr)
996 996 if lr in cl:
997 997 s.add(lr)
998 998 elif scanpos is not None:
999 999 # lowest matching changeset is filtered, scan further
1000 1000 # ahead in changelog
1001 1001 start = max(lr, scanpos) + 1
1002 1002 scanpos = None
1003 1003 for r in cl.revs(start):
1004 1004 # minimize parsing of non-matching entries
1005 1005 if f in cl.revision(r) and f in cl.readfiles(r):
1006 1006 try:
1007 1007 # try to use manifest delta fastpath
1008 1008 n = repo[r].filenode(f)
1009 1009 if n not in known:
1010 1010 if n == fn:
1011 1011 s.add(r)
1012 1012 scanpos = r
1013 1013 break
1014 1014 else:
1015 1015 known[n] = r
1016 1016 except error.ManifestLookupError:
1017 1017 # deletion in changelog
1018 1018 continue
1019 1019
1020 1020 return subset & s
1021 1021
1022 1022 @predicate('first(set, [n])', safe=True, takeorder=True, weight=0)
1023 1023 def first(repo, subset, x, order):
1024 1024 """An alias for limit().
1025 1025 """
1026 1026 return limit(repo, subset, x, order)
1027 1027
1028 1028 def _follow(repo, subset, x, name, followfirst=False):
1029 1029 args = getargsdict(x, name, 'file startrev')
1030 1030 revs = None
1031 1031 if 'startrev' in args:
1032 1032 revs = getset(repo, fullreposet(repo), args['startrev'])
1033 1033 if 'file' in args:
1034 1034 x = getstring(args['file'], _("%s expected a pattern") % name)
1035 1035 if revs is None:
1036 1036 revs = [None]
1037 1037 fctxs = []
1038 1038 for r in revs:
1039 1039 ctx = mctx = repo[r]
1040 1040 if r is None:
1041 1041 ctx = repo['.']
1042 1042 m = matchmod.match(repo.root, repo.getcwd(), [x],
1043 1043 ctx=mctx, default='path')
1044 1044 fctxs.extend(ctx[f].introfilectx() for f in ctx.manifest().walk(m))
1045 1045 s = dagop.filerevancestors(fctxs, followfirst)
1046 1046 else:
1047 1047 if revs is None:
1048 1048 revs = baseset([repo['.'].rev()])
1049 1049 s = dagop.revancestors(repo, revs, followfirst)
1050 1050
1051 1051 return subset & s
1052 1052
1053 1053 @predicate('follow([file[, startrev]])', safe=True)
1054 1054 def follow(repo, subset, x):
1055 1055 """
1056 1056 An alias for ``::.`` (ancestors of the working directory's first parent).
1057 1057 If file pattern is specified, the histories of files matching given
1058 1058 pattern in the revision given by startrev are followed, including copies.
1059 1059 """
1060 1060 return _follow(repo, subset, x, 'follow')
1061 1061
1062 1062 @predicate('_followfirst', safe=True)
1063 1063 def _followfirst(repo, subset, x):
1064 1064 # ``followfirst([file[, startrev]])``
1065 1065 # Like ``follow([file[, startrev]])`` but follows only the first parent
1066 1066 # of every revisions or files revisions.
1067 1067 return _follow(repo, subset, x, '_followfirst', followfirst=True)
1068 1068
1069 1069 @predicate('followlines(file, fromline:toline[, startrev=., descend=False])',
1070 1070 safe=True)
1071 1071 def followlines(repo, subset, x):
1072 1072 """Changesets modifying `file` in line range ('fromline', 'toline').
1073 1073
1074 1074 Line range corresponds to 'file' content at 'startrev' and should hence be
1075 1075 consistent with file size. If startrev is not specified, working directory's
1076 1076 parent is used.
1077 1077
1078 1078 By default, ancestors of 'startrev' are returned. If 'descend' is True,
1079 1079 descendants of 'startrev' are returned though renames are (currently) not
1080 1080 followed in this direction.
1081 1081 """
1082 1082 args = getargsdict(x, 'followlines', 'file *lines startrev descend')
1083 1083 if len(args['lines']) != 1:
1084 1084 raise error.ParseError(_("followlines requires a line range"))
1085 1085
1086 1086 rev = '.'
1087 1087 if 'startrev' in args:
1088 1088 revs = getset(repo, fullreposet(repo), args['startrev'])
1089 1089 if len(revs) != 1:
1090 1090 raise error.ParseError(
1091 1091 # i18n: "followlines" is a keyword
1092 1092 _("followlines expects exactly one revision"))
1093 1093 rev = revs.last()
1094 1094
1095 1095 pat = getstring(args['file'], _("followlines requires a pattern"))
1096 1096 # i18n: "followlines" is a keyword
1097 1097 msg = _("followlines expects exactly one file")
1098 1098 fname = scmutil.parsefollowlinespattern(repo, rev, pat, msg)
1099 1099 fromline, toline = util.processlinerange(
1100 1100 *getintrange(args['lines'][0],
1101 1101 # i18n: "followlines" is a keyword
1102 1102 _("followlines expects a line number or a range"),
1103 1103 _("line range bounds must be integers")))
1104 1104
1105 1105 fctx = repo[rev].filectx(fname)
1106 1106 descend = False
1107 1107 if 'descend' in args:
1108 1108 descend = getboolean(args['descend'],
1109 1109 # i18n: "descend" is a keyword
1110 1110 _("descend argument must be a boolean"))
1111 1111 if descend:
1112 1112 rs = generatorset(
1113 1113 (c.rev() for c, _linerange
1114 1114 in dagop.blockdescendants(fctx, fromline, toline)),
1115 1115 iterasc=True)
1116 1116 else:
1117 1117 rs = generatorset(
1118 1118 (c.rev() for c, _linerange
1119 1119 in dagop.blockancestors(fctx, fromline, toline)),
1120 1120 iterasc=False)
1121 1121 return subset & rs
1122 1122
1123 1123 @predicate('all()', safe=True)
1124 1124 def getall(repo, subset, x):
1125 1125 """All changesets, the same as ``0:tip``.
1126 1126 """
1127 1127 # i18n: "all" is a keyword
1128 1128 getargs(x, 0, 0, _("all takes no arguments"))
1129 1129 return subset & spanset(repo) # drop "null" if any
1130 1130
1131 1131 @predicate('grep(regex)', weight=10)
1132 1132 def grep(repo, subset, x):
1133 1133 """Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
1134 1134 to ensure special escape characters are handled correctly. Unlike
1135 1135 ``keyword(string)``, the match is case-sensitive.
1136 1136 """
1137 1137 try:
1138 1138 # i18n: "grep" is a keyword
1139 1139 gr = re.compile(getstring(x, _("grep requires a string")))
1140 1140 except re.error as e:
1141 1141 raise error.ParseError(
1142 1142 _('invalid match pattern: %s') % stringutil.forcebytestr(e))
1143 1143
1144 1144 def matches(x):
1145 1145 c = repo[x]
1146 1146 for e in c.files() + [c.user(), c.description()]:
1147 1147 if gr.search(e):
1148 1148 return True
1149 1149 return False
1150 1150
1151 1151 return subset.filter(matches, condrepr=('<grep %r>', gr.pattern))
1152 1152
1153 1153 @predicate('_matchfiles', safe=True)
1154 1154 def _matchfiles(repo, subset, x):
1155 1155 # _matchfiles takes a revset list of prefixed arguments:
1156 1156 #
1157 1157 # [p:foo, i:bar, x:baz]
1158 1158 #
1159 1159 # builds a match object from them and filters subset. Allowed
1160 1160 # prefixes are 'p:' for regular patterns, 'i:' for include
1161 1161 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
1162 1162 # a revision identifier, or the empty string to reference the
1163 1163 # working directory, from which the match object is
1164 1164 # initialized. Use 'd:' to set the default matching mode, default
1165 1165 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
1166 1166
1167 1167 l = getargs(x, 1, -1, "_matchfiles requires at least one argument")
1168 1168 pats, inc, exc = [], [], []
1169 1169 rev, default = None, None
1170 1170 for arg in l:
1171 1171 s = getstring(arg, "_matchfiles requires string arguments")
1172 1172 prefix, value = s[:2], s[2:]
1173 1173 if prefix == 'p:':
1174 1174 pats.append(value)
1175 1175 elif prefix == 'i:':
1176 1176 inc.append(value)
1177 1177 elif prefix == 'x:':
1178 1178 exc.append(value)
1179 1179 elif prefix == 'r:':
1180 1180 if rev is not None:
1181 1181 raise error.ParseError('_matchfiles expected at most one '
1182 1182 'revision')
1183 1183 if value == '': # empty means working directory
1184 1184 rev = node.wdirrev
1185 1185 else:
1186 1186 rev = value
1187 1187 elif prefix == 'd:':
1188 1188 if default is not None:
1189 1189 raise error.ParseError('_matchfiles expected at most one '
1190 1190 'default mode')
1191 1191 default = value
1192 1192 else:
1193 1193 raise error.ParseError('invalid _matchfiles prefix: %s' % prefix)
1194 1194 if not default:
1195 1195 default = 'glob'
1196 1196 hasset = any(matchmod.patkind(p) == 'set' for p in pats + inc + exc)
1197 1197
1198 1198 mcache = [None]
1199 1199
1200 1200 # This directly read the changelog data as creating changectx for all
1201 1201 # revisions is quite expensive.
1202 1202 getfiles = repo.changelog.readfiles
1203 1203 wdirrev = node.wdirrev
1204 1204 def matches(x):
1205 1205 if x == wdirrev:
1206 1206 files = repo[x].files()
1207 1207 else:
1208 1208 files = getfiles(x)
1209 1209
1210 1210 if not mcache[0] or (hasset and rev is None):
1211 1211 r = x if rev is None else rev
1212 1212 mcache[0] = matchmod.match(repo.root, repo.getcwd(), pats,
1213 1213 include=inc, exclude=exc, ctx=repo[r],
1214 1214 default=default)
1215 1215 m = mcache[0]
1216 1216
1217 1217 for f in files:
1218 1218 if m(f):
1219 1219 return True
1220 1220 return False
1221 1221
1222 1222 return subset.filter(matches,
1223 1223 condrepr=('<matchfiles patterns=%r, include=%r '
1224 1224 'exclude=%r, default=%r, rev=%r>',
1225 1225 pats, inc, exc, default, rev))
1226 1226
1227 1227 @predicate('file(pattern)', safe=True, weight=10)
1228 1228 def hasfile(repo, subset, x):
1229 1229 """Changesets affecting files matched by pattern.
1230 1230
1231 1231 For a faster but less accurate result, consider using ``filelog()``
1232 1232 instead.
1233 1233
1234 1234 This predicate uses ``glob:`` as the default kind of pattern.
1235 1235 """
1236 1236 # i18n: "file" is a keyword
1237 1237 pat = getstring(x, _("file requires a pattern"))
1238 1238 return _matchfiles(repo, subset, ('string', 'p:' + pat))
1239 1239
1240 1240 @predicate('head()', safe=True)
1241 1241 def head(repo, subset, x):
1242 1242 """Changeset is a named branch head.
1243 1243 """
1244 1244 # i18n: "head" is a keyword
1245 1245 getargs(x, 0, 0, _("head takes no arguments"))
1246 1246 hs = set()
1247 1247 cl = repo.changelog
1248 1248 for ls in repo.branchmap().iterheads():
1249 1249 hs.update(cl.rev(h) for h in ls)
1250 1250 return subset & baseset(hs)
1251 1251
1252 1252 @predicate('heads(set)', safe=True, takeorder=True)
1253 1253 def heads(repo, subset, x, order):
1254 1254 """Members of set with no children in set.
1255 1255 """
1256 1256 # argument set should never define order
1257 1257 if order == defineorder:
1258 1258 order = followorder
1259 1259 inputset = getset(repo, fullreposet(repo), x, order=order)
1260 1260 wdirparents = None
1261 1261 if node.wdirrev in inputset:
1262 1262 # a bit slower, but not common so good enough for now
1263 1263 wdirparents = [p.rev() for p in repo[None].parents()]
1264 1264 inputset = set(inputset)
1265 1265 inputset.discard(node.wdirrev)
1266 1266 heads = repo.changelog.headrevs(inputset)
1267 1267 if wdirparents is not None:
1268 1268 heads.difference_update(wdirparents)
1269 1269 heads.add(node.wdirrev)
1270 1270 heads = baseset(heads)
1271 1271 return subset & heads
1272 1272
1273 1273 @predicate('hidden()', safe=True)
1274 1274 def hidden(repo, subset, x):
1275 1275 """Hidden changesets.
1276 1276 """
1277 1277 # i18n: "hidden" is a keyword
1278 1278 getargs(x, 0, 0, _("hidden takes no arguments"))
1279 1279 hiddenrevs = repoview.filterrevs(repo, 'visible')
1280 1280 return subset & hiddenrevs
1281 1281
1282 1282 @predicate('keyword(string)', safe=True, weight=10)
1283 1283 def keyword(repo, subset, x):
1284 1284 """Search commit message, user name, and names of changed files for
1285 1285 string. The match is case-insensitive.
1286 1286
1287 1287 For a regular expression or case sensitive search of these fields, use
1288 1288 ``grep(regex)``.
1289 1289 """
1290 1290 # i18n: "keyword" is a keyword
1291 1291 kw = encoding.lower(getstring(x, _("keyword requires a string")))
1292 1292
1293 1293 def matches(r):
1294 1294 c = repo[r]
1295 1295 return any(kw in encoding.lower(t)
1296 1296 for t in c.files() + [c.user(), c.description()])
1297 1297
1298 1298 return subset.filter(matches, condrepr=('<keyword %r>', kw))
1299 1299
1300 1300 @predicate('limit(set[, n[, offset]])', safe=True, takeorder=True, weight=0)
1301 1301 def limit(repo, subset, x, order):
1302 1302 """First n members of set, defaulting to 1, starting from offset.
1303 1303 """
1304 1304 args = getargsdict(x, 'limit', 'set n offset')
1305 1305 if 'set' not in args:
1306 1306 # i18n: "limit" is a keyword
1307 1307 raise error.ParseError(_("limit requires one to three arguments"))
1308 1308 # i18n: "limit" is a keyword
1309 1309 lim = getinteger(args.get('n'), _("limit expects a number"), default=1)
1310 1310 if lim < 0:
1311 1311 raise error.ParseError(_("negative number to select"))
1312 1312 # i18n: "limit" is a keyword
1313 1313 ofs = getinteger(args.get('offset'), _("limit expects a number"), default=0)
1314 1314 if ofs < 0:
1315 1315 raise error.ParseError(_("negative offset"))
1316 1316 os = getset(repo, fullreposet(repo), args['set'])
1317 1317 ls = os.slice(ofs, ofs + lim)
1318 1318 if order == followorder and lim > 1:
1319 1319 return subset & ls
1320 1320 return ls & subset
1321 1321
1322 1322 @predicate('last(set, [n])', safe=True, takeorder=True)
1323 1323 def last(repo, subset, x, order):
1324 1324 """Last n members of set, defaulting to 1.
1325 1325 """
1326 1326 # i18n: "last" is a keyword
1327 1327 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1328 1328 lim = 1
1329 1329 if len(l) == 2:
1330 1330 # i18n: "last" is a keyword
1331 1331 lim = getinteger(l[1], _("last expects a number"))
1332 1332 if lim < 0:
1333 1333 raise error.ParseError(_("negative number to select"))
1334 1334 os = getset(repo, fullreposet(repo), l[0])
1335 1335 os.reverse()
1336 1336 ls = os.slice(0, lim)
1337 1337 if order == followorder and lim > 1:
1338 1338 return subset & ls
1339 1339 ls.reverse()
1340 1340 return ls & subset
1341 1341
1342 1342 @predicate('max(set)', safe=True)
1343 1343 def maxrev(repo, subset, x):
1344 1344 """Changeset with highest revision number in set.
1345 1345 """
1346 1346 os = getset(repo, fullreposet(repo), x)
1347 1347 try:
1348 1348 m = os.max()
1349 1349 if m in subset:
1350 1350 return baseset([m], datarepr=('<max %r, %r>', subset, os))
1351 1351 except ValueError:
1352 1352 # os.max() throws a ValueError when the collection is empty.
1353 1353 # Same as python's max().
1354 1354 pass
1355 1355 return baseset(datarepr=('<max %r, %r>', subset, os))
1356 1356
1357 1357 @predicate('merge()', safe=True)
1358 1358 def merge(repo, subset, x):
1359 1359 """Changeset is a merge changeset.
1360 1360 """
1361 1361 # i18n: "merge" is a keyword
1362 1362 getargs(x, 0, 0, _("merge takes no arguments"))
1363 1363 cl = repo.changelog
1364 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1,
1364 nullrev = node.nullrev
1365 return subset.filter(lambda r: cl.parentrevs(r)[1] != nullrev,
1365 1366 condrepr='<merge>')
1366 1367
1367 1368 @predicate('branchpoint()', safe=True)
1368 1369 def branchpoint(repo, subset, x):
1369 1370 """Changesets with more than one child.
1370 1371 """
1371 1372 # i18n: "branchpoint" is a keyword
1372 1373 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1373 1374 cl = repo.changelog
1374 1375 if not subset:
1375 1376 return baseset()
1376 1377 # XXX this should be 'parentset.min()' assuming 'parentset' is a smartset
1377 1378 # (and if it is not, it should.)
1378 1379 baserev = min(subset)
1379 1380 parentscount = [0]*(len(repo) - baserev)
1380 1381 for r in cl.revs(start=baserev + 1):
1381 1382 for p in cl.parentrevs(r):
1382 1383 if p >= baserev:
1383 1384 parentscount[p - baserev] += 1
1384 1385 return subset.filter(lambda r: parentscount[r - baserev] > 1,
1385 1386 condrepr='<branchpoint>')
1386 1387
1387 1388 @predicate('min(set)', safe=True)
1388 1389 def minrev(repo, subset, x):
1389 1390 """Changeset with lowest revision number in set.
1390 1391 """
1391 1392 os = getset(repo, fullreposet(repo), x)
1392 1393 try:
1393 1394 m = os.min()
1394 1395 if m in subset:
1395 1396 return baseset([m], datarepr=('<min %r, %r>', subset, os))
1396 1397 except ValueError:
1397 1398 # os.min() throws a ValueError when the collection is empty.
1398 1399 # Same as python's min().
1399 1400 pass
1400 1401 return baseset(datarepr=('<min %r, %r>', subset, os))
1401 1402
1402 1403 @predicate('modifies(pattern)', safe=True, weight=30)
1403 1404 def modifies(repo, subset, x):
1404 1405 """Changesets modifying files matched by pattern.
1405 1406
1406 1407 The pattern without explicit kind like ``glob:`` is expected to be
1407 1408 relative to the current directory and match against a file or a
1408 1409 directory.
1409 1410 """
1410 1411 # i18n: "modifies" is a keyword
1411 1412 pat = getstring(x, _("modifies requires a pattern"))
1412 1413 return checkstatus(repo, subset, pat, 0)
1413 1414
1414 1415 @predicate('named(namespace)')
1415 1416 def named(repo, subset, x):
1416 1417 """The changesets in a given namespace.
1417 1418
1418 1419 Pattern matching is supported for `namespace`. See
1419 1420 :hg:`help revisions.patterns`.
1420 1421 """
1421 1422 # i18n: "named" is a keyword
1422 1423 args = getargs(x, 1, 1, _('named requires a namespace argument'))
1423 1424
1424 1425 ns = getstring(args[0],
1425 1426 # i18n: "named" is a keyword
1426 1427 _('the argument to named must be a string'))
1427 1428 kind, pattern, matcher = stringutil.stringmatcher(ns)
1428 1429 namespaces = set()
1429 1430 if kind == 'literal':
1430 1431 if pattern not in repo.names:
1431 1432 raise error.RepoLookupError(_("namespace '%s' does not exist")
1432 1433 % ns)
1433 1434 namespaces.add(repo.names[pattern])
1434 1435 else:
1435 1436 for name, ns in repo.names.iteritems():
1436 1437 if matcher(name):
1437 1438 namespaces.add(ns)
1438 1439
1439 1440 names = set()
1440 1441 for ns in namespaces:
1441 1442 for name in ns.listnames(repo):
1442 1443 if name not in ns.deprecated:
1443 1444 names.update(repo[n].rev() for n in ns.nodes(repo, name))
1444 1445
1445 1446 names -= {node.nullrev}
1446 1447 return subset & names
1447 1448
1448 1449 @predicate('id(string)', safe=True)
1449 1450 def node_(repo, subset, x):
1450 1451 """Revision non-ambiguously specified by the given hex string prefix.
1451 1452 """
1452 1453 # i18n: "id" is a keyword
1453 1454 l = getargs(x, 1, 1, _("id requires one argument"))
1454 1455 # i18n: "id" is a keyword
1455 1456 n = getstring(l[0], _("id requires a string"))
1456 1457 if len(n) == 40:
1457 1458 try:
1458 1459 rn = repo.changelog.rev(node.bin(n))
1459 1460 except error.WdirUnsupported:
1460 1461 rn = node.wdirrev
1461 1462 except (LookupError, TypeError):
1462 1463 rn = None
1463 1464 else:
1464 1465 rn = None
1465 1466 try:
1466 1467 pm = scmutil.resolvehexnodeidprefix(repo, n)
1467 1468 if pm is not None:
1468 1469 rn = repo.changelog.rev(pm)
1469 1470 except LookupError:
1470 1471 pass
1471 1472 except error.WdirUnsupported:
1472 1473 rn = node.wdirrev
1473 1474
1474 1475 if rn is None:
1475 1476 return baseset()
1476 1477 result = baseset([rn])
1477 1478 return result & subset
1478 1479
1479 1480 @predicate('none()', safe=True)
1480 1481 def none(repo, subset, x):
1481 1482 """No changesets.
1482 1483 """
1483 1484 # i18n: "none" is a keyword
1484 1485 getargs(x, 0, 0, _("none takes no arguments"))
1485 1486 return baseset()
1486 1487
1487 1488 @predicate('obsolete()', safe=True)
1488 1489 def obsolete(repo, subset, x):
1489 1490 """Mutable changeset with a newer version."""
1490 1491 # i18n: "obsolete" is a keyword
1491 1492 getargs(x, 0, 0, _("obsolete takes no arguments"))
1492 1493 obsoletes = obsmod.getrevs(repo, 'obsolete')
1493 1494 return subset & obsoletes
1494 1495
1495 1496 @predicate('only(set, [set])', safe=True)
1496 1497 def only(repo, subset, x):
1497 1498 """Changesets that are ancestors of the first set that are not ancestors
1498 1499 of any other head in the repo. If a second set is specified, the result
1499 1500 is ancestors of the first set that are not ancestors of the second set
1500 1501 (i.e. ::<set1> - ::<set2>).
1501 1502 """
1502 1503 cl = repo.changelog
1503 1504 # i18n: "only" is a keyword
1504 1505 args = getargs(x, 1, 2, _('only takes one or two arguments'))
1505 1506 include = getset(repo, fullreposet(repo), args[0])
1506 1507 if len(args) == 1:
1507 1508 if not include:
1508 1509 return baseset()
1509 1510
1510 1511 descendants = set(dagop.revdescendants(repo, include, False))
1511 1512 exclude = [rev for rev in cl.headrevs()
1512 1513 if not rev in descendants and not rev in include]
1513 1514 else:
1514 1515 exclude = getset(repo, fullreposet(repo), args[1])
1515 1516
1516 1517 results = set(cl.findmissingrevs(common=exclude, heads=include))
1517 1518 # XXX we should turn this into a baseset instead of a set, smartset may do
1518 1519 # some optimizations from the fact this is a baseset.
1519 1520 return subset & results
1520 1521
1521 1522 @predicate('origin([set])', safe=True)
1522 1523 def origin(repo, subset, x):
1523 1524 """
1524 1525 Changesets that were specified as a source for the grafts, transplants or
1525 1526 rebases that created the given revisions. Omitting the optional set is the
1526 1527 same as passing all(). If a changeset created by these operations is itself
1527 1528 specified as a source for one of these operations, only the source changeset
1528 1529 for the first operation is selected.
1529 1530 """
1530 1531 if x is not None:
1531 1532 dests = getset(repo, fullreposet(repo), x)
1532 1533 else:
1533 1534 dests = fullreposet(repo)
1534 1535
1535 1536 def _firstsrc(rev):
1536 1537 src = _getrevsource(repo, rev)
1537 1538 if src is None:
1538 1539 return None
1539 1540
1540 1541 while True:
1541 1542 prev = _getrevsource(repo, src)
1542 1543
1543 1544 if prev is None:
1544 1545 return src
1545 1546 src = prev
1546 1547
1547 1548 o = {_firstsrc(r) for r in dests}
1548 1549 o -= {None}
1549 1550 # XXX we should turn this into a baseset instead of a set, smartset may do
1550 1551 # some optimizations from the fact this is a baseset.
1551 1552 return subset & o
1552 1553
1553 1554 @predicate('outgoing([path])', safe=False, weight=10)
1554 1555 def outgoing(repo, subset, x):
1555 1556 """Changesets not found in the specified destination repository, or the
1556 1557 default push location.
1557 1558 """
1558 1559 # Avoid cycles.
1559 1560 from . import (
1560 1561 discovery,
1561 1562 hg,
1562 1563 )
1563 1564 # i18n: "outgoing" is a keyword
1564 1565 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1565 1566 # i18n: "outgoing" is a keyword
1566 1567 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1567 1568 if not dest:
1568 1569 # ui.paths.getpath() explicitly tests for None, not just a boolean
1569 1570 dest = None
1570 1571 path = repo.ui.paths.getpath(dest, default=('default-push', 'default'))
1571 1572 if not path:
1572 1573 raise error.Abort(_('default repository not configured!'),
1573 1574 hint=_("see 'hg help config.paths'"))
1574 1575 dest = path.pushloc or path.loc
1575 1576 branches = path.branch, []
1576 1577
1577 1578 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1578 1579 if revs:
1579 1580 revs = [repo.lookup(rev) for rev in revs]
1580 1581 other = hg.peer(repo, {}, dest)
1581 1582 repo.ui.pushbuffer()
1582 1583 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1583 1584 repo.ui.popbuffer()
1584 1585 cl = repo.changelog
1585 1586 o = {cl.rev(r) for r in outgoing.missing}
1586 1587 return subset & o
1587 1588
1588 1589 @predicate('p1([set])', safe=True)
1589 1590 def p1(repo, subset, x):
1590 1591 """First parent of changesets in set, or the working directory.
1591 1592 """
1592 1593 if x is None:
1593 1594 p = repo[x].p1().rev()
1594 1595 if p >= 0:
1595 1596 return subset & baseset([p])
1596 1597 return baseset()
1597 1598
1598 1599 ps = set()
1599 1600 cl = repo.changelog
1600 1601 for r in getset(repo, fullreposet(repo), x):
1601 1602 try:
1602 1603 ps.add(cl.parentrevs(r)[0])
1603 1604 except error.WdirUnsupported:
1604 1605 ps.add(repo[r].p1().rev())
1605 1606 ps -= {node.nullrev}
1606 1607 # XXX we should turn this into a baseset instead of a set, smartset may do
1607 1608 # some optimizations from the fact this is a baseset.
1608 1609 return subset & ps
1609 1610
1610 1611 @predicate('p2([set])', safe=True)
1611 1612 def p2(repo, subset, x):
1612 1613 """Second parent of changesets in set, or the working directory.
1613 1614 """
1614 1615 if x is None:
1615 1616 ps = repo[x].parents()
1616 1617 try:
1617 1618 p = ps[1].rev()
1618 1619 if p >= 0:
1619 1620 return subset & baseset([p])
1620 1621 return baseset()
1621 1622 except IndexError:
1622 1623 return baseset()
1623 1624
1624 1625 ps = set()
1625 1626 cl = repo.changelog
1626 1627 for r in getset(repo, fullreposet(repo), x):
1627 1628 try:
1628 1629 ps.add(cl.parentrevs(r)[1])
1629 1630 except error.WdirUnsupported:
1630 1631 parents = repo[r].parents()
1631 1632 if len(parents) == 2:
1632 1633 ps.add(parents[1])
1633 1634 ps -= {node.nullrev}
1634 1635 # XXX we should turn this into a baseset instead of a set, smartset may do
1635 1636 # some optimizations from the fact this is a baseset.
1636 1637 return subset & ps
1637 1638
1638 1639 def parentpost(repo, subset, x, order):
1639 1640 return p1(repo, subset, x)
1640 1641
1641 1642 @predicate('parents([set])', safe=True)
1642 1643 def parents(repo, subset, x):
1643 1644 """
1644 1645 The set of all parents for all changesets in set, or the working directory.
1645 1646 """
1646 1647 if x is None:
1647 1648 ps = set(p.rev() for p in repo[x].parents())
1648 1649 else:
1649 1650 ps = set()
1650 1651 cl = repo.changelog
1651 1652 up = ps.update
1652 1653 parentrevs = cl.parentrevs
1653 1654 for r in getset(repo, fullreposet(repo), x):
1654 1655 try:
1655 1656 up(parentrevs(r))
1656 1657 except error.WdirUnsupported:
1657 1658 up(p.rev() for p in repo[r].parents())
1658 1659 ps -= {node.nullrev}
1659 1660 return subset & ps
1660 1661
1661 1662 def _phase(repo, subset, *targets):
1662 1663 """helper to select all rev in <targets> phases"""
1663 1664 return repo._phasecache.getrevset(repo, targets, subset)
1664 1665
1665 1666 @predicate('_phase(idx)', safe=True)
1666 1667 def phase(repo, subset, x):
1667 1668 l = getargs(x, 1, 1, ("_phase requires one argument"))
1668 1669 target = getinteger(l[0], ("_phase expects a number"))
1669 1670 return _phase(repo, subset, target)
1670 1671
1671 1672 @predicate('draft()', safe=True)
1672 1673 def draft(repo, subset, x):
1673 1674 """Changeset in draft phase."""
1674 1675 # i18n: "draft" is a keyword
1675 1676 getargs(x, 0, 0, _("draft takes no arguments"))
1676 1677 target = phases.draft
1677 1678 return _phase(repo, subset, target)
1678 1679
1679 1680 @predicate('secret()', safe=True)
1680 1681 def secret(repo, subset, x):
1681 1682 """Changeset in secret phase."""
1682 1683 # i18n: "secret" is a keyword
1683 1684 getargs(x, 0, 0, _("secret takes no arguments"))
1684 1685 target = phases.secret
1685 1686 return _phase(repo, subset, target)
1686 1687
1687 1688 @predicate('stack([revs])', safe=True)
1688 1689 def stack(repo, subset, x):
1689 1690 """Experimental revset for the stack of changesets or working directory
1690 1691 parent. (EXPERIMENTAL)
1691 1692 """
1692 1693 if x is None:
1693 1694 stacks = stackmod.getstack(repo, x)
1694 1695 else:
1695 1696 stacks = smartset.baseset([])
1696 1697 for revision in getset(repo, fullreposet(repo), x):
1697 1698 currentstack = stackmod.getstack(repo, revision)
1698 1699 stacks = stacks + currentstack
1699 1700
1700 1701 return subset & stacks
1701 1702
1702 1703 def parentspec(repo, subset, x, n, order):
1703 1704 """``set^0``
1704 1705 The set.
1705 1706 ``set^1`` (or ``set^``), ``set^2``
1706 1707 First or second parent, respectively, of all changesets in set.
1707 1708 """
1708 1709 try:
1709 1710 n = int(n[1])
1710 1711 if n not in (0, 1, 2):
1711 1712 raise ValueError
1712 1713 except (TypeError, ValueError):
1713 1714 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1714 1715 ps = set()
1715 1716 cl = repo.changelog
1716 1717 for r in getset(repo, fullreposet(repo), x):
1717 1718 if n == 0:
1718 1719 ps.add(r)
1719 1720 elif n == 1:
1720 1721 try:
1721 1722 ps.add(cl.parentrevs(r)[0])
1722 1723 except error.WdirUnsupported:
1723 1724 ps.add(repo[r].p1().rev())
1724 1725 else:
1725 1726 try:
1726 1727 parents = cl.parentrevs(r)
1727 1728 if parents[1] != node.nullrev:
1728 1729 ps.add(parents[1])
1729 1730 except error.WdirUnsupported:
1730 1731 parents = repo[r].parents()
1731 1732 if len(parents) == 2:
1732 1733 ps.add(parents[1].rev())
1733 1734 return subset & ps
1734 1735
1735 1736 @predicate('present(set)', safe=True, takeorder=True)
1736 1737 def present(repo, subset, x, order):
1737 1738 """An empty set, if any revision in set isn't found; otherwise,
1738 1739 all revisions in set.
1739 1740
1740 1741 If any of specified revisions is not present in the local repository,
1741 1742 the query is normally aborted. But this predicate allows the query
1742 1743 to continue even in such cases.
1743 1744 """
1744 1745 try:
1745 1746 return getset(repo, subset, x, order)
1746 1747 except error.RepoLookupError:
1747 1748 return baseset()
1748 1749
1749 1750 # for internal use
1750 1751 @predicate('_notpublic', safe=True)
1751 1752 def _notpublic(repo, subset, x):
1752 1753 getargs(x, 0, 0, "_notpublic takes no arguments")
1753 1754 return _phase(repo, subset, phases.draft, phases.secret)
1754 1755
1755 1756 # for internal use
1756 1757 @predicate('_phaseandancestors(phasename, set)', safe=True)
1757 1758 def _phaseandancestors(repo, subset, x):
1758 1759 # equivalent to (phasename() & ancestors(set)) but more efficient
1759 1760 # phasename could be one of 'draft', 'secret', or '_notpublic'
1760 1761 args = getargs(x, 2, 2, "_phaseandancestors requires two arguments")
1761 1762 phasename = getsymbol(args[0])
1762 1763 s = getset(repo, fullreposet(repo), args[1])
1763 1764
1764 1765 draft = phases.draft
1765 1766 secret = phases.secret
1766 1767 phasenamemap = {
1767 1768 '_notpublic': draft,
1768 1769 'draft': draft, # follow secret's ancestors
1769 1770 'secret': secret,
1770 1771 }
1771 1772 if phasename not in phasenamemap:
1772 1773 raise error.ParseError('%r is not a valid phasename' % phasename)
1773 1774
1774 1775 minimalphase = phasenamemap[phasename]
1775 1776 getphase = repo._phasecache.phase
1776 1777
1777 1778 def cutfunc(rev):
1778 1779 return getphase(repo, rev) < minimalphase
1779 1780
1780 1781 revs = dagop.revancestors(repo, s, cutfunc=cutfunc)
1781 1782
1782 1783 if phasename == 'draft': # need to remove secret changesets
1783 1784 revs = revs.filter(lambda r: getphase(repo, r) == draft)
1784 1785 return subset & revs
1785 1786
1786 1787 @predicate('public()', safe=True)
1787 1788 def public(repo, subset, x):
1788 1789 """Changeset in public phase."""
1789 1790 # i18n: "public" is a keyword
1790 1791 getargs(x, 0, 0, _("public takes no arguments"))
1791 1792 return _phase(repo, subset, phases.public)
1792 1793
1793 1794 @predicate('remote([id [,path]])', safe=False)
1794 1795 def remote(repo, subset, x):
1795 1796 """Local revision that corresponds to the given identifier in a
1796 1797 remote repository, if present. Here, the '.' identifier is a
1797 1798 synonym for the current local branch.
1798 1799 """
1799 1800
1800 1801 from . import hg # avoid start-up nasties
1801 1802 # i18n: "remote" is a keyword
1802 1803 l = getargs(x, 0, 2, _("remote takes zero, one, or two arguments"))
1803 1804
1804 1805 q = '.'
1805 1806 if len(l) > 0:
1806 1807 # i18n: "remote" is a keyword
1807 1808 q = getstring(l[0], _("remote requires a string id"))
1808 1809 if q == '.':
1809 1810 q = repo['.'].branch()
1810 1811
1811 1812 dest = ''
1812 1813 if len(l) > 1:
1813 1814 # i18n: "remote" is a keyword
1814 1815 dest = getstring(l[1], _("remote requires a repository path"))
1815 1816 dest = repo.ui.expandpath(dest or 'default')
1816 1817 dest, branches = hg.parseurl(dest)
1817 1818 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1818 1819 if revs:
1819 1820 revs = [repo.lookup(rev) for rev in revs]
1820 1821 other = hg.peer(repo, {}, dest)
1821 1822 n = other.lookup(q)
1822 1823 if n in repo:
1823 1824 r = repo[n].rev()
1824 1825 if r in subset:
1825 1826 return baseset([r])
1826 1827 return baseset()
1827 1828
1828 1829 @predicate('removes(pattern)', safe=True, weight=30)
1829 1830 def removes(repo, subset, x):
1830 1831 """Changesets which remove files matching pattern.
1831 1832
1832 1833 The pattern without explicit kind like ``glob:`` is expected to be
1833 1834 relative to the current directory and match against a file or a
1834 1835 directory.
1835 1836 """
1836 1837 # i18n: "removes" is a keyword
1837 1838 pat = getstring(x, _("removes requires a pattern"))
1838 1839 return checkstatus(repo, subset, pat, 2)
1839 1840
1840 1841 @predicate('rev(number)', safe=True)
1841 1842 def rev(repo, subset, x):
1842 1843 """Revision with the given numeric identifier.
1843 1844 """
1844 1845 # i18n: "rev" is a keyword
1845 1846 l = getargs(x, 1, 1, _("rev requires one argument"))
1846 1847 try:
1847 1848 # i18n: "rev" is a keyword
1848 1849 l = int(getstring(l[0], _("rev requires a number")))
1849 1850 except (TypeError, ValueError):
1850 1851 # i18n: "rev" is a keyword
1851 1852 raise error.ParseError(_("rev expects a number"))
1852 1853 if l not in repo.changelog and l not in _virtualrevs:
1853 1854 return baseset()
1854 1855 return subset & baseset([l])
1855 1856
1856 1857 @predicate('_rev(number)', safe=True)
1857 1858 def _rev(repo, subset, x):
1858 1859 # internal version of "rev(x)" that raise error if "x" is invalid
1859 1860 # i18n: "rev" is a keyword
1860 1861 l = getargs(x, 1, 1, _("rev requires one argument"))
1861 1862 try:
1862 1863 # i18n: "rev" is a keyword
1863 1864 l = int(getstring(l[0], _("rev requires a number")))
1864 1865 except (TypeError, ValueError):
1865 1866 # i18n: "rev" is a keyword
1866 1867 raise error.ParseError(_("rev expects a number"))
1867 1868 repo.changelog.node(l) # check that the rev exists
1868 1869 return subset & baseset([l])
1869 1870
1870 1871 @predicate('revset(set)', safe=True, takeorder=True)
1871 1872 def revsetpredicate(repo, subset, x, order):
1872 1873 """Strictly interpret the content as a revset.
1873 1874
1874 1875 The content of this special predicate will be strictly interpreted as a
1875 1876 revset. For example, ``revset(id(0))`` will be interpreted as "id(0)"
1876 1877 without possible ambiguity with a "id(0)" bookmark or tag.
1877 1878 """
1878 1879 return getset(repo, subset, x, order)
1879 1880
1880 1881 @predicate('matching(revision [, field])', safe=True)
1881 1882 def matching(repo, subset, x):
1882 1883 """Changesets in which a given set of fields match the set of fields in the
1883 1884 selected revision or set.
1884 1885
1885 1886 To match more than one field pass the list of fields to match separated
1886 1887 by spaces (e.g. ``author description``).
1887 1888
1888 1889 Valid fields are most regular revision fields and some special fields.
1889 1890
1890 1891 Regular revision fields are ``description``, ``author``, ``branch``,
1891 1892 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1892 1893 and ``diff``.
1893 1894 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1894 1895 contents of the revision. Two revisions matching their ``diff`` will
1895 1896 also match their ``files``.
1896 1897
1897 1898 Special fields are ``summary`` and ``metadata``:
1898 1899 ``summary`` matches the first line of the description.
1899 1900 ``metadata`` is equivalent to matching ``description user date``
1900 1901 (i.e. it matches the main metadata fields).
1901 1902
1902 1903 ``metadata`` is the default field which is used when no fields are
1903 1904 specified. You can match more than one field at a time.
1904 1905 """
1905 1906 # i18n: "matching" is a keyword
1906 1907 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1907 1908
1908 1909 revs = getset(repo, fullreposet(repo), l[0])
1909 1910
1910 1911 fieldlist = ['metadata']
1911 1912 if len(l) > 1:
1912 1913 fieldlist = getstring(l[1],
1913 1914 # i18n: "matching" is a keyword
1914 1915 _("matching requires a string "
1915 1916 "as its second argument")).split()
1916 1917
1917 1918 # Make sure that there are no repeated fields,
1918 1919 # expand the 'special' 'metadata' field type
1919 1920 # and check the 'files' whenever we check the 'diff'
1920 1921 fields = []
1921 1922 for field in fieldlist:
1922 1923 if field == 'metadata':
1923 1924 fields += ['user', 'description', 'date']
1924 1925 elif field == 'diff':
1925 1926 # a revision matching the diff must also match the files
1926 1927 # since matching the diff is very costly, make sure to
1927 1928 # also match the files first
1928 1929 fields += ['files', 'diff']
1929 1930 else:
1930 1931 if field == 'author':
1931 1932 field = 'user'
1932 1933 fields.append(field)
1933 1934 fields = set(fields)
1934 1935 if 'summary' in fields and 'description' in fields:
1935 1936 # If a revision matches its description it also matches its summary
1936 1937 fields.discard('summary')
1937 1938
1938 1939 # We may want to match more than one field
1939 1940 # Not all fields take the same amount of time to be matched
1940 1941 # Sort the selected fields in order of increasing matching cost
1941 1942 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1942 1943 'files', 'description', 'substate', 'diff']
1943 1944 def fieldkeyfunc(f):
1944 1945 try:
1945 1946 return fieldorder.index(f)
1946 1947 except ValueError:
1947 1948 # assume an unknown field is very costly
1948 1949 return len(fieldorder)
1949 1950 fields = list(fields)
1950 1951 fields.sort(key=fieldkeyfunc)
1951 1952
1952 1953 # Each field will be matched with its own "getfield" function
1953 1954 # which will be added to the getfieldfuncs array of functions
1954 1955 getfieldfuncs = []
1955 1956 _funcs = {
1956 1957 'user': lambda r: repo[r].user(),
1957 1958 'branch': lambda r: repo[r].branch(),
1958 1959 'date': lambda r: repo[r].date(),
1959 1960 'description': lambda r: repo[r].description(),
1960 1961 'files': lambda r: repo[r].files(),
1961 1962 'parents': lambda r: repo[r].parents(),
1962 1963 'phase': lambda r: repo[r].phase(),
1963 1964 'substate': lambda r: repo[r].substate,
1964 1965 'summary': lambda r: repo[r].description().splitlines()[0],
1965 1966 'diff': lambda r: list(repo[r].diff(
1966 1967 opts=diffutil.diffallopts(repo.ui, {'git': True}))),
1967 1968 }
1968 1969 for info in fields:
1969 1970 getfield = _funcs.get(info, None)
1970 1971 if getfield is None:
1971 1972 raise error.ParseError(
1972 1973 # i18n: "matching" is a keyword
1973 1974 _("unexpected field name passed to matching: %s") % info)
1974 1975 getfieldfuncs.append(getfield)
1975 1976 # convert the getfield array of functions into a "getinfo" function
1976 1977 # which returns an array of field values (or a single value if there
1977 1978 # is only one field to match)
1978 1979 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1979 1980
1980 1981 def matches(x):
1981 1982 for rev in revs:
1982 1983 target = getinfo(rev)
1983 1984 match = True
1984 1985 for n, f in enumerate(getfieldfuncs):
1985 1986 if target[n] != f(x):
1986 1987 match = False
1987 1988 if match:
1988 1989 return True
1989 1990 return False
1990 1991
1991 1992 return subset.filter(matches, condrepr=('<matching%r %r>', fields, revs))
1992 1993
1993 1994 @predicate('reverse(set)', safe=True, takeorder=True, weight=0)
1994 1995 def reverse(repo, subset, x, order):
1995 1996 """Reverse order of set.
1996 1997 """
1997 1998 l = getset(repo, subset, x, order)
1998 1999 if order == defineorder:
1999 2000 l.reverse()
2000 2001 return l
2001 2002
2002 2003 @predicate('roots(set)', safe=True)
2003 2004 def roots(repo, subset, x):
2004 2005 """Changesets in set with no parent changeset in set.
2005 2006 """
2006 2007 s = getset(repo, fullreposet(repo), x)
2007 2008 parents = repo.changelog.parentrevs
2008 2009 def filter(r):
2009 2010 for p in parents(r):
2010 2011 if 0 <= p and p in s:
2011 2012 return False
2012 2013 return True
2013 2014 return subset & s.filter(filter, condrepr='<roots>')
2014 2015
2015 2016 _sortkeyfuncs = {
2016 2017 'rev': lambda c: c.rev(),
2017 2018 'branch': lambda c: c.branch(),
2018 2019 'desc': lambda c: c.description(),
2019 2020 'user': lambda c: c.user(),
2020 2021 'author': lambda c: c.user(),
2021 2022 'date': lambda c: c.date()[0],
2022 2023 }
2023 2024
2024 2025 def _getsortargs(x):
2025 2026 """Parse sort options into (set, [(key, reverse)], opts)"""
2026 2027 args = getargsdict(x, 'sort', 'set keys topo.firstbranch')
2027 2028 if 'set' not in args:
2028 2029 # i18n: "sort" is a keyword
2029 2030 raise error.ParseError(_('sort requires one or two arguments'))
2030 2031 keys = "rev"
2031 2032 if 'keys' in args:
2032 2033 # i18n: "sort" is a keyword
2033 2034 keys = getstring(args['keys'], _("sort spec must be a string"))
2034 2035
2035 2036 keyflags = []
2036 2037 for k in keys.split():
2037 2038 fk = k
2038 2039 reverse = (k.startswith('-'))
2039 2040 if reverse:
2040 2041 k = k[1:]
2041 2042 if k not in _sortkeyfuncs and k != 'topo':
2042 2043 raise error.ParseError(
2043 2044 _("unknown sort key %r") % pycompat.bytestr(fk))
2044 2045 keyflags.append((k, reverse))
2045 2046
2046 2047 if len(keyflags) > 1 and any(k == 'topo' for k, reverse in keyflags):
2047 2048 # i18n: "topo" is a keyword
2048 2049 raise error.ParseError(_('topo sort order cannot be combined '
2049 2050 'with other sort keys'))
2050 2051
2051 2052 opts = {}
2052 2053 if 'topo.firstbranch' in args:
2053 2054 if any(k == 'topo' for k, reverse in keyflags):
2054 2055 opts['topo.firstbranch'] = args['topo.firstbranch']
2055 2056 else:
2056 2057 # i18n: "topo" and "topo.firstbranch" are keywords
2057 2058 raise error.ParseError(_('topo.firstbranch can only be used '
2058 2059 'when using the topo sort key'))
2059 2060
2060 2061 return args['set'], keyflags, opts
2061 2062
2062 2063 @predicate('sort(set[, [-]key... [, ...]])', safe=True, takeorder=True,
2063 2064 weight=10)
2064 2065 def sort(repo, subset, x, order):
2065 2066 """Sort set by keys. The default sort order is ascending, specify a key
2066 2067 as ``-key`` to sort in descending order.
2067 2068
2068 2069 The keys can be:
2069 2070
2070 2071 - ``rev`` for the revision number,
2071 2072 - ``branch`` for the branch name,
2072 2073 - ``desc`` for the commit message (description),
2073 2074 - ``user`` for user name (``author`` can be used as an alias),
2074 2075 - ``date`` for the commit date
2075 2076 - ``topo`` for a reverse topographical sort
2076 2077
2077 2078 The ``topo`` sort order cannot be combined with other sort keys. This sort
2078 2079 takes one optional argument, ``topo.firstbranch``, which takes a revset that
2079 2080 specifies what topographical branches to prioritize in the sort.
2080 2081
2081 2082 """
2082 2083 s, keyflags, opts = _getsortargs(x)
2083 2084 revs = getset(repo, subset, s, order)
2084 2085
2085 2086 if not keyflags or order != defineorder:
2086 2087 return revs
2087 2088 if len(keyflags) == 1 and keyflags[0][0] == "rev":
2088 2089 revs.sort(reverse=keyflags[0][1])
2089 2090 return revs
2090 2091 elif keyflags[0][0] == "topo":
2091 2092 firstbranch = ()
2092 2093 if 'topo.firstbranch' in opts:
2093 2094 firstbranch = getset(repo, subset, opts['topo.firstbranch'])
2094 2095 revs = baseset(dagop.toposort(revs, repo.changelog.parentrevs,
2095 2096 firstbranch),
2096 2097 istopo=True)
2097 2098 if keyflags[0][1]:
2098 2099 revs.reverse()
2099 2100 return revs
2100 2101
2101 2102 # sort() is guaranteed to be stable
2102 2103 ctxs = [repo[r] for r in revs]
2103 2104 for k, reverse in reversed(keyflags):
2104 2105 ctxs.sort(key=_sortkeyfuncs[k], reverse=reverse)
2105 2106 return baseset([c.rev() for c in ctxs])
2106 2107
2107 2108 @predicate('subrepo([pattern])')
2108 2109 def subrepo(repo, subset, x):
2109 2110 """Changesets that add, modify or remove the given subrepo. If no subrepo
2110 2111 pattern is named, any subrepo changes are returned.
2111 2112 """
2112 2113 # i18n: "subrepo" is a keyword
2113 2114 args = getargs(x, 0, 1, _('subrepo takes at most one argument'))
2114 2115 pat = None
2115 2116 if len(args) != 0:
2116 2117 pat = getstring(args[0], _("subrepo requires a pattern"))
2117 2118
2118 2119 m = matchmod.exact(['.hgsubstate'])
2119 2120
2120 2121 def submatches(names):
2121 2122 k, p, m = stringutil.stringmatcher(pat)
2122 2123 for name in names:
2123 2124 if m(name):
2124 2125 yield name
2125 2126
2126 2127 def matches(x):
2127 2128 c = repo[x]
2128 2129 s = repo.status(c.p1().node(), c.node(), match=m)
2129 2130
2130 2131 if pat is None:
2131 2132 return s.added or s.modified or s.removed
2132 2133
2133 2134 if s.added:
2134 2135 return any(submatches(c.substate.keys()))
2135 2136
2136 2137 if s.modified:
2137 2138 subs = set(c.p1().substate.keys())
2138 2139 subs.update(c.substate.keys())
2139 2140
2140 2141 for path in submatches(subs):
2141 2142 if c.p1().substate.get(path) != c.substate.get(path):
2142 2143 return True
2143 2144
2144 2145 if s.removed:
2145 2146 return any(submatches(c.p1().substate.keys()))
2146 2147
2147 2148 return False
2148 2149
2149 2150 return subset.filter(matches, condrepr=('<subrepo %r>', pat))
2150 2151
2151 2152 def _mapbynodefunc(repo, s, f):
2152 2153 """(repo, smartset, [node] -> [node]) -> smartset
2153 2154
2154 2155 Helper method to map a smartset to another smartset given a function only
2155 2156 talking about nodes. Handles converting between rev numbers and nodes, and
2156 2157 filtering.
2157 2158 """
2158 2159 cl = repo.unfiltered().changelog
2159 2160 torev = cl.rev
2160 2161 tonode = cl.node
2161 2162 nodemap = cl.nodemap
2162 2163 result = set(torev(n) for n in f(tonode(r) for r in s) if n in nodemap)
2163 2164 return smartset.baseset(result - repo.changelog.filteredrevs)
2164 2165
2165 2166 @predicate('successors(set)', safe=True)
2166 2167 def successors(repo, subset, x):
2167 2168 """All successors for set, including the given set themselves"""
2168 2169 s = getset(repo, fullreposet(repo), x)
2169 2170 f = lambda nodes: obsutil.allsuccessors(repo.obsstore, nodes)
2170 2171 d = _mapbynodefunc(repo, s, f)
2171 2172 return subset & d
2172 2173
2173 2174 def _substringmatcher(pattern, casesensitive=True):
2174 2175 kind, pattern, matcher = stringutil.stringmatcher(
2175 2176 pattern, casesensitive=casesensitive)
2176 2177 if kind == 'literal':
2177 2178 if not casesensitive:
2178 2179 pattern = encoding.lower(pattern)
2179 2180 matcher = lambda s: pattern in encoding.lower(s)
2180 2181 else:
2181 2182 matcher = lambda s: pattern in s
2182 2183 return kind, pattern, matcher
2183 2184
2184 2185 @predicate('tag([name])', safe=True)
2185 2186 def tag(repo, subset, x):
2186 2187 """The specified tag by name, or all tagged revisions if no name is given.
2187 2188
2188 2189 Pattern matching is supported for `name`. See
2189 2190 :hg:`help revisions.patterns`.
2190 2191 """
2191 2192 # i18n: "tag" is a keyword
2192 2193 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
2193 2194 cl = repo.changelog
2194 2195 if args:
2195 2196 pattern = getstring(args[0],
2196 2197 # i18n: "tag" is a keyword
2197 2198 _('the argument to tag must be a string'))
2198 2199 kind, pattern, matcher = stringutil.stringmatcher(pattern)
2199 2200 if kind == 'literal':
2200 2201 # avoid resolving all tags
2201 2202 tn = repo._tagscache.tags.get(pattern, None)
2202 2203 if tn is None:
2203 2204 raise error.RepoLookupError(_("tag '%s' does not exist")
2204 2205 % pattern)
2205 2206 s = {repo[tn].rev()}
2206 2207 else:
2207 2208 s = {cl.rev(n) for t, n in repo.tagslist() if matcher(t)}
2208 2209 else:
2209 2210 s = {cl.rev(n) for t, n in repo.tagslist() if t != 'tip'}
2210 2211 return subset & s
2211 2212
2212 2213 @predicate('tagged', safe=True)
2213 2214 def tagged(repo, subset, x):
2214 2215 return tag(repo, subset, x)
2215 2216
2216 2217 @predicate('orphan()', safe=True)
2217 2218 def orphan(repo, subset, x):
2218 2219 """Non-obsolete changesets with obsolete ancestors. (EXPERIMENTAL)
2219 2220 """
2220 2221 # i18n: "orphan" is a keyword
2221 2222 getargs(x, 0, 0, _("orphan takes no arguments"))
2222 2223 orphan = obsmod.getrevs(repo, 'orphan')
2223 2224 return subset & orphan
2224 2225
2225 2226
2226 2227 @predicate('user(string)', safe=True, weight=10)
2227 2228 def user(repo, subset, x):
2228 2229 """User name contains string. The match is case-insensitive.
2229 2230
2230 2231 Pattern matching is supported for `string`. See
2231 2232 :hg:`help revisions.patterns`.
2232 2233 """
2233 2234 return author(repo, subset, x)
2234 2235
2235 2236 @predicate('wdir()', safe=True, weight=0)
2236 2237 def wdir(repo, subset, x):
2237 2238 """Working directory. (EXPERIMENTAL)"""
2238 2239 # i18n: "wdir" is a keyword
2239 2240 getargs(x, 0, 0, _("wdir takes no arguments"))
2240 2241 if node.wdirrev in subset or isinstance(subset, fullreposet):
2241 2242 return baseset([node.wdirrev])
2242 2243 return baseset()
2243 2244
2244 2245 def _orderedlist(repo, subset, x):
2245 2246 s = getstring(x, "internal error")
2246 2247 if not s:
2247 2248 return baseset()
2248 2249 # remove duplicates here. it's difficult for caller to deduplicate sets
2249 2250 # because different symbols can point to the same rev.
2250 2251 cl = repo.changelog
2251 2252 ls = []
2252 2253 seen = set()
2253 2254 for t in s.split('\0'):
2254 2255 try:
2255 2256 # fast path for integer revision
2256 2257 r = int(t)
2257 2258 if ('%d' % r) != t or r not in cl:
2258 2259 raise ValueError
2259 2260 revs = [r]
2260 2261 except ValueError:
2261 2262 revs = stringset(repo, subset, t, defineorder)
2262 2263
2263 2264 for r in revs:
2264 2265 if r in seen:
2265 2266 continue
2266 2267 if (r in subset
2267 2268 or r in _virtualrevs and isinstance(subset, fullreposet)):
2268 2269 ls.append(r)
2269 2270 seen.add(r)
2270 2271 return baseset(ls)
2271 2272
2272 2273 # for internal use
2273 2274 @predicate('_list', safe=True, takeorder=True)
2274 2275 def _list(repo, subset, x, order):
2275 2276 if order == followorder:
2276 2277 # slow path to take the subset order
2277 2278 return subset & _orderedlist(repo, fullreposet(repo), x)
2278 2279 else:
2279 2280 return _orderedlist(repo, subset, x)
2280 2281
2281 2282 def _orderedintlist(repo, subset, x):
2282 2283 s = getstring(x, "internal error")
2283 2284 if not s:
2284 2285 return baseset()
2285 2286 ls = [int(r) for r in s.split('\0')]
2286 2287 s = subset
2287 2288 return baseset([r for r in ls if r in s])
2288 2289
2289 2290 # for internal use
2290 2291 @predicate('_intlist', safe=True, takeorder=True, weight=0)
2291 2292 def _intlist(repo, subset, x, order):
2292 2293 if order == followorder:
2293 2294 # slow path to take the subset order
2294 2295 return subset & _orderedintlist(repo, fullreposet(repo), x)
2295 2296 else:
2296 2297 return _orderedintlist(repo, subset, x)
2297 2298
2298 2299 def _orderedhexlist(repo, subset, x):
2299 2300 s = getstring(x, "internal error")
2300 2301 if not s:
2301 2302 return baseset()
2302 2303 cl = repo.changelog
2303 2304 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
2304 2305 s = subset
2305 2306 return baseset([r for r in ls if r in s])
2306 2307
2307 2308 # for internal use
2308 2309 @predicate('_hexlist', safe=True, takeorder=True)
2309 2310 def _hexlist(repo, subset, x, order):
2310 2311 if order == followorder:
2311 2312 # slow path to take the subset order
2312 2313 return subset & _orderedhexlist(repo, fullreposet(repo), x)
2313 2314 else:
2314 2315 return _orderedhexlist(repo, subset, x)
2315 2316
2316 2317 methods = {
2317 2318 "range": rangeset,
2318 2319 "rangeall": rangeall,
2319 2320 "rangepre": rangepre,
2320 2321 "rangepost": rangepost,
2321 2322 "dagrange": dagrange,
2322 2323 "string": stringset,
2323 2324 "symbol": stringset,
2324 2325 "and": andset,
2325 2326 "andsmally": andsmallyset,
2326 2327 "or": orset,
2327 2328 "not": notset,
2328 2329 "difference": differenceset,
2329 2330 "relation": relationset,
2330 2331 "relsubscript": relsubscriptset,
2331 2332 "subscript": subscriptset,
2332 2333 "list": listset,
2333 2334 "keyvalue": keyvaluepair,
2334 2335 "func": func,
2335 2336 "ancestor": ancestorspec,
2336 2337 "parent": parentspec,
2337 2338 "parentpost": parentpost,
2338 2339 "smartset": rawsmartset,
2339 2340 }
2340 2341
2341 2342 subscriptrelations = {
2342 2343 "g": generationsrel,
2343 2344 "generations": generationsrel,
2344 2345 }
2345 2346
2346 2347 def lookupfn(repo):
2347 2348 return lambda symbol: scmutil.isrevsymbol(repo, symbol)
2348 2349
2349 2350 def match(ui, spec, lookup=None):
2350 2351 """Create a matcher for a single revision spec"""
2351 2352 return matchany(ui, [spec], lookup=lookup)
2352 2353
2353 2354 def matchany(ui, specs, lookup=None, localalias=None):
2354 2355 """Create a matcher that will include any revisions matching one of the
2355 2356 given specs
2356 2357
2357 2358 If lookup function is not None, the parser will first attempt to handle
2358 2359 old-style ranges, which may contain operator characters.
2359 2360
2360 2361 If localalias is not None, it is a dict {name: definitionstring}. It takes
2361 2362 precedence over [revsetalias] config section.
2362 2363 """
2363 2364 if not specs:
2364 2365 def mfunc(repo, subset=None):
2365 2366 return baseset()
2366 2367 return mfunc
2367 2368 if not all(specs):
2368 2369 raise error.ParseError(_("empty query"))
2369 2370 if len(specs) == 1:
2370 2371 tree = revsetlang.parse(specs[0], lookup)
2371 2372 else:
2372 2373 tree = ('or',
2373 2374 ('list',) + tuple(revsetlang.parse(s, lookup) for s in specs))
2374 2375
2375 2376 aliases = []
2376 2377 warn = None
2377 2378 if ui:
2378 2379 aliases.extend(ui.configitems('revsetalias'))
2379 2380 warn = ui.warn
2380 2381 if localalias:
2381 2382 aliases.extend(localalias.items())
2382 2383 if aliases:
2383 2384 tree = revsetlang.expandaliases(tree, aliases, warn=warn)
2384 2385 tree = revsetlang.foldconcat(tree)
2385 2386 tree = revsetlang.analyze(tree)
2386 2387 tree = revsetlang.optimize(tree)
2387 2388 return makematcher(tree)
2388 2389
2389 2390 def makematcher(tree):
2390 2391 """Create a matcher from an evaluatable tree"""
2391 2392 def mfunc(repo, subset=None, order=None):
2392 2393 if order is None:
2393 2394 if subset is None:
2394 2395 order = defineorder # 'x'
2395 2396 else:
2396 2397 order = followorder # 'subset & x'
2397 2398 if subset is None:
2398 2399 subset = fullreposet(repo)
2399 2400 return getset(repo, subset, tree, order)
2400 2401 return mfunc
2401 2402
2402 2403 def loadpredicate(ui, extname, registrarobj):
2403 2404 """Load revset predicates from specified registrarobj
2404 2405 """
2405 2406 for name, func in registrarobj._table.iteritems():
2406 2407 symbols[name] = func
2407 2408 if func._safe:
2408 2409 safesymbols.add(name)
2409 2410
2410 2411 # load built-in predicates explicitly to setup safesymbols
2411 2412 loadpredicate(None, None, predicate)
2412 2413
2413 2414 # tell hggettext to extract docstrings from these functions:
2414 2415 i18nfunctions = symbols.values()
General Comments 0
You need to be logged in to leave comments. Login now