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