##// END OF EJS Templates
revset: add documentation and comment for _generatorset...
Pierre-Yves David -
r20739:1b4f2399 default
parent child Browse files
Show More
@@ -1,2772 +1,2780 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 import re
8 import re
9 import parser, util, error, discovery, hbisect, phases
9 import parser, util, error, discovery, hbisect, phases
10 import node
10 import node
11 import heapq
11 import heapq
12 import match as matchmod
12 import match as matchmod
13 import ancestor as ancestormod
13 import ancestor as ancestormod
14 from i18n import _
14 from i18n import _
15 import encoding
15 import encoding
16 import obsolete as obsmod
16 import obsolete as obsmod
17 import pathutil
17 import pathutil
18 import repoview
18 import repoview
19
19
20 def _revancestors(repo, revs, followfirst):
20 def _revancestors(repo, revs, followfirst):
21 """Like revlog.ancestors(), but supports followfirst."""
21 """Like revlog.ancestors(), but supports followfirst."""
22 cut = followfirst and 1 or None
22 cut = followfirst and 1 or None
23 cl = repo.changelog
23 cl = repo.changelog
24
24
25 def iterate():
25 def iterate():
26 revqueue, revsnode = None, None
26 revqueue, revsnode = None, None
27 h = []
27 h = []
28
28
29 revs.descending()
29 revs.descending()
30 revqueue = util.deque(revs)
30 revqueue = util.deque(revs)
31 if revqueue:
31 if revqueue:
32 revsnode = revqueue.popleft()
32 revsnode = revqueue.popleft()
33 heapq.heappush(h, -revsnode)
33 heapq.heappush(h, -revsnode)
34
34
35 seen = set([node.nullrev])
35 seen = set([node.nullrev])
36 while h:
36 while h:
37 current = -heapq.heappop(h)
37 current = -heapq.heappop(h)
38 if current not in seen:
38 if current not in seen:
39 if revsnode and current == revsnode:
39 if revsnode and current == revsnode:
40 if revqueue:
40 if revqueue:
41 revsnode = revqueue.popleft()
41 revsnode = revqueue.popleft()
42 heapq.heappush(h, -revsnode)
42 heapq.heappush(h, -revsnode)
43 seen.add(current)
43 seen.add(current)
44 yield current
44 yield current
45 for parent in cl.parentrevs(current)[:cut]:
45 for parent in cl.parentrevs(current)[:cut]:
46 if parent != node.nullrev:
46 if parent != node.nullrev:
47 heapq.heappush(h, -parent)
47 heapq.heappush(h, -parent)
48
48
49 return _descgeneratorset(iterate())
49 return _descgeneratorset(iterate())
50
50
51 def _revdescendants(repo, revs, followfirst):
51 def _revdescendants(repo, revs, followfirst):
52 """Like revlog.descendants() but supports followfirst."""
52 """Like revlog.descendants() but supports followfirst."""
53 cut = followfirst and 1 or None
53 cut = followfirst and 1 or None
54
54
55 def iterate():
55 def iterate():
56 cl = repo.changelog
56 cl = repo.changelog
57 first = min(revs)
57 first = min(revs)
58 nullrev = node.nullrev
58 nullrev = node.nullrev
59 if first == nullrev:
59 if first == nullrev:
60 # Are there nodes with a null first parent and a non-null
60 # Are there nodes with a null first parent and a non-null
61 # second one? Maybe. Do we care? Probably not.
61 # second one? Maybe. Do we care? Probably not.
62 for i in cl:
62 for i in cl:
63 yield i
63 yield i
64 else:
64 else:
65 seen = set(revs)
65 seen = set(revs)
66 for i in cl.revs(first + 1):
66 for i in cl.revs(first + 1):
67 for x in cl.parentrevs(i)[:cut]:
67 for x in cl.parentrevs(i)[:cut]:
68 if x != nullrev and x in seen:
68 if x != nullrev and x in seen:
69 seen.add(i)
69 seen.add(i)
70 yield i
70 yield i
71 break
71 break
72
72
73 return _ascgeneratorset(iterate())
73 return _ascgeneratorset(iterate())
74
74
75 def _revsbetween(repo, roots, heads):
75 def _revsbetween(repo, roots, heads):
76 """Return all paths between roots and heads, inclusive of both endpoint
76 """Return all paths between roots and heads, inclusive of both endpoint
77 sets."""
77 sets."""
78 if not roots:
78 if not roots:
79 return baseset([])
79 return baseset([])
80 parentrevs = repo.changelog.parentrevs
80 parentrevs = repo.changelog.parentrevs
81 visit = baseset(heads)
81 visit = baseset(heads)
82 reachable = set()
82 reachable = set()
83 seen = {}
83 seen = {}
84 minroot = min(roots)
84 minroot = min(roots)
85 roots = set(roots)
85 roots = set(roots)
86 # open-code the post-order traversal due to the tiny size of
86 # open-code the post-order traversal due to the tiny size of
87 # sys.getrecursionlimit()
87 # sys.getrecursionlimit()
88 while visit:
88 while visit:
89 rev = visit.pop()
89 rev = visit.pop()
90 if rev in roots:
90 if rev in roots:
91 reachable.add(rev)
91 reachable.add(rev)
92 parents = parentrevs(rev)
92 parents = parentrevs(rev)
93 seen[rev] = parents
93 seen[rev] = parents
94 for parent in parents:
94 for parent in parents:
95 if parent >= minroot and parent not in seen:
95 if parent >= minroot and parent not in seen:
96 visit.append(parent)
96 visit.append(parent)
97 if not reachable:
97 if not reachable:
98 return baseset([])
98 return baseset([])
99 for rev in sorted(seen):
99 for rev in sorted(seen):
100 for parent in seen[rev]:
100 for parent in seen[rev]:
101 if parent in reachable:
101 if parent in reachable:
102 reachable.add(rev)
102 reachable.add(rev)
103 return baseset(sorted(reachable))
103 return baseset(sorted(reachable))
104
104
105 elements = {
105 elements = {
106 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
106 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
107 "~": (18, None, ("ancestor", 18)),
107 "~": (18, None, ("ancestor", 18)),
108 "^": (18, None, ("parent", 18), ("parentpost", 18)),
108 "^": (18, None, ("parent", 18), ("parentpost", 18)),
109 "-": (5, ("negate", 19), ("minus", 5)),
109 "-": (5, ("negate", 19), ("minus", 5)),
110 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
110 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
111 ("dagrangepost", 17)),
111 ("dagrangepost", 17)),
112 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
112 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
113 ("dagrangepost", 17)),
113 ("dagrangepost", 17)),
114 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
114 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
115 "not": (10, ("not", 10)),
115 "not": (10, ("not", 10)),
116 "!": (10, ("not", 10)),
116 "!": (10, ("not", 10)),
117 "and": (5, None, ("and", 5)),
117 "and": (5, None, ("and", 5)),
118 "&": (5, None, ("and", 5)),
118 "&": (5, None, ("and", 5)),
119 "or": (4, None, ("or", 4)),
119 "or": (4, None, ("or", 4)),
120 "|": (4, None, ("or", 4)),
120 "|": (4, None, ("or", 4)),
121 "+": (4, None, ("or", 4)),
121 "+": (4, None, ("or", 4)),
122 ",": (2, None, ("list", 2)),
122 ",": (2, None, ("list", 2)),
123 ")": (0, None, None),
123 ")": (0, None, None),
124 "symbol": (0, ("symbol",), None),
124 "symbol": (0, ("symbol",), None),
125 "string": (0, ("string",), None),
125 "string": (0, ("string",), None),
126 "end": (0, None, None),
126 "end": (0, None, None),
127 }
127 }
128
128
129 keywords = set(['and', 'or', 'not'])
129 keywords = set(['and', 'or', 'not'])
130
130
131 def tokenize(program):
131 def tokenize(program):
132 '''
132 '''
133 Parse a revset statement into a stream of tokens
133 Parse a revset statement into a stream of tokens
134
134
135 Check that @ is a valid unquoted token character (issue3686):
135 Check that @ is a valid unquoted token character (issue3686):
136 >>> list(tokenize("@::"))
136 >>> list(tokenize("@::"))
137 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
137 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
138
138
139 '''
139 '''
140
140
141 pos, l = 0, len(program)
141 pos, l = 0, len(program)
142 while pos < l:
142 while pos < l:
143 c = program[pos]
143 c = program[pos]
144 if c.isspace(): # skip inter-token whitespace
144 if c.isspace(): # skip inter-token whitespace
145 pass
145 pass
146 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
146 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
147 yield ('::', None, pos)
147 yield ('::', None, pos)
148 pos += 1 # skip ahead
148 pos += 1 # skip ahead
149 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
149 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
150 yield ('..', None, pos)
150 yield ('..', None, pos)
151 pos += 1 # skip ahead
151 pos += 1 # skip ahead
152 elif c in "():,-|&+!~^": # handle simple operators
152 elif c in "():,-|&+!~^": # handle simple operators
153 yield (c, None, pos)
153 yield (c, None, pos)
154 elif (c in '"\'' or c == 'r' and
154 elif (c in '"\'' or c == 'r' and
155 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
155 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
156 if c == 'r':
156 if c == 'r':
157 pos += 1
157 pos += 1
158 c = program[pos]
158 c = program[pos]
159 decode = lambda x: x
159 decode = lambda x: x
160 else:
160 else:
161 decode = lambda x: x.decode('string-escape')
161 decode = lambda x: x.decode('string-escape')
162 pos += 1
162 pos += 1
163 s = pos
163 s = pos
164 while pos < l: # find closing quote
164 while pos < l: # find closing quote
165 d = program[pos]
165 d = program[pos]
166 if d == '\\': # skip over escaped characters
166 if d == '\\': # skip over escaped characters
167 pos += 2
167 pos += 2
168 continue
168 continue
169 if d == c:
169 if d == c:
170 yield ('string', decode(program[s:pos]), s)
170 yield ('string', decode(program[s:pos]), s)
171 break
171 break
172 pos += 1
172 pos += 1
173 else:
173 else:
174 raise error.ParseError(_("unterminated string"), s)
174 raise error.ParseError(_("unterminated string"), s)
175 # gather up a symbol/keyword
175 # gather up a symbol/keyword
176 elif c.isalnum() or c in '._@' or ord(c) > 127:
176 elif c.isalnum() or c in '._@' or ord(c) > 127:
177 s = pos
177 s = pos
178 pos += 1
178 pos += 1
179 while pos < l: # find end of symbol
179 while pos < l: # find end of symbol
180 d = program[pos]
180 d = program[pos]
181 if not (d.isalnum() or d in "._/@" or ord(d) > 127):
181 if not (d.isalnum() or d in "._/@" or ord(d) > 127):
182 break
182 break
183 if d == '.' and program[pos - 1] == '.': # special case for ..
183 if d == '.' and program[pos - 1] == '.': # special case for ..
184 pos -= 1
184 pos -= 1
185 break
185 break
186 pos += 1
186 pos += 1
187 sym = program[s:pos]
187 sym = program[s:pos]
188 if sym in keywords: # operator keywords
188 if sym in keywords: # operator keywords
189 yield (sym, None, s)
189 yield (sym, None, s)
190 else:
190 else:
191 yield ('symbol', sym, s)
191 yield ('symbol', sym, s)
192 pos -= 1
192 pos -= 1
193 else:
193 else:
194 raise error.ParseError(_("syntax error"), pos)
194 raise error.ParseError(_("syntax error"), pos)
195 pos += 1
195 pos += 1
196 yield ('end', None, pos)
196 yield ('end', None, pos)
197
197
198 # helpers
198 # helpers
199
199
200 def getstring(x, err):
200 def getstring(x, err):
201 if x and (x[0] == 'string' or x[0] == 'symbol'):
201 if x and (x[0] == 'string' or x[0] == 'symbol'):
202 return x[1]
202 return x[1]
203 raise error.ParseError(err)
203 raise error.ParseError(err)
204
204
205 def getlist(x):
205 def getlist(x):
206 if not x:
206 if not x:
207 return []
207 return []
208 if x[0] == 'list':
208 if x[0] == 'list':
209 return getlist(x[1]) + [x[2]]
209 return getlist(x[1]) + [x[2]]
210 return [x]
210 return [x]
211
211
212 def getargs(x, min, max, err):
212 def getargs(x, min, max, err):
213 l = getlist(x)
213 l = getlist(x)
214 if len(l) < min or (max >= 0 and len(l) > max):
214 if len(l) < min or (max >= 0 and len(l) > max):
215 raise error.ParseError(err)
215 raise error.ParseError(err)
216 return l
216 return l
217
217
218 def getset(repo, subset, x):
218 def getset(repo, subset, x):
219 if not x:
219 if not x:
220 raise error.ParseError(_("missing argument"))
220 raise error.ParseError(_("missing argument"))
221 s = methods[x[0]](repo, subset, *x[1:])
221 s = methods[x[0]](repo, subset, *x[1:])
222 if util.safehasattr(s, 'set'):
222 if util.safehasattr(s, 'set'):
223 return s
223 return s
224 return baseset(s)
224 return baseset(s)
225
225
226 def _getrevsource(repo, r):
226 def _getrevsource(repo, r):
227 extra = repo[r].extra()
227 extra = repo[r].extra()
228 for label in ('source', 'transplant_source', 'rebase_source'):
228 for label in ('source', 'transplant_source', 'rebase_source'):
229 if label in extra:
229 if label in extra:
230 try:
230 try:
231 return repo[extra[label]].rev()
231 return repo[extra[label]].rev()
232 except error.RepoLookupError:
232 except error.RepoLookupError:
233 pass
233 pass
234 return None
234 return None
235
235
236 # operator methods
236 # operator methods
237
237
238 def stringset(repo, subset, x):
238 def stringset(repo, subset, x):
239 x = repo[x].rev()
239 x = repo[x].rev()
240 if x == -1 and len(subset) == len(repo):
240 if x == -1 and len(subset) == len(repo):
241 return baseset([-1])
241 return baseset([-1])
242 if len(subset) == len(repo) or x in subset:
242 if len(subset) == len(repo) or x in subset:
243 return baseset([x])
243 return baseset([x])
244 return baseset([])
244 return baseset([])
245
245
246 def symbolset(repo, subset, x):
246 def symbolset(repo, subset, x):
247 if x in symbols:
247 if x in symbols:
248 raise error.ParseError(_("can't use %s here") % x)
248 raise error.ParseError(_("can't use %s here") % x)
249 return stringset(repo, subset, x)
249 return stringset(repo, subset, x)
250
250
251 def rangeset(repo, subset, x, y):
251 def rangeset(repo, subset, x, y):
252 cl = baseset(repo.changelog)
252 cl = baseset(repo.changelog)
253 m = getset(repo, cl, x)
253 m = getset(repo, cl, x)
254 n = getset(repo, cl, y)
254 n = getset(repo, cl, y)
255
255
256 if not m or not n:
256 if not m or not n:
257 return baseset([])
257 return baseset([])
258 m, n = m[0], n[-1]
258 m, n = m[0], n[-1]
259
259
260 if m < n:
260 if m < n:
261 r = spanset(repo, m, n + 1)
261 r = spanset(repo, m, n + 1)
262 else:
262 else:
263 r = spanset(repo, m, n - 1)
263 r = spanset(repo, m, n - 1)
264 return r & subset
264 return r & subset
265
265
266 def dagrange(repo, subset, x, y):
266 def dagrange(repo, subset, x, y):
267 r = spanset(repo)
267 r = spanset(repo)
268 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
268 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
269 s = subset.set()
269 s = subset.set()
270 return xs.filter(lambda r: r in s)
270 return xs.filter(lambda r: r in s)
271
271
272 def andset(repo, subset, x, y):
272 def andset(repo, subset, x, y):
273 return getset(repo, getset(repo, subset, x), y)
273 return getset(repo, getset(repo, subset, x), y)
274
274
275 def orset(repo, subset, x, y):
275 def orset(repo, subset, x, y):
276 xl = getset(repo, subset, x)
276 xl = getset(repo, subset, x)
277 yl = getset(repo, subset - xl, y)
277 yl = getset(repo, subset - xl, y)
278 return xl + yl
278 return xl + yl
279
279
280 def notset(repo, subset, x):
280 def notset(repo, subset, x):
281 return subset - getset(repo, subset, x)
281 return subset - getset(repo, subset, x)
282
282
283 def listset(repo, subset, a, b):
283 def listset(repo, subset, a, b):
284 raise error.ParseError(_("can't use a list in this context"))
284 raise error.ParseError(_("can't use a list in this context"))
285
285
286 def func(repo, subset, a, b):
286 def func(repo, subset, a, b):
287 if a[0] == 'symbol' and a[1] in symbols:
287 if a[0] == 'symbol' and a[1] in symbols:
288 return symbols[a[1]](repo, subset, b)
288 return symbols[a[1]](repo, subset, b)
289 raise error.ParseError(_("not a function: %s") % a[1])
289 raise error.ParseError(_("not a function: %s") % a[1])
290
290
291 # functions
291 # functions
292
292
293 def adds(repo, subset, x):
293 def adds(repo, subset, x):
294 """``adds(pattern)``
294 """``adds(pattern)``
295 Changesets that add a file matching pattern.
295 Changesets that add a file matching pattern.
296
296
297 The pattern without explicit kind like ``glob:`` is expected to be
297 The pattern without explicit kind like ``glob:`` is expected to be
298 relative to the current directory and match against a file or a
298 relative to the current directory and match against a file or a
299 directory.
299 directory.
300 """
300 """
301 # i18n: "adds" is a keyword
301 # i18n: "adds" is a keyword
302 pat = getstring(x, _("adds requires a pattern"))
302 pat = getstring(x, _("adds requires a pattern"))
303 return checkstatus(repo, subset, pat, 1)
303 return checkstatus(repo, subset, pat, 1)
304
304
305 def ancestor(repo, subset, x):
305 def ancestor(repo, subset, x):
306 """``ancestor(*changeset)``
306 """``ancestor(*changeset)``
307 Greatest common ancestor of the changesets.
307 Greatest common ancestor of the changesets.
308
308
309 Accepts 0 or more changesets.
309 Accepts 0 or more changesets.
310 Will return empty list when passed no args.
310 Will return empty list when passed no args.
311 Greatest common ancestor of a single changeset is that changeset.
311 Greatest common ancestor of a single changeset is that changeset.
312 """
312 """
313 # i18n: "ancestor" is a keyword
313 # i18n: "ancestor" is a keyword
314 l = getlist(x)
314 l = getlist(x)
315 rl = spanset(repo)
315 rl = spanset(repo)
316 anc = None
316 anc = None
317
317
318 # (getset(repo, rl, i) for i in l) generates a list of lists
318 # (getset(repo, rl, i) for i in l) generates a list of lists
319 rev = repo.changelog.rev
319 rev = repo.changelog.rev
320 ancestor = repo.changelog.ancestor
320 ancestor = repo.changelog.ancestor
321 node = repo.changelog.node
321 node = repo.changelog.node
322 for revs in (getset(repo, rl, i) for i in l):
322 for revs in (getset(repo, rl, i) for i in l):
323 for r in revs:
323 for r in revs:
324 if anc is None:
324 if anc is None:
325 anc = r
325 anc = r
326 else:
326 else:
327 anc = rev(ancestor(node(anc), node(r)))
327 anc = rev(ancestor(node(anc), node(r)))
328
328
329 if anc is not None and anc in subset:
329 if anc is not None and anc in subset:
330 return baseset([anc])
330 return baseset([anc])
331 return baseset([])
331 return baseset([])
332
332
333 def _ancestors(repo, subset, x, followfirst=False):
333 def _ancestors(repo, subset, x, followfirst=False):
334 args = getset(repo, spanset(repo), x)
334 args = getset(repo, spanset(repo), x)
335 if not args:
335 if not args:
336 return baseset([])
336 return baseset([])
337 s = _revancestors(repo, args, followfirst)
337 s = _revancestors(repo, args, followfirst)
338 return subset.filter(lambda r: r in s)
338 return subset.filter(lambda r: r in s)
339
339
340 def ancestors(repo, subset, x):
340 def ancestors(repo, subset, x):
341 """``ancestors(set)``
341 """``ancestors(set)``
342 Changesets that are ancestors of a changeset in set.
342 Changesets that are ancestors of a changeset in set.
343 """
343 """
344 return _ancestors(repo, subset, x)
344 return _ancestors(repo, subset, x)
345
345
346 def _firstancestors(repo, subset, x):
346 def _firstancestors(repo, subset, x):
347 # ``_firstancestors(set)``
347 # ``_firstancestors(set)``
348 # Like ``ancestors(set)`` but follows only the first parents.
348 # Like ``ancestors(set)`` but follows only the first parents.
349 return _ancestors(repo, subset, x, followfirst=True)
349 return _ancestors(repo, subset, x, followfirst=True)
350
350
351 def ancestorspec(repo, subset, x, n):
351 def ancestorspec(repo, subset, x, n):
352 """``set~n``
352 """``set~n``
353 Changesets that are the Nth ancestor (first parents only) of a changeset
353 Changesets that are the Nth ancestor (first parents only) of a changeset
354 in set.
354 in set.
355 """
355 """
356 try:
356 try:
357 n = int(n[1])
357 n = int(n[1])
358 except (TypeError, ValueError):
358 except (TypeError, ValueError):
359 raise error.ParseError(_("~ expects a number"))
359 raise error.ParseError(_("~ expects a number"))
360 ps = set()
360 ps = set()
361 cl = repo.changelog
361 cl = repo.changelog
362 for r in getset(repo, baseset(cl), x):
362 for r in getset(repo, baseset(cl), x):
363 for i in range(n):
363 for i in range(n):
364 r = cl.parentrevs(r)[0]
364 r = cl.parentrevs(r)[0]
365 ps.add(r)
365 ps.add(r)
366 return subset.filter(lambda r: r in ps)
366 return subset.filter(lambda r: r in ps)
367
367
368 def author(repo, subset, x):
368 def author(repo, subset, x):
369 """``author(string)``
369 """``author(string)``
370 Alias for ``user(string)``.
370 Alias for ``user(string)``.
371 """
371 """
372 # i18n: "author" is a keyword
372 # i18n: "author" is a keyword
373 n = encoding.lower(getstring(x, _("author requires a string")))
373 n = encoding.lower(getstring(x, _("author requires a string")))
374 kind, pattern, matcher = _substringmatcher(n)
374 kind, pattern, matcher = _substringmatcher(n)
375 return subset.filter(lambda x: matcher(encoding.lower(repo[x].user())))
375 return subset.filter(lambda x: matcher(encoding.lower(repo[x].user())))
376
376
377 def only(repo, subset, x):
377 def only(repo, subset, x):
378 """``only(set, [set])``
378 """``only(set, [set])``
379 Changesets that are ancestors of the first set that are not ancestors
379 Changesets that are ancestors of the first set that are not ancestors
380 of any other head in the repo. If a second set is specified, the result
380 of any other head in the repo. If a second set is specified, the result
381 is ancestors of the first set that are not ancestors of the second set
381 is ancestors of the first set that are not ancestors of the second set
382 (i.e. ::<set1> - ::<set2>).
382 (i.e. ::<set1> - ::<set2>).
383 """
383 """
384 cl = repo.changelog
384 cl = repo.changelog
385 args = getargs(x, 1, 2, _('only takes one or two arguments'))
385 args = getargs(x, 1, 2, _('only takes one or two arguments'))
386 include = getset(repo, spanset(repo), args[0]).set()
386 include = getset(repo, spanset(repo), args[0]).set()
387 if len(args) == 1:
387 if len(args) == 1:
388 descendants = set(_revdescendants(repo, include, False))
388 descendants = set(_revdescendants(repo, include, False))
389 exclude = [rev for rev in cl.headrevs()
389 exclude = [rev for rev in cl.headrevs()
390 if not rev in descendants and not rev in include]
390 if not rev in descendants and not rev in include]
391 else:
391 else:
392 exclude = getset(repo, spanset(repo), args[1])
392 exclude = getset(repo, spanset(repo), args[1])
393
393
394 results = set(ancestormod.missingancestors(include, exclude, cl.parentrevs))
394 results = set(ancestormod.missingancestors(include, exclude, cl.parentrevs))
395 return lazyset(subset, lambda x: x in results)
395 return lazyset(subset, lambda x: x in results)
396
396
397 def bisect(repo, subset, x):
397 def bisect(repo, subset, x):
398 """``bisect(string)``
398 """``bisect(string)``
399 Changesets marked in the specified bisect status:
399 Changesets marked in the specified bisect status:
400
400
401 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
401 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
402 - ``goods``, ``bads`` : csets topologically good/bad
402 - ``goods``, ``bads`` : csets topologically good/bad
403 - ``range`` : csets taking part in the bisection
403 - ``range`` : csets taking part in the bisection
404 - ``pruned`` : csets that are goods, bads or skipped
404 - ``pruned`` : csets that are goods, bads or skipped
405 - ``untested`` : csets whose fate is yet unknown
405 - ``untested`` : csets whose fate is yet unknown
406 - ``ignored`` : csets ignored due to DAG topology
406 - ``ignored`` : csets ignored due to DAG topology
407 - ``current`` : the cset currently being bisected
407 - ``current`` : the cset currently being bisected
408 """
408 """
409 # i18n: "bisect" is a keyword
409 # i18n: "bisect" is a keyword
410 status = getstring(x, _("bisect requires a string")).lower()
410 status = getstring(x, _("bisect requires a string")).lower()
411 state = set(hbisect.get(repo, status))
411 state = set(hbisect.get(repo, status))
412 return subset.filter(lambda r: r in state)
412 return subset.filter(lambda r: r in state)
413
413
414 # Backward-compatibility
414 # Backward-compatibility
415 # - no help entry so that we do not advertise it any more
415 # - no help entry so that we do not advertise it any more
416 def bisected(repo, subset, x):
416 def bisected(repo, subset, x):
417 return bisect(repo, subset, x)
417 return bisect(repo, subset, x)
418
418
419 def bookmark(repo, subset, x):
419 def bookmark(repo, subset, x):
420 """``bookmark([name])``
420 """``bookmark([name])``
421 The named bookmark or all bookmarks.
421 The named bookmark or all bookmarks.
422
422
423 If `name` starts with `re:`, the remainder of the name is treated as
423 If `name` starts with `re:`, the remainder of the name is treated as
424 a regular expression. To match a bookmark that actually starts with `re:`,
424 a regular expression. To match a bookmark that actually starts with `re:`,
425 use the prefix `literal:`.
425 use the prefix `literal:`.
426 """
426 """
427 # i18n: "bookmark" is a keyword
427 # i18n: "bookmark" is a keyword
428 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
428 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
429 if args:
429 if args:
430 bm = getstring(args[0],
430 bm = getstring(args[0],
431 # i18n: "bookmark" is a keyword
431 # i18n: "bookmark" is a keyword
432 _('the argument to bookmark must be a string'))
432 _('the argument to bookmark must be a string'))
433 kind, pattern, matcher = _stringmatcher(bm)
433 kind, pattern, matcher = _stringmatcher(bm)
434 if kind == 'literal':
434 if kind == 'literal':
435 bmrev = repo._bookmarks.get(bm, None)
435 bmrev = repo._bookmarks.get(bm, None)
436 if not bmrev:
436 if not bmrev:
437 raise util.Abort(_("bookmark '%s' does not exist") % bm)
437 raise util.Abort(_("bookmark '%s' does not exist") % bm)
438 bmrev = repo[bmrev].rev()
438 bmrev = repo[bmrev].rev()
439 return subset.filter(lambda r: r == bmrev)
439 return subset.filter(lambda r: r == bmrev)
440 else:
440 else:
441 matchrevs = set()
441 matchrevs = set()
442 for name, bmrev in repo._bookmarks.iteritems():
442 for name, bmrev in repo._bookmarks.iteritems():
443 if matcher(name):
443 if matcher(name):
444 matchrevs.add(bmrev)
444 matchrevs.add(bmrev)
445 if not matchrevs:
445 if not matchrevs:
446 raise util.Abort(_("no bookmarks exist that match '%s'")
446 raise util.Abort(_("no bookmarks exist that match '%s'")
447 % pattern)
447 % pattern)
448 bmrevs = set()
448 bmrevs = set()
449 for bmrev in matchrevs:
449 for bmrev in matchrevs:
450 bmrevs.add(repo[bmrev].rev())
450 bmrevs.add(repo[bmrev].rev())
451 return subset & bmrevs
451 return subset & bmrevs
452
452
453 bms = set([repo[r].rev()
453 bms = set([repo[r].rev()
454 for r in repo._bookmarks.values()])
454 for r in repo._bookmarks.values()])
455 return subset.filter(lambda r: r in bms)
455 return subset.filter(lambda r: r in bms)
456
456
457 def branch(repo, subset, x):
457 def branch(repo, subset, x):
458 """``branch(string or set)``
458 """``branch(string or set)``
459 All changesets belonging to the given branch or the branches of the given
459 All changesets belonging to the given branch or the branches of the given
460 changesets.
460 changesets.
461
461
462 If `string` starts with `re:`, the remainder of the name is treated as
462 If `string` starts with `re:`, the remainder of the name is treated as
463 a regular expression. To match a branch that actually starts with `re:`,
463 a regular expression. To match a branch that actually starts with `re:`,
464 use the prefix `literal:`.
464 use the prefix `literal:`.
465 """
465 """
466 try:
466 try:
467 b = getstring(x, '')
467 b = getstring(x, '')
468 except error.ParseError:
468 except error.ParseError:
469 # not a string, but another revspec, e.g. tip()
469 # not a string, but another revspec, e.g. tip()
470 pass
470 pass
471 else:
471 else:
472 kind, pattern, matcher = _stringmatcher(b)
472 kind, pattern, matcher = _stringmatcher(b)
473 if kind == 'literal':
473 if kind == 'literal':
474 # note: falls through to the revspec case if no branch with
474 # note: falls through to the revspec case if no branch with
475 # this name exists
475 # this name exists
476 if pattern in repo.branchmap():
476 if pattern in repo.branchmap():
477 return subset.filter(lambda r: matcher(repo[r].branch()))
477 return subset.filter(lambda r: matcher(repo[r].branch()))
478 else:
478 else:
479 return subset.filter(lambda r: matcher(repo[r].branch()))
479 return subset.filter(lambda r: matcher(repo[r].branch()))
480
480
481 s = getset(repo, spanset(repo), x)
481 s = getset(repo, spanset(repo), x)
482 b = set()
482 b = set()
483 for r in s:
483 for r in s:
484 b.add(repo[r].branch())
484 b.add(repo[r].branch())
485 s = s.set()
485 s = s.set()
486 return subset.filter(lambda r: r in s or repo[r].branch() in b)
486 return subset.filter(lambda r: r in s or repo[r].branch() in b)
487
487
488 def bumped(repo, subset, x):
488 def bumped(repo, subset, x):
489 """``bumped()``
489 """``bumped()``
490 Mutable changesets marked as successors of public changesets.
490 Mutable changesets marked as successors of public changesets.
491
491
492 Only non-public and non-obsolete changesets can be `bumped`.
492 Only non-public and non-obsolete changesets can be `bumped`.
493 """
493 """
494 # i18n: "bumped" is a keyword
494 # i18n: "bumped" is a keyword
495 getargs(x, 0, 0, _("bumped takes no arguments"))
495 getargs(x, 0, 0, _("bumped takes no arguments"))
496 bumped = obsmod.getrevs(repo, 'bumped')
496 bumped = obsmod.getrevs(repo, 'bumped')
497 return subset & bumped
497 return subset & bumped
498
498
499 def bundle(repo, subset, x):
499 def bundle(repo, subset, x):
500 """``bundle()``
500 """``bundle()``
501 Changesets in the bundle.
501 Changesets in the bundle.
502
502
503 Bundle must be specified by the -R option."""
503 Bundle must be specified by the -R option."""
504
504
505 try:
505 try:
506 bundlerevs = repo.changelog.bundlerevs
506 bundlerevs = repo.changelog.bundlerevs
507 except AttributeError:
507 except AttributeError:
508 raise util.Abort(_("no bundle provided - specify with -R"))
508 raise util.Abort(_("no bundle provided - specify with -R"))
509 return subset & bundlerevs
509 return subset & bundlerevs
510
510
511 def checkstatus(repo, subset, pat, field):
511 def checkstatus(repo, subset, pat, field):
512 hasset = matchmod.patkind(pat) == 'set'
512 hasset = matchmod.patkind(pat) == 'set'
513
513
514 def matches(x):
514 def matches(x):
515 m = None
515 m = None
516 fname = None
516 fname = None
517 c = repo[x]
517 c = repo[x]
518 if not m or hasset:
518 if not m or hasset:
519 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
519 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
520 if not m.anypats() and len(m.files()) == 1:
520 if not m.anypats() and len(m.files()) == 1:
521 fname = m.files()[0]
521 fname = m.files()[0]
522 if fname is not None:
522 if fname is not None:
523 if fname not in c.files():
523 if fname not in c.files():
524 return False
524 return False
525 else:
525 else:
526 for f in c.files():
526 for f in c.files():
527 if m(f):
527 if m(f):
528 break
528 break
529 else:
529 else:
530 return False
530 return False
531 files = repo.status(c.p1().node(), c.node())[field]
531 files = repo.status(c.p1().node(), c.node())[field]
532 if fname is not None:
532 if fname is not None:
533 if fname in files:
533 if fname in files:
534 return True
534 return True
535 else:
535 else:
536 for f in files:
536 for f in files:
537 if m(f):
537 if m(f):
538 return True
538 return True
539
539
540 return subset.filter(matches)
540 return subset.filter(matches)
541
541
542 def _children(repo, narrow, parentset):
542 def _children(repo, narrow, parentset):
543 cs = set()
543 cs = set()
544 if not parentset:
544 if not parentset:
545 return baseset(cs)
545 return baseset(cs)
546 pr = repo.changelog.parentrevs
546 pr = repo.changelog.parentrevs
547 minrev = min(parentset)
547 minrev = min(parentset)
548 for r in narrow:
548 for r in narrow:
549 if r <= minrev:
549 if r <= minrev:
550 continue
550 continue
551 for p in pr(r):
551 for p in pr(r):
552 if p in parentset:
552 if p in parentset:
553 cs.add(r)
553 cs.add(r)
554 return baseset(cs)
554 return baseset(cs)
555
555
556 def children(repo, subset, x):
556 def children(repo, subset, x):
557 """``children(set)``
557 """``children(set)``
558 Child changesets of changesets in set.
558 Child changesets of changesets in set.
559 """
559 """
560 s = getset(repo, baseset(repo), x).set()
560 s = getset(repo, baseset(repo), x).set()
561 cs = _children(repo, subset, s)
561 cs = _children(repo, subset, s)
562 return subset & cs
562 return subset & cs
563
563
564 def closed(repo, subset, x):
564 def closed(repo, subset, x):
565 """``closed()``
565 """``closed()``
566 Changeset is closed.
566 Changeset is closed.
567 """
567 """
568 # i18n: "closed" is a keyword
568 # i18n: "closed" is a keyword
569 getargs(x, 0, 0, _("closed takes no arguments"))
569 getargs(x, 0, 0, _("closed takes no arguments"))
570 return subset.filter(lambda r: repo[r].closesbranch())
570 return subset.filter(lambda r: repo[r].closesbranch())
571
571
572 def contains(repo, subset, x):
572 def contains(repo, subset, x):
573 """``contains(pattern)``
573 """``contains(pattern)``
574 Revision contains a file matching pattern. See :hg:`help patterns`
574 Revision contains a file matching pattern. See :hg:`help patterns`
575 for information about file patterns.
575 for information about file patterns.
576
576
577 The pattern without explicit kind like ``glob:`` is expected to be
577 The pattern without explicit kind like ``glob:`` is expected to be
578 relative to the current directory and match against a file exactly
578 relative to the current directory and match against a file exactly
579 for efficiency.
579 for efficiency.
580 """
580 """
581 # i18n: "contains" is a keyword
581 # i18n: "contains" is a keyword
582 pat = getstring(x, _("contains requires a pattern"))
582 pat = getstring(x, _("contains requires a pattern"))
583
583
584 def matches(x):
584 def matches(x):
585 if not matchmod.patkind(pat):
585 if not matchmod.patkind(pat):
586 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
586 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
587 if pats in repo[x]:
587 if pats in repo[x]:
588 return True
588 return True
589 else:
589 else:
590 c = repo[x]
590 c = repo[x]
591 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
591 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
592 for f in c.manifest():
592 for f in c.manifest():
593 if m(f):
593 if m(f):
594 return True
594 return True
595 return False
595 return False
596
596
597 return subset.filter(matches)
597 return subset.filter(matches)
598
598
599 def converted(repo, subset, x):
599 def converted(repo, subset, x):
600 """``converted([id])``
600 """``converted([id])``
601 Changesets converted from the given identifier in the old repository if
601 Changesets converted from the given identifier in the old repository if
602 present, or all converted changesets if no identifier is specified.
602 present, or all converted changesets if no identifier is specified.
603 """
603 """
604
604
605 # There is exactly no chance of resolving the revision, so do a simple
605 # There is exactly no chance of resolving the revision, so do a simple
606 # string compare and hope for the best
606 # string compare and hope for the best
607
607
608 rev = None
608 rev = None
609 # i18n: "converted" is a keyword
609 # i18n: "converted" is a keyword
610 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
610 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
611 if l:
611 if l:
612 # i18n: "converted" is a keyword
612 # i18n: "converted" is a keyword
613 rev = getstring(l[0], _('converted requires a revision'))
613 rev = getstring(l[0], _('converted requires a revision'))
614
614
615 def _matchvalue(r):
615 def _matchvalue(r):
616 source = repo[r].extra().get('convert_revision', None)
616 source = repo[r].extra().get('convert_revision', None)
617 return source is not None and (rev is None or source.startswith(rev))
617 return source is not None and (rev is None or source.startswith(rev))
618
618
619 return subset.filter(lambda r: _matchvalue(r))
619 return subset.filter(lambda r: _matchvalue(r))
620
620
621 def date(repo, subset, x):
621 def date(repo, subset, x):
622 """``date(interval)``
622 """``date(interval)``
623 Changesets within the interval, see :hg:`help dates`.
623 Changesets within the interval, see :hg:`help dates`.
624 """
624 """
625 # i18n: "date" is a keyword
625 # i18n: "date" is a keyword
626 ds = getstring(x, _("date requires a string"))
626 ds = getstring(x, _("date requires a string"))
627 dm = util.matchdate(ds)
627 dm = util.matchdate(ds)
628 return subset.filter(lambda x: dm(repo[x].date()[0]))
628 return subset.filter(lambda x: dm(repo[x].date()[0]))
629
629
630 def desc(repo, subset, x):
630 def desc(repo, subset, x):
631 """``desc(string)``
631 """``desc(string)``
632 Search commit message for string. The match is case-insensitive.
632 Search commit message for string. The match is case-insensitive.
633 """
633 """
634 # i18n: "desc" is a keyword
634 # i18n: "desc" is a keyword
635 ds = encoding.lower(getstring(x, _("desc requires a string")))
635 ds = encoding.lower(getstring(x, _("desc requires a string")))
636
636
637 def matches(x):
637 def matches(x):
638 c = repo[x]
638 c = repo[x]
639 return ds in encoding.lower(c.description())
639 return ds in encoding.lower(c.description())
640
640
641 return subset.filter(matches)
641 return subset.filter(matches)
642
642
643 def _descendants(repo, subset, x, followfirst=False):
643 def _descendants(repo, subset, x, followfirst=False):
644 args = getset(repo, spanset(repo), x)
644 args = getset(repo, spanset(repo), x)
645 if not args:
645 if not args:
646 return baseset([])
646 return baseset([])
647 s = _revdescendants(repo, args, followfirst)
647 s = _revdescendants(repo, args, followfirst)
648 a = set(args)
648 a = set(args)
649 return subset.filter(lambda r: r in s or r in a)
649 return subset.filter(lambda r: r in s or r in a)
650
650
651 def descendants(repo, subset, x):
651 def descendants(repo, subset, x):
652 """``descendants(set)``
652 """``descendants(set)``
653 Changesets which are descendants of changesets in set.
653 Changesets which are descendants of changesets in set.
654 """
654 """
655 return _descendants(repo, subset, x)
655 return _descendants(repo, subset, x)
656
656
657 def _firstdescendants(repo, subset, x):
657 def _firstdescendants(repo, subset, x):
658 # ``_firstdescendants(set)``
658 # ``_firstdescendants(set)``
659 # Like ``descendants(set)`` but follows only the first parents.
659 # Like ``descendants(set)`` but follows only the first parents.
660 return _descendants(repo, subset, x, followfirst=True)
660 return _descendants(repo, subset, x, followfirst=True)
661
661
662 def destination(repo, subset, x):
662 def destination(repo, subset, x):
663 """``destination([set])``
663 """``destination([set])``
664 Changesets that were created by a graft, transplant or rebase operation,
664 Changesets that were created by a graft, transplant or rebase operation,
665 with the given revisions specified as the source. Omitting the optional set
665 with the given revisions specified as the source. Omitting the optional set
666 is the same as passing all().
666 is the same as passing all().
667 """
667 """
668 if x is not None:
668 if x is not None:
669 args = getset(repo, spanset(repo), x).set()
669 args = getset(repo, spanset(repo), x).set()
670 else:
670 else:
671 args = getall(repo, spanset(repo), x).set()
671 args = getall(repo, spanset(repo), x).set()
672
672
673 dests = set()
673 dests = set()
674
674
675 # subset contains all of the possible destinations that can be returned, so
675 # subset contains all of the possible destinations that can be returned, so
676 # iterate over them and see if their source(s) were provided in the args.
676 # iterate over them and see if their source(s) were provided in the args.
677 # Even if the immediate src of r is not in the args, src's source (or
677 # Even if the immediate src of r is not in the args, src's source (or
678 # further back) may be. Scanning back further than the immediate src allows
678 # further back) may be. Scanning back further than the immediate src allows
679 # transitive transplants and rebases to yield the same results as transitive
679 # transitive transplants and rebases to yield the same results as transitive
680 # grafts.
680 # grafts.
681 for r in subset:
681 for r in subset:
682 src = _getrevsource(repo, r)
682 src = _getrevsource(repo, r)
683 lineage = None
683 lineage = None
684
684
685 while src is not None:
685 while src is not None:
686 if lineage is None:
686 if lineage is None:
687 lineage = list()
687 lineage = list()
688
688
689 lineage.append(r)
689 lineage.append(r)
690
690
691 # The visited lineage is a match if the current source is in the arg
691 # The visited lineage is a match if the current source is in the arg
692 # set. Since every candidate dest is visited by way of iterating
692 # set. Since every candidate dest is visited by way of iterating
693 # subset, any dests further back in the lineage will be tested by a
693 # subset, any dests further back in the lineage will be tested by a
694 # different iteration over subset. Likewise, if the src was already
694 # different iteration over subset. Likewise, if the src was already
695 # selected, the current lineage can be selected without going back
695 # selected, the current lineage can be selected without going back
696 # further.
696 # further.
697 if src in args or src in dests:
697 if src in args or src in dests:
698 dests.update(lineage)
698 dests.update(lineage)
699 break
699 break
700
700
701 r = src
701 r = src
702 src = _getrevsource(repo, r)
702 src = _getrevsource(repo, r)
703
703
704 return subset.filter(lambda r: r in dests)
704 return subset.filter(lambda r: r in dests)
705
705
706 def divergent(repo, subset, x):
706 def divergent(repo, subset, x):
707 """``divergent()``
707 """``divergent()``
708 Final successors of changesets with an alternative set of final successors.
708 Final successors of changesets with an alternative set of final successors.
709 """
709 """
710 # i18n: "divergent" is a keyword
710 # i18n: "divergent" is a keyword
711 getargs(x, 0, 0, _("divergent takes no arguments"))
711 getargs(x, 0, 0, _("divergent takes no arguments"))
712 divergent = obsmod.getrevs(repo, 'divergent')
712 divergent = obsmod.getrevs(repo, 'divergent')
713 return subset.filter(lambda r: r in divergent)
713 return subset.filter(lambda r: r in divergent)
714
714
715 def draft(repo, subset, x):
715 def draft(repo, subset, x):
716 """``draft()``
716 """``draft()``
717 Changeset in draft phase."""
717 Changeset in draft phase."""
718 # i18n: "draft" is a keyword
718 # i18n: "draft" is a keyword
719 getargs(x, 0, 0, _("draft takes no arguments"))
719 getargs(x, 0, 0, _("draft takes no arguments"))
720 pc = repo._phasecache
720 pc = repo._phasecache
721 return subset.filter(lambda r: pc.phase(repo, r) == phases.draft)
721 return subset.filter(lambda r: pc.phase(repo, r) == phases.draft)
722
722
723 def extinct(repo, subset, x):
723 def extinct(repo, subset, x):
724 """``extinct()``
724 """``extinct()``
725 Obsolete changesets with obsolete descendants only.
725 Obsolete changesets with obsolete descendants only.
726 """
726 """
727 # i18n: "extinct" is a keyword
727 # i18n: "extinct" is a keyword
728 getargs(x, 0, 0, _("extinct takes no arguments"))
728 getargs(x, 0, 0, _("extinct takes no arguments"))
729 extincts = obsmod.getrevs(repo, 'extinct')
729 extincts = obsmod.getrevs(repo, 'extinct')
730 return subset & extincts
730 return subset & extincts
731
731
732 def extra(repo, subset, x):
732 def extra(repo, subset, x):
733 """``extra(label, [value])``
733 """``extra(label, [value])``
734 Changesets with the given label in the extra metadata, with the given
734 Changesets with the given label in the extra metadata, with the given
735 optional value.
735 optional value.
736
736
737 If `value` starts with `re:`, the remainder of the value is treated as
737 If `value` starts with `re:`, the remainder of the value is treated as
738 a regular expression. To match a value that actually starts with `re:`,
738 a regular expression. To match a value that actually starts with `re:`,
739 use the prefix `literal:`.
739 use the prefix `literal:`.
740 """
740 """
741
741
742 # i18n: "extra" is a keyword
742 # i18n: "extra" is a keyword
743 l = getargs(x, 1, 2, _('extra takes at least 1 and at most 2 arguments'))
743 l = getargs(x, 1, 2, _('extra takes at least 1 and at most 2 arguments'))
744 # i18n: "extra" is a keyword
744 # i18n: "extra" is a keyword
745 label = getstring(l[0], _('first argument to extra must be a string'))
745 label = getstring(l[0], _('first argument to extra must be a string'))
746 value = None
746 value = None
747
747
748 if len(l) > 1:
748 if len(l) > 1:
749 # i18n: "extra" is a keyword
749 # i18n: "extra" is a keyword
750 value = getstring(l[1], _('second argument to extra must be a string'))
750 value = getstring(l[1], _('second argument to extra must be a string'))
751 kind, value, matcher = _stringmatcher(value)
751 kind, value, matcher = _stringmatcher(value)
752
752
753 def _matchvalue(r):
753 def _matchvalue(r):
754 extra = repo[r].extra()
754 extra = repo[r].extra()
755 return label in extra and (value is None or matcher(extra[label]))
755 return label in extra and (value is None or matcher(extra[label]))
756
756
757 return subset.filter(lambda r: _matchvalue(r))
757 return subset.filter(lambda r: _matchvalue(r))
758
758
759 def filelog(repo, subset, x):
759 def filelog(repo, subset, x):
760 """``filelog(pattern)``
760 """``filelog(pattern)``
761 Changesets connected to the specified filelog.
761 Changesets connected to the specified filelog.
762
762
763 For performance reasons, ``filelog()`` does not show every changeset
763 For performance reasons, ``filelog()`` does not show every changeset
764 that affects the requested file(s). See :hg:`help log` for details. For
764 that affects the requested file(s). See :hg:`help log` for details. For
765 a slower, more accurate result, use ``file()``.
765 a slower, more accurate result, use ``file()``.
766
766
767 The pattern without explicit kind like ``glob:`` is expected to be
767 The pattern without explicit kind like ``glob:`` is expected to be
768 relative to the current directory and match against a file exactly
768 relative to the current directory and match against a file exactly
769 for efficiency.
769 for efficiency.
770 """
770 """
771
771
772 # i18n: "filelog" is a keyword
772 # i18n: "filelog" is a keyword
773 pat = getstring(x, _("filelog requires a pattern"))
773 pat = getstring(x, _("filelog requires a pattern"))
774 s = set()
774 s = set()
775
775
776 if not matchmod.patkind(pat):
776 if not matchmod.patkind(pat):
777 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
777 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
778 fl = repo.file(f)
778 fl = repo.file(f)
779 for fr in fl:
779 for fr in fl:
780 s.add(fl.linkrev(fr))
780 s.add(fl.linkrev(fr))
781 else:
781 else:
782 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
782 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
783 for f in repo[None]:
783 for f in repo[None]:
784 if m(f):
784 if m(f):
785 fl = repo.file(f)
785 fl = repo.file(f)
786 for fr in fl:
786 for fr in fl:
787 s.add(fl.linkrev(fr))
787 s.add(fl.linkrev(fr))
788
788
789 return subset.filter(lambda r: r in s)
789 return subset.filter(lambda r: r in s)
790
790
791 def first(repo, subset, x):
791 def first(repo, subset, x):
792 """``first(set, [n])``
792 """``first(set, [n])``
793 An alias for limit().
793 An alias for limit().
794 """
794 """
795 return limit(repo, subset, x)
795 return limit(repo, subset, x)
796
796
797 def _follow(repo, subset, x, name, followfirst=False):
797 def _follow(repo, subset, x, name, followfirst=False):
798 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
798 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
799 c = repo['.']
799 c = repo['.']
800 if l:
800 if l:
801 x = getstring(l[0], _("%s expected a filename") % name)
801 x = getstring(l[0], _("%s expected a filename") % name)
802 if x in c:
802 if x in c:
803 cx = c[x]
803 cx = c[x]
804 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
804 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
805 # include the revision responsible for the most recent version
805 # include the revision responsible for the most recent version
806 s.add(cx.linkrev())
806 s.add(cx.linkrev())
807 else:
807 else:
808 return baseset([])
808 return baseset([])
809 else:
809 else:
810 s = _revancestors(repo, baseset([c.rev()]), followfirst)
810 s = _revancestors(repo, baseset([c.rev()]), followfirst)
811
811
812 return subset.filter(lambda r: r in s)
812 return subset.filter(lambda r: r in s)
813
813
814 def follow(repo, subset, x):
814 def follow(repo, subset, x):
815 """``follow([file])``
815 """``follow([file])``
816 An alias for ``::.`` (ancestors of the working copy's first parent).
816 An alias for ``::.`` (ancestors of the working copy's first parent).
817 If a filename is specified, the history of the given file is followed,
817 If a filename is specified, the history of the given file is followed,
818 including copies.
818 including copies.
819 """
819 """
820 return _follow(repo, subset, x, 'follow')
820 return _follow(repo, subset, x, 'follow')
821
821
822 def _followfirst(repo, subset, x):
822 def _followfirst(repo, subset, x):
823 # ``followfirst([file])``
823 # ``followfirst([file])``
824 # Like ``follow([file])`` but follows only the first parent of
824 # Like ``follow([file])`` but follows only the first parent of
825 # every revision or file revision.
825 # every revision or file revision.
826 return _follow(repo, subset, x, '_followfirst', followfirst=True)
826 return _follow(repo, subset, x, '_followfirst', followfirst=True)
827
827
828 def getall(repo, subset, x):
828 def getall(repo, subset, x):
829 """``all()``
829 """``all()``
830 All changesets, the same as ``0:tip``.
830 All changesets, the same as ``0:tip``.
831 """
831 """
832 # i18n: "all" is a keyword
832 # i18n: "all" is a keyword
833 getargs(x, 0, 0, _("all takes no arguments"))
833 getargs(x, 0, 0, _("all takes no arguments"))
834 return subset
834 return subset
835
835
836 def grep(repo, subset, x):
836 def grep(repo, subset, x):
837 """``grep(regex)``
837 """``grep(regex)``
838 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
838 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
839 to ensure special escape characters are handled correctly. Unlike
839 to ensure special escape characters are handled correctly. Unlike
840 ``keyword(string)``, the match is case-sensitive.
840 ``keyword(string)``, the match is case-sensitive.
841 """
841 """
842 try:
842 try:
843 # i18n: "grep" is a keyword
843 # i18n: "grep" is a keyword
844 gr = re.compile(getstring(x, _("grep requires a string")))
844 gr = re.compile(getstring(x, _("grep requires a string")))
845 except re.error, e:
845 except re.error, e:
846 raise error.ParseError(_('invalid match pattern: %s') % e)
846 raise error.ParseError(_('invalid match pattern: %s') % e)
847
847
848 def matches(x):
848 def matches(x):
849 c = repo[x]
849 c = repo[x]
850 for e in c.files() + [c.user(), c.description()]:
850 for e in c.files() + [c.user(), c.description()]:
851 if gr.search(e):
851 if gr.search(e):
852 return True
852 return True
853 return False
853 return False
854
854
855 return subset.filter(matches)
855 return subset.filter(matches)
856
856
857 def _matchfiles(repo, subset, x):
857 def _matchfiles(repo, subset, x):
858 # _matchfiles takes a revset list of prefixed arguments:
858 # _matchfiles takes a revset list of prefixed arguments:
859 #
859 #
860 # [p:foo, i:bar, x:baz]
860 # [p:foo, i:bar, x:baz]
861 #
861 #
862 # builds a match object from them and filters subset. Allowed
862 # builds a match object from them and filters subset. Allowed
863 # prefixes are 'p:' for regular patterns, 'i:' for include
863 # prefixes are 'p:' for regular patterns, 'i:' for include
864 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
864 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
865 # a revision identifier, or the empty string to reference the
865 # a revision identifier, or the empty string to reference the
866 # working directory, from which the match object is
866 # working directory, from which the match object is
867 # initialized. Use 'd:' to set the default matching mode, default
867 # initialized. Use 'd:' to set the default matching mode, default
868 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
868 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
869
869
870 # i18n: "_matchfiles" is a keyword
870 # i18n: "_matchfiles" is a keyword
871 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
871 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
872 pats, inc, exc = [], [], []
872 pats, inc, exc = [], [], []
873 hasset = False
873 hasset = False
874 rev, default = None, None
874 rev, default = None, None
875 for arg in l:
875 for arg in l:
876 # i18n: "_matchfiles" is a keyword
876 # i18n: "_matchfiles" is a keyword
877 s = getstring(arg, _("_matchfiles requires string arguments"))
877 s = getstring(arg, _("_matchfiles requires string arguments"))
878 prefix, value = s[:2], s[2:]
878 prefix, value = s[:2], s[2:]
879 if prefix == 'p:':
879 if prefix == 'p:':
880 pats.append(value)
880 pats.append(value)
881 elif prefix == 'i:':
881 elif prefix == 'i:':
882 inc.append(value)
882 inc.append(value)
883 elif prefix == 'x:':
883 elif prefix == 'x:':
884 exc.append(value)
884 exc.append(value)
885 elif prefix == 'r:':
885 elif prefix == 'r:':
886 if rev is not None:
886 if rev is not None:
887 # i18n: "_matchfiles" is a keyword
887 # i18n: "_matchfiles" is a keyword
888 raise error.ParseError(_('_matchfiles expected at most one '
888 raise error.ParseError(_('_matchfiles expected at most one '
889 'revision'))
889 'revision'))
890 rev = value
890 rev = value
891 elif prefix == 'd:':
891 elif prefix == 'd:':
892 if default is not None:
892 if default is not None:
893 # i18n: "_matchfiles" is a keyword
893 # i18n: "_matchfiles" is a keyword
894 raise error.ParseError(_('_matchfiles expected at most one '
894 raise error.ParseError(_('_matchfiles expected at most one '
895 'default mode'))
895 'default mode'))
896 default = value
896 default = value
897 else:
897 else:
898 # i18n: "_matchfiles" is a keyword
898 # i18n: "_matchfiles" is a keyword
899 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
899 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
900 if not hasset and matchmod.patkind(value) == 'set':
900 if not hasset and matchmod.patkind(value) == 'set':
901 hasset = True
901 hasset = True
902 if not default:
902 if not default:
903 default = 'glob'
903 default = 'glob'
904
904
905 def matches(x):
905 def matches(x):
906 m = None
906 m = None
907 c = repo[x]
907 c = repo[x]
908 if not m or (hasset and rev is None):
908 if not m or (hasset and rev is None):
909 ctx = c
909 ctx = c
910 if rev is not None:
910 if rev is not None:
911 ctx = repo[rev or None]
911 ctx = repo[rev or None]
912 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
912 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
913 exclude=exc, ctx=ctx, default=default)
913 exclude=exc, ctx=ctx, default=default)
914 for f in c.files():
914 for f in c.files():
915 if m(f):
915 if m(f):
916 return True
916 return True
917 return False
917 return False
918
918
919 return subset.filter(matches)
919 return subset.filter(matches)
920
920
921 def hasfile(repo, subset, x):
921 def hasfile(repo, subset, x):
922 """``file(pattern)``
922 """``file(pattern)``
923 Changesets affecting files matched by pattern.
923 Changesets affecting files matched by pattern.
924
924
925 For a faster but less accurate result, consider using ``filelog()``
925 For a faster but less accurate result, consider using ``filelog()``
926 instead.
926 instead.
927
927
928 This predicate uses ``glob:`` as the default kind of pattern.
928 This predicate uses ``glob:`` as the default kind of pattern.
929 """
929 """
930 # i18n: "file" is a keyword
930 # i18n: "file" is a keyword
931 pat = getstring(x, _("file requires a pattern"))
931 pat = getstring(x, _("file requires a pattern"))
932 return _matchfiles(repo, subset, ('string', 'p:' + pat))
932 return _matchfiles(repo, subset, ('string', 'p:' + pat))
933
933
934 def head(repo, subset, x):
934 def head(repo, subset, x):
935 """``head()``
935 """``head()``
936 Changeset is a named branch head.
936 Changeset is a named branch head.
937 """
937 """
938 # i18n: "head" is a keyword
938 # i18n: "head" is a keyword
939 getargs(x, 0, 0, _("head takes no arguments"))
939 getargs(x, 0, 0, _("head takes no arguments"))
940 hs = set()
940 hs = set()
941 for b, ls in repo.branchmap().iteritems():
941 for b, ls in repo.branchmap().iteritems():
942 hs.update(repo[h].rev() for h in ls)
942 hs.update(repo[h].rev() for h in ls)
943 return baseset(hs).filter(subset.__contains__)
943 return baseset(hs).filter(subset.__contains__)
944
944
945 def heads(repo, subset, x):
945 def heads(repo, subset, x):
946 """``heads(set)``
946 """``heads(set)``
947 Members of set with no children in set.
947 Members of set with no children in set.
948 """
948 """
949 s = getset(repo, subset, x)
949 s = getset(repo, subset, x)
950 ps = parents(repo, subset, x)
950 ps = parents(repo, subset, x)
951 return s - ps
951 return s - ps
952
952
953 def hidden(repo, subset, x):
953 def hidden(repo, subset, x):
954 """``hidden()``
954 """``hidden()``
955 Hidden changesets.
955 Hidden changesets.
956 """
956 """
957 # i18n: "hidden" is a keyword
957 # i18n: "hidden" is a keyword
958 getargs(x, 0, 0, _("hidden takes no arguments"))
958 getargs(x, 0, 0, _("hidden takes no arguments"))
959 hiddenrevs = repoview.filterrevs(repo, 'visible')
959 hiddenrevs = repoview.filterrevs(repo, 'visible')
960 return subset & hiddenrevs
960 return subset & hiddenrevs
961
961
962 def keyword(repo, subset, x):
962 def keyword(repo, subset, x):
963 """``keyword(string)``
963 """``keyword(string)``
964 Search commit message, user name, and names of changed files for
964 Search commit message, user name, and names of changed files for
965 string. The match is case-insensitive.
965 string. The match is case-insensitive.
966 """
966 """
967 # i18n: "keyword" is a keyword
967 # i18n: "keyword" is a keyword
968 kw = encoding.lower(getstring(x, _("keyword requires a string")))
968 kw = encoding.lower(getstring(x, _("keyword requires a string")))
969
969
970 def matches(r):
970 def matches(r):
971 c = repo[r]
971 c = repo[r]
972 return util.any(kw in encoding.lower(t) for t in c.files() + [c.user(),
972 return util.any(kw in encoding.lower(t) for t in c.files() + [c.user(),
973 c.description()])
973 c.description()])
974
974
975 return subset.filter(matches)
975 return subset.filter(matches)
976
976
977 def limit(repo, subset, x):
977 def limit(repo, subset, x):
978 """``limit(set, [n])``
978 """``limit(set, [n])``
979 First n members of set, defaulting to 1.
979 First n members of set, defaulting to 1.
980 """
980 """
981 # i18n: "limit" is a keyword
981 # i18n: "limit" is a keyword
982 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
982 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
983 try:
983 try:
984 lim = 1
984 lim = 1
985 if len(l) == 2:
985 if len(l) == 2:
986 # i18n: "limit" is a keyword
986 # i18n: "limit" is a keyword
987 lim = int(getstring(l[1], _("limit requires a number")))
987 lim = int(getstring(l[1], _("limit requires a number")))
988 except (TypeError, ValueError):
988 except (TypeError, ValueError):
989 # i18n: "limit" is a keyword
989 # i18n: "limit" is a keyword
990 raise error.ParseError(_("limit expects a number"))
990 raise error.ParseError(_("limit expects a number"))
991 ss = subset.set()
991 ss = subset.set()
992 os = getset(repo, spanset(repo), l[0])
992 os = getset(repo, spanset(repo), l[0])
993 bs = baseset([])
993 bs = baseset([])
994 it = iter(os)
994 it = iter(os)
995 for x in xrange(lim):
995 for x in xrange(lim):
996 try:
996 try:
997 y = it.next()
997 y = it.next()
998 if y in ss:
998 if y in ss:
999 bs.append(y)
999 bs.append(y)
1000 except (StopIteration):
1000 except (StopIteration):
1001 break
1001 break
1002 return bs
1002 return bs
1003
1003
1004 def last(repo, subset, x):
1004 def last(repo, subset, x):
1005 """``last(set, [n])``
1005 """``last(set, [n])``
1006 Last n members of set, defaulting to 1.
1006 Last n members of set, defaulting to 1.
1007 """
1007 """
1008 # i18n: "last" is a keyword
1008 # i18n: "last" is a keyword
1009 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1009 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1010 try:
1010 try:
1011 lim = 1
1011 lim = 1
1012 if len(l) == 2:
1012 if len(l) == 2:
1013 # i18n: "last" is a keyword
1013 # i18n: "last" is a keyword
1014 lim = int(getstring(l[1], _("last requires a number")))
1014 lim = int(getstring(l[1], _("last requires a number")))
1015 except (TypeError, ValueError):
1015 except (TypeError, ValueError):
1016 # i18n: "last" is a keyword
1016 # i18n: "last" is a keyword
1017 raise error.ParseError(_("last expects a number"))
1017 raise error.ParseError(_("last expects a number"))
1018 ss = subset.set()
1018 ss = subset.set()
1019 os = getset(repo, spanset(repo), l[0])
1019 os = getset(repo, spanset(repo), l[0])
1020 os.reverse()
1020 os.reverse()
1021 bs = baseset([])
1021 bs = baseset([])
1022 it = iter(os)
1022 it = iter(os)
1023 for x in xrange(lim):
1023 for x in xrange(lim):
1024 try:
1024 try:
1025 y = it.next()
1025 y = it.next()
1026 if y in ss:
1026 if y in ss:
1027 bs.append(y)
1027 bs.append(y)
1028 except (StopIteration):
1028 except (StopIteration):
1029 break
1029 break
1030 return bs
1030 return bs
1031
1031
1032 def maxrev(repo, subset, x):
1032 def maxrev(repo, subset, x):
1033 """``max(set)``
1033 """``max(set)``
1034 Changeset with highest revision number in set.
1034 Changeset with highest revision number in set.
1035 """
1035 """
1036 os = getset(repo, spanset(repo), x)
1036 os = getset(repo, spanset(repo), x)
1037 if os:
1037 if os:
1038 m = max(os)
1038 m = max(os)
1039 if m in subset:
1039 if m in subset:
1040 return baseset([m])
1040 return baseset([m])
1041 return baseset([])
1041 return baseset([])
1042
1042
1043 def merge(repo, subset, x):
1043 def merge(repo, subset, x):
1044 """``merge()``
1044 """``merge()``
1045 Changeset is a merge changeset.
1045 Changeset is a merge changeset.
1046 """
1046 """
1047 # i18n: "merge" is a keyword
1047 # i18n: "merge" is a keyword
1048 getargs(x, 0, 0, _("merge takes no arguments"))
1048 getargs(x, 0, 0, _("merge takes no arguments"))
1049 cl = repo.changelog
1049 cl = repo.changelog
1050 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1)
1050 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1)
1051
1051
1052 def branchpoint(repo, subset, x):
1052 def branchpoint(repo, subset, x):
1053 """``branchpoint()``
1053 """``branchpoint()``
1054 Changesets with more than one child.
1054 Changesets with more than one child.
1055 """
1055 """
1056 # i18n: "branchpoint" is a keyword
1056 # i18n: "branchpoint" is a keyword
1057 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1057 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1058 cl = repo.changelog
1058 cl = repo.changelog
1059 if not subset:
1059 if not subset:
1060 return baseset([])
1060 return baseset([])
1061 baserev = min(subset)
1061 baserev = min(subset)
1062 parentscount = [0]*(len(repo) - baserev)
1062 parentscount = [0]*(len(repo) - baserev)
1063 for r in cl.revs(start=baserev + 1):
1063 for r in cl.revs(start=baserev + 1):
1064 for p in cl.parentrevs(r):
1064 for p in cl.parentrevs(r):
1065 if p >= baserev:
1065 if p >= baserev:
1066 parentscount[p - baserev] += 1
1066 parentscount[p - baserev] += 1
1067 return subset.filter(lambda r: parentscount[r - baserev] > 1)
1067 return subset.filter(lambda r: parentscount[r - baserev] > 1)
1068
1068
1069 def minrev(repo, subset, x):
1069 def minrev(repo, subset, x):
1070 """``min(set)``
1070 """``min(set)``
1071 Changeset with lowest revision number in set.
1071 Changeset with lowest revision number in set.
1072 """
1072 """
1073 os = getset(repo, spanset(repo), x)
1073 os = getset(repo, spanset(repo), x)
1074 if os:
1074 if os:
1075 m = min(os)
1075 m = min(os)
1076 if m in subset:
1076 if m in subset:
1077 return baseset([m])
1077 return baseset([m])
1078 return baseset([])
1078 return baseset([])
1079
1079
1080 def _missingancestors(repo, subset, x):
1080 def _missingancestors(repo, subset, x):
1081 # i18n: "_missingancestors" is a keyword
1081 # i18n: "_missingancestors" is a keyword
1082 revs, bases = getargs(x, 2, 2,
1082 revs, bases = getargs(x, 2, 2,
1083 _("_missingancestors requires two arguments"))
1083 _("_missingancestors requires two arguments"))
1084 rs = baseset(repo)
1084 rs = baseset(repo)
1085 revs = getset(repo, rs, revs)
1085 revs = getset(repo, rs, revs)
1086 bases = getset(repo, rs, bases)
1086 bases = getset(repo, rs, bases)
1087 missing = set(repo.changelog.findmissingrevs(bases, revs))
1087 missing = set(repo.changelog.findmissingrevs(bases, revs))
1088 return baseset([r for r in subset if r in missing])
1088 return baseset([r for r in subset if r in missing])
1089
1089
1090 def modifies(repo, subset, x):
1090 def modifies(repo, subset, x):
1091 """``modifies(pattern)``
1091 """``modifies(pattern)``
1092 Changesets modifying files matched by pattern.
1092 Changesets modifying files matched by pattern.
1093
1093
1094 The pattern without explicit kind like ``glob:`` is expected to be
1094 The pattern without explicit kind like ``glob:`` is expected to be
1095 relative to the current directory and match against a file or a
1095 relative to the current directory and match against a file or a
1096 directory.
1096 directory.
1097 """
1097 """
1098 # i18n: "modifies" is a keyword
1098 # i18n: "modifies" is a keyword
1099 pat = getstring(x, _("modifies requires a pattern"))
1099 pat = getstring(x, _("modifies requires a pattern"))
1100 return checkstatus(repo, subset, pat, 0)
1100 return checkstatus(repo, subset, pat, 0)
1101
1101
1102 def node_(repo, subset, x):
1102 def node_(repo, subset, x):
1103 """``id(string)``
1103 """``id(string)``
1104 Revision non-ambiguously specified by the given hex string prefix.
1104 Revision non-ambiguously specified by the given hex string prefix.
1105 """
1105 """
1106 # i18n: "id" is a keyword
1106 # i18n: "id" is a keyword
1107 l = getargs(x, 1, 1, _("id requires one argument"))
1107 l = getargs(x, 1, 1, _("id requires one argument"))
1108 # i18n: "id" is a keyword
1108 # i18n: "id" is a keyword
1109 n = getstring(l[0], _("id requires a string"))
1109 n = getstring(l[0], _("id requires a string"))
1110 if len(n) == 40:
1110 if len(n) == 40:
1111 rn = repo[n].rev()
1111 rn = repo[n].rev()
1112 else:
1112 else:
1113 rn = None
1113 rn = None
1114 pm = repo.changelog._partialmatch(n)
1114 pm = repo.changelog._partialmatch(n)
1115 if pm is not None:
1115 if pm is not None:
1116 rn = repo.changelog.rev(pm)
1116 rn = repo.changelog.rev(pm)
1117
1117
1118 return subset.filter(lambda r: r == rn)
1118 return subset.filter(lambda r: r == rn)
1119
1119
1120 def obsolete(repo, subset, x):
1120 def obsolete(repo, subset, x):
1121 """``obsolete()``
1121 """``obsolete()``
1122 Mutable changeset with a newer version."""
1122 Mutable changeset with a newer version."""
1123 # i18n: "obsolete" is a keyword
1123 # i18n: "obsolete" is a keyword
1124 getargs(x, 0, 0, _("obsolete takes no arguments"))
1124 getargs(x, 0, 0, _("obsolete takes no arguments"))
1125 obsoletes = obsmod.getrevs(repo, 'obsolete')
1125 obsoletes = obsmod.getrevs(repo, 'obsolete')
1126 return subset & obsoletes
1126 return subset & obsoletes
1127
1127
1128 def origin(repo, subset, x):
1128 def origin(repo, subset, x):
1129 """``origin([set])``
1129 """``origin([set])``
1130 Changesets that were specified as a source for the grafts, transplants or
1130 Changesets that were specified as a source for the grafts, transplants or
1131 rebases that created the given revisions. Omitting the optional set is the
1131 rebases that created the given revisions. Omitting the optional set is the
1132 same as passing all(). If a changeset created by these operations is itself
1132 same as passing all(). If a changeset created by these operations is itself
1133 specified as a source for one of these operations, only the source changeset
1133 specified as a source for one of these operations, only the source changeset
1134 for the first operation is selected.
1134 for the first operation is selected.
1135 """
1135 """
1136 if x is not None:
1136 if x is not None:
1137 args = getset(repo, spanset(repo), x).set()
1137 args = getset(repo, spanset(repo), x).set()
1138 else:
1138 else:
1139 args = getall(repo, spanset(repo), x).set()
1139 args = getall(repo, spanset(repo), x).set()
1140
1140
1141 def _firstsrc(rev):
1141 def _firstsrc(rev):
1142 src = _getrevsource(repo, rev)
1142 src = _getrevsource(repo, rev)
1143 if src is None:
1143 if src is None:
1144 return None
1144 return None
1145
1145
1146 while True:
1146 while True:
1147 prev = _getrevsource(repo, src)
1147 prev = _getrevsource(repo, src)
1148
1148
1149 if prev is None:
1149 if prev is None:
1150 return src
1150 return src
1151 src = prev
1151 src = prev
1152
1152
1153 o = set([_firstsrc(r) for r in args])
1153 o = set([_firstsrc(r) for r in args])
1154 return subset.filter(lambda r: r in o)
1154 return subset.filter(lambda r: r in o)
1155
1155
1156 def outgoing(repo, subset, x):
1156 def outgoing(repo, subset, x):
1157 """``outgoing([path])``
1157 """``outgoing([path])``
1158 Changesets not found in the specified destination repository, or the
1158 Changesets not found in the specified destination repository, or the
1159 default push location.
1159 default push location.
1160 """
1160 """
1161 import hg # avoid start-up nasties
1161 import hg # avoid start-up nasties
1162 # i18n: "outgoing" is a keyword
1162 # i18n: "outgoing" is a keyword
1163 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1163 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1164 # i18n: "outgoing" is a keyword
1164 # i18n: "outgoing" is a keyword
1165 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1165 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1166 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1166 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1167 dest, branches = hg.parseurl(dest)
1167 dest, branches = hg.parseurl(dest)
1168 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1168 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1169 if revs:
1169 if revs:
1170 revs = [repo.lookup(rev) for rev in revs]
1170 revs = [repo.lookup(rev) for rev in revs]
1171 other = hg.peer(repo, {}, dest)
1171 other = hg.peer(repo, {}, dest)
1172 repo.ui.pushbuffer()
1172 repo.ui.pushbuffer()
1173 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1173 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1174 repo.ui.popbuffer()
1174 repo.ui.popbuffer()
1175 cl = repo.changelog
1175 cl = repo.changelog
1176 o = set([cl.rev(r) for r in outgoing.missing])
1176 o = set([cl.rev(r) for r in outgoing.missing])
1177 return subset.filter(lambda r: r in o)
1177 return subset.filter(lambda r: r in o)
1178
1178
1179 def p1(repo, subset, x):
1179 def p1(repo, subset, x):
1180 """``p1([set])``
1180 """``p1([set])``
1181 First parent of changesets in set, or the working directory.
1181 First parent of changesets in set, or the working directory.
1182 """
1182 """
1183 if x is None:
1183 if x is None:
1184 p = repo[x].p1().rev()
1184 p = repo[x].p1().rev()
1185 return subset.filter(lambda r: r == p)
1185 return subset.filter(lambda r: r == p)
1186
1186
1187 ps = set()
1187 ps = set()
1188 cl = repo.changelog
1188 cl = repo.changelog
1189 for r in getset(repo, spanset(repo), x):
1189 for r in getset(repo, spanset(repo), x):
1190 ps.add(cl.parentrevs(r)[0])
1190 ps.add(cl.parentrevs(r)[0])
1191 return subset & ps
1191 return subset & ps
1192
1192
1193 def p2(repo, subset, x):
1193 def p2(repo, subset, x):
1194 """``p2([set])``
1194 """``p2([set])``
1195 Second parent of changesets in set, or the working directory.
1195 Second parent of changesets in set, or the working directory.
1196 """
1196 """
1197 if x is None:
1197 if x is None:
1198 ps = repo[x].parents()
1198 ps = repo[x].parents()
1199 try:
1199 try:
1200 p = ps[1].rev()
1200 p = ps[1].rev()
1201 return subset.filter(lambda r: r == p)
1201 return subset.filter(lambda r: r == p)
1202 except IndexError:
1202 except IndexError:
1203 return baseset([])
1203 return baseset([])
1204
1204
1205 ps = set()
1205 ps = set()
1206 cl = repo.changelog
1206 cl = repo.changelog
1207 for r in getset(repo, spanset(repo), x):
1207 for r in getset(repo, spanset(repo), x):
1208 ps.add(cl.parentrevs(r)[1])
1208 ps.add(cl.parentrevs(r)[1])
1209 return subset & ps
1209 return subset & ps
1210
1210
1211 def parents(repo, subset, x):
1211 def parents(repo, subset, x):
1212 """``parents([set])``
1212 """``parents([set])``
1213 The set of all parents for all changesets in set, or the working directory.
1213 The set of all parents for all changesets in set, or the working directory.
1214 """
1214 """
1215 if x is None:
1215 if x is None:
1216 ps = tuple(p.rev() for p in repo[x].parents())
1216 ps = tuple(p.rev() for p in repo[x].parents())
1217 return subset & ps
1217 return subset & ps
1218
1218
1219 ps = set()
1219 ps = set()
1220 cl = repo.changelog
1220 cl = repo.changelog
1221 for r in getset(repo, spanset(repo), x):
1221 for r in getset(repo, spanset(repo), x):
1222 ps.update(cl.parentrevs(r))
1222 ps.update(cl.parentrevs(r))
1223 return subset & ps
1223 return subset & ps
1224
1224
1225 def parentspec(repo, subset, x, n):
1225 def parentspec(repo, subset, x, n):
1226 """``set^0``
1226 """``set^0``
1227 The set.
1227 The set.
1228 ``set^1`` (or ``set^``), ``set^2``
1228 ``set^1`` (or ``set^``), ``set^2``
1229 First or second parent, respectively, of all changesets in set.
1229 First or second parent, respectively, of all changesets in set.
1230 """
1230 """
1231 try:
1231 try:
1232 n = int(n[1])
1232 n = int(n[1])
1233 if n not in (0, 1, 2):
1233 if n not in (0, 1, 2):
1234 raise ValueError
1234 raise ValueError
1235 except (TypeError, ValueError):
1235 except (TypeError, ValueError):
1236 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1236 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1237 ps = set()
1237 ps = set()
1238 cl = repo.changelog
1238 cl = repo.changelog
1239 for r in getset(repo, baseset(cl), x):
1239 for r in getset(repo, baseset(cl), x):
1240 if n == 0:
1240 if n == 0:
1241 ps.add(r)
1241 ps.add(r)
1242 elif n == 1:
1242 elif n == 1:
1243 ps.add(cl.parentrevs(r)[0])
1243 ps.add(cl.parentrevs(r)[0])
1244 elif n == 2:
1244 elif n == 2:
1245 parents = cl.parentrevs(r)
1245 parents = cl.parentrevs(r)
1246 if len(parents) > 1:
1246 if len(parents) > 1:
1247 ps.add(parents[1])
1247 ps.add(parents[1])
1248 return subset & ps
1248 return subset & ps
1249
1249
1250 def present(repo, subset, x):
1250 def present(repo, subset, x):
1251 """``present(set)``
1251 """``present(set)``
1252 An empty set, if any revision in set isn't found; otherwise,
1252 An empty set, if any revision in set isn't found; otherwise,
1253 all revisions in set.
1253 all revisions in set.
1254
1254
1255 If any of specified revisions is not present in the local repository,
1255 If any of specified revisions is not present in the local repository,
1256 the query is normally aborted. But this predicate allows the query
1256 the query is normally aborted. But this predicate allows the query
1257 to continue even in such cases.
1257 to continue even in such cases.
1258 """
1258 """
1259 try:
1259 try:
1260 return getset(repo, subset, x)
1260 return getset(repo, subset, x)
1261 except error.RepoLookupError:
1261 except error.RepoLookupError:
1262 return baseset([])
1262 return baseset([])
1263
1263
1264 def public(repo, subset, x):
1264 def public(repo, subset, x):
1265 """``public()``
1265 """``public()``
1266 Changeset in public phase."""
1266 Changeset in public phase."""
1267 # i18n: "public" is a keyword
1267 # i18n: "public" is a keyword
1268 getargs(x, 0, 0, _("public takes no arguments"))
1268 getargs(x, 0, 0, _("public takes no arguments"))
1269 pc = repo._phasecache
1269 pc = repo._phasecache
1270 return subset.filter(lambda r: pc.phase(repo, r) == phases.public)
1270 return subset.filter(lambda r: pc.phase(repo, r) == phases.public)
1271
1271
1272 def remote(repo, subset, x):
1272 def remote(repo, subset, x):
1273 """``remote([id [,path]])``
1273 """``remote([id [,path]])``
1274 Local revision that corresponds to the given identifier in a
1274 Local revision that corresponds to the given identifier in a
1275 remote repository, if present. Here, the '.' identifier is a
1275 remote repository, if present. Here, the '.' identifier is a
1276 synonym for the current local branch.
1276 synonym for the current local branch.
1277 """
1277 """
1278
1278
1279 import hg # avoid start-up nasties
1279 import hg # avoid start-up nasties
1280 # i18n: "remote" is a keyword
1280 # i18n: "remote" is a keyword
1281 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1281 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1282
1282
1283 q = '.'
1283 q = '.'
1284 if len(l) > 0:
1284 if len(l) > 0:
1285 # i18n: "remote" is a keyword
1285 # i18n: "remote" is a keyword
1286 q = getstring(l[0], _("remote requires a string id"))
1286 q = getstring(l[0], _("remote requires a string id"))
1287 if q == '.':
1287 if q == '.':
1288 q = repo['.'].branch()
1288 q = repo['.'].branch()
1289
1289
1290 dest = ''
1290 dest = ''
1291 if len(l) > 1:
1291 if len(l) > 1:
1292 # i18n: "remote" is a keyword
1292 # i18n: "remote" is a keyword
1293 dest = getstring(l[1], _("remote requires a repository path"))
1293 dest = getstring(l[1], _("remote requires a repository path"))
1294 dest = repo.ui.expandpath(dest or 'default')
1294 dest = repo.ui.expandpath(dest or 'default')
1295 dest, branches = hg.parseurl(dest)
1295 dest, branches = hg.parseurl(dest)
1296 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1296 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1297 if revs:
1297 if revs:
1298 revs = [repo.lookup(rev) for rev in revs]
1298 revs = [repo.lookup(rev) for rev in revs]
1299 other = hg.peer(repo, {}, dest)
1299 other = hg.peer(repo, {}, dest)
1300 n = other.lookup(q)
1300 n = other.lookup(q)
1301 if n in repo:
1301 if n in repo:
1302 r = repo[n].rev()
1302 r = repo[n].rev()
1303 if r in subset:
1303 if r in subset:
1304 return baseset([r])
1304 return baseset([r])
1305 return baseset([])
1305 return baseset([])
1306
1306
1307 def removes(repo, subset, x):
1307 def removes(repo, subset, x):
1308 """``removes(pattern)``
1308 """``removes(pattern)``
1309 Changesets which remove files matching pattern.
1309 Changesets which remove files matching pattern.
1310
1310
1311 The pattern without explicit kind like ``glob:`` is expected to be
1311 The pattern without explicit kind like ``glob:`` is expected to be
1312 relative to the current directory and match against a file or a
1312 relative to the current directory and match against a file or a
1313 directory.
1313 directory.
1314 """
1314 """
1315 # i18n: "removes" is a keyword
1315 # i18n: "removes" is a keyword
1316 pat = getstring(x, _("removes requires a pattern"))
1316 pat = getstring(x, _("removes requires a pattern"))
1317 return checkstatus(repo, subset, pat, 2)
1317 return checkstatus(repo, subset, pat, 2)
1318
1318
1319 def rev(repo, subset, x):
1319 def rev(repo, subset, x):
1320 """``rev(number)``
1320 """``rev(number)``
1321 Revision with the given numeric identifier.
1321 Revision with the given numeric identifier.
1322 """
1322 """
1323 # i18n: "rev" is a keyword
1323 # i18n: "rev" is a keyword
1324 l = getargs(x, 1, 1, _("rev requires one argument"))
1324 l = getargs(x, 1, 1, _("rev requires one argument"))
1325 try:
1325 try:
1326 # i18n: "rev" is a keyword
1326 # i18n: "rev" is a keyword
1327 l = int(getstring(l[0], _("rev requires a number")))
1327 l = int(getstring(l[0], _("rev requires a number")))
1328 except (TypeError, ValueError):
1328 except (TypeError, ValueError):
1329 # i18n: "rev" is a keyword
1329 # i18n: "rev" is a keyword
1330 raise error.ParseError(_("rev expects a number"))
1330 raise error.ParseError(_("rev expects a number"))
1331 return subset.filter(lambda r: r == l)
1331 return subset.filter(lambda r: r == l)
1332
1332
1333 def matching(repo, subset, x):
1333 def matching(repo, subset, x):
1334 """``matching(revision [, field])``
1334 """``matching(revision [, field])``
1335 Changesets in which a given set of fields match the set of fields in the
1335 Changesets in which a given set of fields match the set of fields in the
1336 selected revision or set.
1336 selected revision or set.
1337
1337
1338 To match more than one field pass the list of fields to match separated
1338 To match more than one field pass the list of fields to match separated
1339 by spaces (e.g. ``author description``).
1339 by spaces (e.g. ``author description``).
1340
1340
1341 Valid fields are most regular revision fields and some special fields.
1341 Valid fields are most regular revision fields and some special fields.
1342
1342
1343 Regular revision fields are ``description``, ``author``, ``branch``,
1343 Regular revision fields are ``description``, ``author``, ``branch``,
1344 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1344 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1345 and ``diff``.
1345 and ``diff``.
1346 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1346 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1347 contents of the revision. Two revisions matching their ``diff`` will
1347 contents of the revision. Two revisions matching their ``diff`` will
1348 also match their ``files``.
1348 also match their ``files``.
1349
1349
1350 Special fields are ``summary`` and ``metadata``:
1350 Special fields are ``summary`` and ``metadata``:
1351 ``summary`` matches the first line of the description.
1351 ``summary`` matches the first line of the description.
1352 ``metadata`` is equivalent to matching ``description user date``
1352 ``metadata`` is equivalent to matching ``description user date``
1353 (i.e. it matches the main metadata fields).
1353 (i.e. it matches the main metadata fields).
1354
1354
1355 ``metadata`` is the default field which is used when no fields are
1355 ``metadata`` is the default field which is used when no fields are
1356 specified. You can match more than one field at a time.
1356 specified. You can match more than one field at a time.
1357 """
1357 """
1358 # i18n: "matching" is a keyword
1358 # i18n: "matching" is a keyword
1359 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1359 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1360
1360
1361 revs = getset(repo, baseset(repo.changelog), l[0])
1361 revs = getset(repo, baseset(repo.changelog), l[0])
1362
1362
1363 fieldlist = ['metadata']
1363 fieldlist = ['metadata']
1364 if len(l) > 1:
1364 if len(l) > 1:
1365 fieldlist = getstring(l[1],
1365 fieldlist = getstring(l[1],
1366 # i18n: "matching" is a keyword
1366 # i18n: "matching" is a keyword
1367 _("matching requires a string "
1367 _("matching requires a string "
1368 "as its second argument")).split()
1368 "as its second argument")).split()
1369
1369
1370 # Make sure that there are no repeated fields,
1370 # Make sure that there are no repeated fields,
1371 # expand the 'special' 'metadata' field type
1371 # expand the 'special' 'metadata' field type
1372 # and check the 'files' whenever we check the 'diff'
1372 # and check the 'files' whenever we check the 'diff'
1373 fields = []
1373 fields = []
1374 for field in fieldlist:
1374 for field in fieldlist:
1375 if field == 'metadata':
1375 if field == 'metadata':
1376 fields += ['user', 'description', 'date']
1376 fields += ['user', 'description', 'date']
1377 elif field == 'diff':
1377 elif field == 'diff':
1378 # a revision matching the diff must also match the files
1378 # a revision matching the diff must also match the files
1379 # since matching the diff is very costly, make sure to
1379 # since matching the diff is very costly, make sure to
1380 # also match the files first
1380 # also match the files first
1381 fields += ['files', 'diff']
1381 fields += ['files', 'diff']
1382 else:
1382 else:
1383 if field == 'author':
1383 if field == 'author':
1384 field = 'user'
1384 field = 'user'
1385 fields.append(field)
1385 fields.append(field)
1386 fields = set(fields)
1386 fields = set(fields)
1387 if 'summary' in fields and 'description' in fields:
1387 if 'summary' in fields and 'description' in fields:
1388 # If a revision matches its description it also matches its summary
1388 # If a revision matches its description it also matches its summary
1389 fields.discard('summary')
1389 fields.discard('summary')
1390
1390
1391 # We may want to match more than one field
1391 # We may want to match more than one field
1392 # Not all fields take the same amount of time to be matched
1392 # Not all fields take the same amount of time to be matched
1393 # Sort the selected fields in order of increasing matching cost
1393 # Sort the selected fields in order of increasing matching cost
1394 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1394 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1395 'files', 'description', 'substate', 'diff']
1395 'files', 'description', 'substate', 'diff']
1396 def fieldkeyfunc(f):
1396 def fieldkeyfunc(f):
1397 try:
1397 try:
1398 return fieldorder.index(f)
1398 return fieldorder.index(f)
1399 except ValueError:
1399 except ValueError:
1400 # assume an unknown field is very costly
1400 # assume an unknown field is very costly
1401 return len(fieldorder)
1401 return len(fieldorder)
1402 fields = list(fields)
1402 fields = list(fields)
1403 fields.sort(key=fieldkeyfunc)
1403 fields.sort(key=fieldkeyfunc)
1404
1404
1405 # Each field will be matched with its own "getfield" function
1405 # Each field will be matched with its own "getfield" function
1406 # which will be added to the getfieldfuncs array of functions
1406 # which will be added to the getfieldfuncs array of functions
1407 getfieldfuncs = []
1407 getfieldfuncs = []
1408 _funcs = {
1408 _funcs = {
1409 'user': lambda r: repo[r].user(),
1409 'user': lambda r: repo[r].user(),
1410 'branch': lambda r: repo[r].branch(),
1410 'branch': lambda r: repo[r].branch(),
1411 'date': lambda r: repo[r].date(),
1411 'date': lambda r: repo[r].date(),
1412 'description': lambda r: repo[r].description(),
1412 'description': lambda r: repo[r].description(),
1413 'files': lambda r: repo[r].files(),
1413 'files': lambda r: repo[r].files(),
1414 'parents': lambda r: repo[r].parents(),
1414 'parents': lambda r: repo[r].parents(),
1415 'phase': lambda r: repo[r].phase(),
1415 'phase': lambda r: repo[r].phase(),
1416 'substate': lambda r: repo[r].substate,
1416 'substate': lambda r: repo[r].substate,
1417 'summary': lambda r: repo[r].description().splitlines()[0],
1417 'summary': lambda r: repo[r].description().splitlines()[0],
1418 'diff': lambda r: list(repo[r].diff(git=True),)
1418 'diff': lambda r: list(repo[r].diff(git=True),)
1419 }
1419 }
1420 for info in fields:
1420 for info in fields:
1421 getfield = _funcs.get(info, None)
1421 getfield = _funcs.get(info, None)
1422 if getfield is None:
1422 if getfield is None:
1423 raise error.ParseError(
1423 raise error.ParseError(
1424 # i18n: "matching" is a keyword
1424 # i18n: "matching" is a keyword
1425 _("unexpected field name passed to matching: %s") % info)
1425 _("unexpected field name passed to matching: %s") % info)
1426 getfieldfuncs.append(getfield)
1426 getfieldfuncs.append(getfield)
1427 # convert the getfield array of functions into a "getinfo" function
1427 # convert the getfield array of functions into a "getinfo" function
1428 # which returns an array of field values (or a single value if there
1428 # which returns an array of field values (or a single value if there
1429 # is only one field to match)
1429 # is only one field to match)
1430 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1430 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1431
1431
1432 def matches(x):
1432 def matches(x):
1433 for rev in revs:
1433 for rev in revs:
1434 target = getinfo(rev)
1434 target = getinfo(rev)
1435 match = True
1435 match = True
1436 for n, f in enumerate(getfieldfuncs):
1436 for n, f in enumerate(getfieldfuncs):
1437 if target[n] != f(x):
1437 if target[n] != f(x):
1438 match = False
1438 match = False
1439 if match:
1439 if match:
1440 return True
1440 return True
1441 return False
1441 return False
1442
1442
1443 return subset.filter(matches)
1443 return subset.filter(matches)
1444
1444
1445 def reverse(repo, subset, x):
1445 def reverse(repo, subset, x):
1446 """``reverse(set)``
1446 """``reverse(set)``
1447 Reverse order of set.
1447 Reverse order of set.
1448 """
1448 """
1449 l = getset(repo, subset, x)
1449 l = getset(repo, subset, x)
1450 l.reverse()
1450 l.reverse()
1451 return l
1451 return l
1452
1452
1453 def roots(repo, subset, x):
1453 def roots(repo, subset, x):
1454 """``roots(set)``
1454 """``roots(set)``
1455 Changesets in set with no parent changeset in set.
1455 Changesets in set with no parent changeset in set.
1456 """
1456 """
1457 s = getset(repo, baseset(repo.changelog), x).set()
1457 s = getset(repo, baseset(repo.changelog), x).set()
1458 subset = baseset([r for r in subset if r in s])
1458 subset = baseset([r for r in subset if r in s])
1459 cs = _children(repo, subset, s)
1459 cs = _children(repo, subset, s)
1460 return subset - cs
1460 return subset - cs
1461
1461
1462 def secret(repo, subset, x):
1462 def secret(repo, subset, x):
1463 """``secret()``
1463 """``secret()``
1464 Changeset in secret phase."""
1464 Changeset in secret phase."""
1465 # i18n: "secret" is a keyword
1465 # i18n: "secret" is a keyword
1466 getargs(x, 0, 0, _("secret takes no arguments"))
1466 getargs(x, 0, 0, _("secret takes no arguments"))
1467 pc = repo._phasecache
1467 pc = repo._phasecache
1468 return subset.filter(lambda x: pc.phase(repo, x) == phases.secret)
1468 return subset.filter(lambda x: pc.phase(repo, x) == phases.secret)
1469
1469
1470 def sort(repo, subset, x):
1470 def sort(repo, subset, x):
1471 """``sort(set[, [-]key...])``
1471 """``sort(set[, [-]key...])``
1472 Sort set by keys. The default sort order is ascending, specify a key
1472 Sort set by keys. The default sort order is ascending, specify a key
1473 as ``-key`` to sort in descending order.
1473 as ``-key`` to sort in descending order.
1474
1474
1475 The keys can be:
1475 The keys can be:
1476
1476
1477 - ``rev`` for the revision number,
1477 - ``rev`` for the revision number,
1478 - ``branch`` for the branch name,
1478 - ``branch`` for the branch name,
1479 - ``desc`` for the commit message (description),
1479 - ``desc`` for the commit message (description),
1480 - ``user`` for user name (``author`` can be used as an alias),
1480 - ``user`` for user name (``author`` can be used as an alias),
1481 - ``date`` for the commit date
1481 - ``date`` for the commit date
1482 """
1482 """
1483 # i18n: "sort" is a keyword
1483 # i18n: "sort" is a keyword
1484 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1484 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1485 keys = "rev"
1485 keys = "rev"
1486 if len(l) == 2:
1486 if len(l) == 2:
1487 # i18n: "sort" is a keyword
1487 # i18n: "sort" is a keyword
1488 keys = getstring(l[1], _("sort spec must be a string"))
1488 keys = getstring(l[1], _("sort spec must be a string"))
1489
1489
1490 s = l[0]
1490 s = l[0]
1491 keys = keys.split()
1491 keys = keys.split()
1492 l = []
1492 l = []
1493 def invert(s):
1493 def invert(s):
1494 return "".join(chr(255 - ord(c)) for c in s)
1494 return "".join(chr(255 - ord(c)) for c in s)
1495 revs = getset(repo, subset, s)
1495 revs = getset(repo, subset, s)
1496 if keys == ["rev"]:
1496 if keys == ["rev"]:
1497 revs.sort()
1497 revs.sort()
1498 return revs
1498 return revs
1499 elif keys == ["-rev"]:
1499 elif keys == ["-rev"]:
1500 revs.sort(reverse=True)
1500 revs.sort(reverse=True)
1501 return revs
1501 return revs
1502 for r in revs:
1502 for r in revs:
1503 c = repo[r]
1503 c = repo[r]
1504 e = []
1504 e = []
1505 for k in keys:
1505 for k in keys:
1506 if k == 'rev':
1506 if k == 'rev':
1507 e.append(r)
1507 e.append(r)
1508 elif k == '-rev':
1508 elif k == '-rev':
1509 e.append(-r)
1509 e.append(-r)
1510 elif k == 'branch':
1510 elif k == 'branch':
1511 e.append(c.branch())
1511 e.append(c.branch())
1512 elif k == '-branch':
1512 elif k == '-branch':
1513 e.append(invert(c.branch()))
1513 e.append(invert(c.branch()))
1514 elif k == 'desc':
1514 elif k == 'desc':
1515 e.append(c.description())
1515 e.append(c.description())
1516 elif k == '-desc':
1516 elif k == '-desc':
1517 e.append(invert(c.description()))
1517 e.append(invert(c.description()))
1518 elif k in 'user author':
1518 elif k in 'user author':
1519 e.append(c.user())
1519 e.append(c.user())
1520 elif k in '-user -author':
1520 elif k in '-user -author':
1521 e.append(invert(c.user()))
1521 e.append(invert(c.user()))
1522 elif k == 'date':
1522 elif k == 'date':
1523 e.append(c.date()[0])
1523 e.append(c.date()[0])
1524 elif k == '-date':
1524 elif k == '-date':
1525 e.append(-c.date()[0])
1525 e.append(-c.date()[0])
1526 else:
1526 else:
1527 raise error.ParseError(_("unknown sort key %r") % k)
1527 raise error.ParseError(_("unknown sort key %r") % k)
1528 e.append(r)
1528 e.append(r)
1529 l.append(e)
1529 l.append(e)
1530 l.sort()
1530 l.sort()
1531 return baseset([e[-1] for e in l])
1531 return baseset([e[-1] for e in l])
1532
1532
1533 def _stringmatcher(pattern):
1533 def _stringmatcher(pattern):
1534 """
1534 """
1535 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1535 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1536 returns the matcher name, pattern, and matcher function.
1536 returns the matcher name, pattern, and matcher function.
1537 missing or unknown prefixes are treated as literal matches.
1537 missing or unknown prefixes are treated as literal matches.
1538
1538
1539 helper for tests:
1539 helper for tests:
1540 >>> def test(pattern, *tests):
1540 >>> def test(pattern, *tests):
1541 ... kind, pattern, matcher = _stringmatcher(pattern)
1541 ... kind, pattern, matcher = _stringmatcher(pattern)
1542 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1542 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1543
1543
1544 exact matching (no prefix):
1544 exact matching (no prefix):
1545 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1545 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1546 ('literal', 'abcdefg', [False, False, True])
1546 ('literal', 'abcdefg', [False, False, True])
1547
1547
1548 regex matching ('re:' prefix)
1548 regex matching ('re:' prefix)
1549 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1549 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1550 ('re', 'a.+b', [False, False, True])
1550 ('re', 'a.+b', [False, False, True])
1551
1551
1552 force exact matches ('literal:' prefix)
1552 force exact matches ('literal:' prefix)
1553 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1553 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1554 ('literal', 're:foobar', [False, True])
1554 ('literal', 're:foobar', [False, True])
1555
1555
1556 unknown prefixes are ignored and treated as literals
1556 unknown prefixes are ignored and treated as literals
1557 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1557 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1558 ('literal', 'foo:bar', [False, False, True])
1558 ('literal', 'foo:bar', [False, False, True])
1559 """
1559 """
1560 if pattern.startswith('re:'):
1560 if pattern.startswith('re:'):
1561 pattern = pattern[3:]
1561 pattern = pattern[3:]
1562 try:
1562 try:
1563 regex = re.compile(pattern)
1563 regex = re.compile(pattern)
1564 except re.error, e:
1564 except re.error, e:
1565 raise error.ParseError(_('invalid regular expression: %s')
1565 raise error.ParseError(_('invalid regular expression: %s')
1566 % e)
1566 % e)
1567 return 're', pattern, regex.search
1567 return 're', pattern, regex.search
1568 elif pattern.startswith('literal:'):
1568 elif pattern.startswith('literal:'):
1569 pattern = pattern[8:]
1569 pattern = pattern[8:]
1570 return 'literal', pattern, pattern.__eq__
1570 return 'literal', pattern, pattern.__eq__
1571
1571
1572 def _substringmatcher(pattern):
1572 def _substringmatcher(pattern):
1573 kind, pattern, matcher = _stringmatcher(pattern)
1573 kind, pattern, matcher = _stringmatcher(pattern)
1574 if kind == 'literal':
1574 if kind == 'literal':
1575 matcher = lambda s: pattern in s
1575 matcher = lambda s: pattern in s
1576 return kind, pattern, matcher
1576 return kind, pattern, matcher
1577
1577
1578 def tag(repo, subset, x):
1578 def tag(repo, subset, x):
1579 """``tag([name])``
1579 """``tag([name])``
1580 The specified tag by name, or all tagged revisions if no name is given.
1580 The specified tag by name, or all tagged revisions if no name is given.
1581 """
1581 """
1582 # i18n: "tag" is a keyword
1582 # i18n: "tag" is a keyword
1583 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1583 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1584 cl = repo.changelog
1584 cl = repo.changelog
1585 if args:
1585 if args:
1586 pattern = getstring(args[0],
1586 pattern = getstring(args[0],
1587 # i18n: "tag" is a keyword
1587 # i18n: "tag" is a keyword
1588 _('the argument to tag must be a string'))
1588 _('the argument to tag must be a string'))
1589 kind, pattern, matcher = _stringmatcher(pattern)
1589 kind, pattern, matcher = _stringmatcher(pattern)
1590 if kind == 'literal':
1590 if kind == 'literal':
1591 # avoid resolving all tags
1591 # avoid resolving all tags
1592 tn = repo._tagscache.tags.get(pattern, None)
1592 tn = repo._tagscache.tags.get(pattern, None)
1593 if tn is None:
1593 if tn is None:
1594 raise util.Abort(_("tag '%s' does not exist") % pattern)
1594 raise util.Abort(_("tag '%s' does not exist") % pattern)
1595 s = set([repo[tn].rev()])
1595 s = set([repo[tn].rev()])
1596 else:
1596 else:
1597 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1597 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1598 else:
1598 else:
1599 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1599 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1600 return subset & s
1600 return subset & s
1601
1601
1602 def tagged(repo, subset, x):
1602 def tagged(repo, subset, x):
1603 return tag(repo, subset, x)
1603 return tag(repo, subset, x)
1604
1604
1605 def unstable(repo, subset, x):
1605 def unstable(repo, subset, x):
1606 """``unstable()``
1606 """``unstable()``
1607 Non-obsolete changesets with obsolete ancestors.
1607 Non-obsolete changesets with obsolete ancestors.
1608 """
1608 """
1609 # i18n: "unstable" is a keyword
1609 # i18n: "unstable" is a keyword
1610 getargs(x, 0, 0, _("unstable takes no arguments"))
1610 getargs(x, 0, 0, _("unstable takes no arguments"))
1611 unstables = obsmod.getrevs(repo, 'unstable')
1611 unstables = obsmod.getrevs(repo, 'unstable')
1612 return subset & unstables
1612 return subset & unstables
1613
1613
1614
1614
1615 def user(repo, subset, x):
1615 def user(repo, subset, x):
1616 """``user(string)``
1616 """``user(string)``
1617 User name contains string. The match is case-insensitive.
1617 User name contains string. The match is case-insensitive.
1618
1618
1619 If `string` starts with `re:`, the remainder of the string is treated as
1619 If `string` starts with `re:`, the remainder of the string is treated as
1620 a regular expression. To match a user that actually contains `re:`, use
1620 a regular expression. To match a user that actually contains `re:`, use
1621 the prefix `literal:`.
1621 the prefix `literal:`.
1622 """
1622 """
1623 return author(repo, subset, x)
1623 return author(repo, subset, x)
1624
1624
1625 # for internal use
1625 # for internal use
1626 def _list(repo, subset, x):
1626 def _list(repo, subset, x):
1627 s = getstring(x, "internal error")
1627 s = getstring(x, "internal error")
1628 if not s:
1628 if not s:
1629 return baseset([])
1629 return baseset([])
1630 ls = [repo[r].rev() for r in s.split('\0')]
1630 ls = [repo[r].rev() for r in s.split('\0')]
1631 s = subset.set()
1631 s = subset.set()
1632 return baseset([r for r in ls if r in s])
1632 return baseset([r for r in ls if r in s])
1633
1633
1634 # for internal use
1634 # for internal use
1635 def _intlist(repo, subset, x):
1635 def _intlist(repo, subset, x):
1636 s = getstring(x, "internal error")
1636 s = getstring(x, "internal error")
1637 if not s:
1637 if not s:
1638 return baseset([])
1638 return baseset([])
1639 ls = [int(r) for r in s.split('\0')]
1639 ls = [int(r) for r in s.split('\0')]
1640 s = subset.set()
1640 s = subset.set()
1641 return baseset([r for r in ls if r in s])
1641 return baseset([r for r in ls if r in s])
1642
1642
1643 # for internal use
1643 # for internal use
1644 def _hexlist(repo, subset, x):
1644 def _hexlist(repo, subset, x):
1645 s = getstring(x, "internal error")
1645 s = getstring(x, "internal error")
1646 if not s:
1646 if not s:
1647 return baseset([])
1647 return baseset([])
1648 cl = repo.changelog
1648 cl = repo.changelog
1649 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
1649 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
1650 s = subset.set()
1650 s = subset.set()
1651 return baseset([r for r in ls if r in s])
1651 return baseset([r for r in ls if r in s])
1652
1652
1653 symbols = {
1653 symbols = {
1654 "adds": adds,
1654 "adds": adds,
1655 "all": getall,
1655 "all": getall,
1656 "ancestor": ancestor,
1656 "ancestor": ancestor,
1657 "ancestors": ancestors,
1657 "ancestors": ancestors,
1658 "_firstancestors": _firstancestors,
1658 "_firstancestors": _firstancestors,
1659 "author": author,
1659 "author": author,
1660 "only": only,
1660 "only": only,
1661 "bisect": bisect,
1661 "bisect": bisect,
1662 "bisected": bisected,
1662 "bisected": bisected,
1663 "bookmark": bookmark,
1663 "bookmark": bookmark,
1664 "branch": branch,
1664 "branch": branch,
1665 "branchpoint": branchpoint,
1665 "branchpoint": branchpoint,
1666 "bumped": bumped,
1666 "bumped": bumped,
1667 "bundle": bundle,
1667 "bundle": bundle,
1668 "children": children,
1668 "children": children,
1669 "closed": closed,
1669 "closed": closed,
1670 "contains": contains,
1670 "contains": contains,
1671 "converted": converted,
1671 "converted": converted,
1672 "date": date,
1672 "date": date,
1673 "desc": desc,
1673 "desc": desc,
1674 "descendants": descendants,
1674 "descendants": descendants,
1675 "_firstdescendants": _firstdescendants,
1675 "_firstdescendants": _firstdescendants,
1676 "destination": destination,
1676 "destination": destination,
1677 "divergent": divergent,
1677 "divergent": divergent,
1678 "draft": draft,
1678 "draft": draft,
1679 "extinct": extinct,
1679 "extinct": extinct,
1680 "extra": extra,
1680 "extra": extra,
1681 "file": hasfile,
1681 "file": hasfile,
1682 "filelog": filelog,
1682 "filelog": filelog,
1683 "first": first,
1683 "first": first,
1684 "follow": follow,
1684 "follow": follow,
1685 "_followfirst": _followfirst,
1685 "_followfirst": _followfirst,
1686 "grep": grep,
1686 "grep": grep,
1687 "head": head,
1687 "head": head,
1688 "heads": heads,
1688 "heads": heads,
1689 "hidden": hidden,
1689 "hidden": hidden,
1690 "id": node_,
1690 "id": node_,
1691 "keyword": keyword,
1691 "keyword": keyword,
1692 "last": last,
1692 "last": last,
1693 "limit": limit,
1693 "limit": limit,
1694 "_matchfiles": _matchfiles,
1694 "_matchfiles": _matchfiles,
1695 "max": maxrev,
1695 "max": maxrev,
1696 "merge": merge,
1696 "merge": merge,
1697 "min": minrev,
1697 "min": minrev,
1698 "_missingancestors": _missingancestors,
1698 "_missingancestors": _missingancestors,
1699 "modifies": modifies,
1699 "modifies": modifies,
1700 "obsolete": obsolete,
1700 "obsolete": obsolete,
1701 "origin": origin,
1701 "origin": origin,
1702 "outgoing": outgoing,
1702 "outgoing": outgoing,
1703 "p1": p1,
1703 "p1": p1,
1704 "p2": p2,
1704 "p2": p2,
1705 "parents": parents,
1705 "parents": parents,
1706 "present": present,
1706 "present": present,
1707 "public": public,
1707 "public": public,
1708 "remote": remote,
1708 "remote": remote,
1709 "removes": removes,
1709 "removes": removes,
1710 "rev": rev,
1710 "rev": rev,
1711 "reverse": reverse,
1711 "reverse": reverse,
1712 "roots": roots,
1712 "roots": roots,
1713 "sort": sort,
1713 "sort": sort,
1714 "secret": secret,
1714 "secret": secret,
1715 "matching": matching,
1715 "matching": matching,
1716 "tag": tag,
1716 "tag": tag,
1717 "tagged": tagged,
1717 "tagged": tagged,
1718 "user": user,
1718 "user": user,
1719 "unstable": unstable,
1719 "unstable": unstable,
1720 "_list": _list,
1720 "_list": _list,
1721 "_intlist": _intlist,
1721 "_intlist": _intlist,
1722 "_hexlist": _hexlist,
1722 "_hexlist": _hexlist,
1723 }
1723 }
1724
1724
1725 # symbols which can't be used for a DoS attack for any given input
1725 # symbols which can't be used for a DoS attack for any given input
1726 # (e.g. those which accept regexes as plain strings shouldn't be included)
1726 # (e.g. those which accept regexes as plain strings shouldn't be included)
1727 # functions that just return a lot of changesets (like all) don't count here
1727 # functions that just return a lot of changesets (like all) don't count here
1728 safesymbols = set([
1728 safesymbols = set([
1729 "adds",
1729 "adds",
1730 "all",
1730 "all",
1731 "ancestor",
1731 "ancestor",
1732 "ancestors",
1732 "ancestors",
1733 "_firstancestors",
1733 "_firstancestors",
1734 "author",
1734 "author",
1735 "bisect",
1735 "bisect",
1736 "bisected",
1736 "bisected",
1737 "bookmark",
1737 "bookmark",
1738 "branch",
1738 "branch",
1739 "branchpoint",
1739 "branchpoint",
1740 "bumped",
1740 "bumped",
1741 "bundle",
1741 "bundle",
1742 "children",
1742 "children",
1743 "closed",
1743 "closed",
1744 "converted",
1744 "converted",
1745 "date",
1745 "date",
1746 "desc",
1746 "desc",
1747 "descendants",
1747 "descendants",
1748 "_firstdescendants",
1748 "_firstdescendants",
1749 "destination",
1749 "destination",
1750 "divergent",
1750 "divergent",
1751 "draft",
1751 "draft",
1752 "extinct",
1752 "extinct",
1753 "extra",
1753 "extra",
1754 "file",
1754 "file",
1755 "filelog",
1755 "filelog",
1756 "first",
1756 "first",
1757 "follow",
1757 "follow",
1758 "_followfirst",
1758 "_followfirst",
1759 "head",
1759 "head",
1760 "heads",
1760 "heads",
1761 "hidden",
1761 "hidden",
1762 "id",
1762 "id",
1763 "keyword",
1763 "keyword",
1764 "last",
1764 "last",
1765 "limit",
1765 "limit",
1766 "_matchfiles",
1766 "_matchfiles",
1767 "max",
1767 "max",
1768 "merge",
1768 "merge",
1769 "min",
1769 "min",
1770 "_missingancestors",
1770 "_missingancestors",
1771 "modifies",
1771 "modifies",
1772 "obsolete",
1772 "obsolete",
1773 "origin",
1773 "origin",
1774 "outgoing",
1774 "outgoing",
1775 "p1",
1775 "p1",
1776 "p2",
1776 "p2",
1777 "parents",
1777 "parents",
1778 "present",
1778 "present",
1779 "public",
1779 "public",
1780 "remote",
1780 "remote",
1781 "removes",
1781 "removes",
1782 "rev",
1782 "rev",
1783 "reverse",
1783 "reverse",
1784 "roots",
1784 "roots",
1785 "sort",
1785 "sort",
1786 "secret",
1786 "secret",
1787 "matching",
1787 "matching",
1788 "tag",
1788 "tag",
1789 "tagged",
1789 "tagged",
1790 "user",
1790 "user",
1791 "unstable",
1791 "unstable",
1792 "_list",
1792 "_list",
1793 "_intlist",
1793 "_intlist",
1794 "_hexlist",
1794 "_hexlist",
1795 ])
1795 ])
1796
1796
1797 methods = {
1797 methods = {
1798 "range": rangeset,
1798 "range": rangeset,
1799 "dagrange": dagrange,
1799 "dagrange": dagrange,
1800 "string": stringset,
1800 "string": stringset,
1801 "symbol": symbolset,
1801 "symbol": symbolset,
1802 "and": andset,
1802 "and": andset,
1803 "or": orset,
1803 "or": orset,
1804 "not": notset,
1804 "not": notset,
1805 "list": listset,
1805 "list": listset,
1806 "func": func,
1806 "func": func,
1807 "ancestor": ancestorspec,
1807 "ancestor": ancestorspec,
1808 "parent": parentspec,
1808 "parent": parentspec,
1809 "parentpost": p1,
1809 "parentpost": p1,
1810 }
1810 }
1811
1811
1812 def optimize(x, small):
1812 def optimize(x, small):
1813 if x is None:
1813 if x is None:
1814 return 0, x
1814 return 0, x
1815
1815
1816 smallbonus = 1
1816 smallbonus = 1
1817 if small:
1817 if small:
1818 smallbonus = .5
1818 smallbonus = .5
1819
1819
1820 op = x[0]
1820 op = x[0]
1821 if op == 'minus':
1821 if op == 'minus':
1822 return optimize(('and', x[1], ('not', x[2])), small)
1822 return optimize(('and', x[1], ('not', x[2])), small)
1823 elif op == 'dagrangepre':
1823 elif op == 'dagrangepre':
1824 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
1824 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
1825 elif op == 'dagrangepost':
1825 elif op == 'dagrangepost':
1826 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
1826 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
1827 elif op == 'rangepre':
1827 elif op == 'rangepre':
1828 return optimize(('range', ('string', '0'), x[1]), small)
1828 return optimize(('range', ('string', '0'), x[1]), small)
1829 elif op == 'rangepost':
1829 elif op == 'rangepost':
1830 return optimize(('range', x[1], ('string', 'tip')), small)
1830 return optimize(('range', x[1], ('string', 'tip')), small)
1831 elif op == 'negate':
1831 elif op == 'negate':
1832 return optimize(('string',
1832 return optimize(('string',
1833 '-' + getstring(x[1], _("can't negate that"))), small)
1833 '-' + getstring(x[1], _("can't negate that"))), small)
1834 elif op in 'string symbol negate':
1834 elif op in 'string symbol negate':
1835 return smallbonus, x # single revisions are small
1835 return smallbonus, x # single revisions are small
1836 elif op == 'and':
1836 elif op == 'and':
1837 wa, ta = optimize(x[1], True)
1837 wa, ta = optimize(x[1], True)
1838 wb, tb = optimize(x[2], True)
1838 wb, tb = optimize(x[2], True)
1839
1839
1840 # (::x and not ::y)/(not ::y and ::x) have a fast path
1840 # (::x and not ::y)/(not ::y and ::x) have a fast path
1841 def ismissingancestors(revs, bases):
1841 def ismissingancestors(revs, bases):
1842 return (
1842 return (
1843 revs[0] == 'func'
1843 revs[0] == 'func'
1844 and getstring(revs[1], _('not a symbol')) == 'ancestors'
1844 and getstring(revs[1], _('not a symbol')) == 'ancestors'
1845 and bases[0] == 'not'
1845 and bases[0] == 'not'
1846 and bases[1][0] == 'func'
1846 and bases[1][0] == 'func'
1847 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
1847 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
1848
1848
1849 w = min(wa, wb)
1849 w = min(wa, wb)
1850 if ismissingancestors(ta, tb):
1850 if ismissingancestors(ta, tb):
1851 return w, ('func', ('symbol', '_missingancestors'),
1851 return w, ('func', ('symbol', '_missingancestors'),
1852 ('list', ta[2], tb[1][2]))
1852 ('list', ta[2], tb[1][2]))
1853 if ismissingancestors(tb, ta):
1853 if ismissingancestors(tb, ta):
1854 return w, ('func', ('symbol', '_missingancestors'),
1854 return w, ('func', ('symbol', '_missingancestors'),
1855 ('list', tb[2], ta[1][2]))
1855 ('list', tb[2], ta[1][2]))
1856
1856
1857 if wa > wb:
1857 if wa > wb:
1858 return w, (op, tb, ta)
1858 return w, (op, tb, ta)
1859 return w, (op, ta, tb)
1859 return w, (op, ta, tb)
1860 elif op == 'or':
1860 elif op == 'or':
1861 wa, ta = optimize(x[1], False)
1861 wa, ta = optimize(x[1], False)
1862 wb, tb = optimize(x[2], False)
1862 wb, tb = optimize(x[2], False)
1863 if wb < wa:
1863 if wb < wa:
1864 wb, wa = wa, wb
1864 wb, wa = wa, wb
1865 return max(wa, wb), (op, ta, tb)
1865 return max(wa, wb), (op, ta, tb)
1866 elif op == 'not':
1866 elif op == 'not':
1867 o = optimize(x[1], not small)
1867 o = optimize(x[1], not small)
1868 return o[0], (op, o[1])
1868 return o[0], (op, o[1])
1869 elif op == 'parentpost':
1869 elif op == 'parentpost':
1870 o = optimize(x[1], small)
1870 o = optimize(x[1], small)
1871 return o[0], (op, o[1])
1871 return o[0], (op, o[1])
1872 elif op == 'group':
1872 elif op == 'group':
1873 return optimize(x[1], small)
1873 return optimize(x[1], small)
1874 elif op in 'dagrange range list parent ancestorspec':
1874 elif op in 'dagrange range list parent ancestorspec':
1875 if op == 'parent':
1875 if op == 'parent':
1876 # x^:y means (x^) : y, not x ^ (:y)
1876 # x^:y means (x^) : y, not x ^ (:y)
1877 post = ('parentpost', x[1])
1877 post = ('parentpost', x[1])
1878 if x[2][0] == 'dagrangepre':
1878 if x[2][0] == 'dagrangepre':
1879 return optimize(('dagrange', post, x[2][1]), small)
1879 return optimize(('dagrange', post, x[2][1]), small)
1880 elif x[2][0] == 'rangepre':
1880 elif x[2][0] == 'rangepre':
1881 return optimize(('range', post, x[2][1]), small)
1881 return optimize(('range', post, x[2][1]), small)
1882
1882
1883 wa, ta = optimize(x[1], small)
1883 wa, ta = optimize(x[1], small)
1884 wb, tb = optimize(x[2], small)
1884 wb, tb = optimize(x[2], small)
1885 return wa + wb, (op, ta, tb)
1885 return wa + wb, (op, ta, tb)
1886 elif op == 'func':
1886 elif op == 'func':
1887 f = getstring(x[1], _("not a symbol"))
1887 f = getstring(x[1], _("not a symbol"))
1888 wa, ta = optimize(x[2], small)
1888 wa, ta = optimize(x[2], small)
1889 if f in ("author branch closed date desc file grep keyword "
1889 if f in ("author branch closed date desc file grep keyword "
1890 "outgoing user"):
1890 "outgoing user"):
1891 w = 10 # slow
1891 w = 10 # slow
1892 elif f in "modifies adds removes":
1892 elif f in "modifies adds removes":
1893 w = 30 # slower
1893 w = 30 # slower
1894 elif f == "contains":
1894 elif f == "contains":
1895 w = 100 # very slow
1895 w = 100 # very slow
1896 elif f == "ancestor":
1896 elif f == "ancestor":
1897 w = 1 * smallbonus
1897 w = 1 * smallbonus
1898 elif f in "reverse limit first":
1898 elif f in "reverse limit first":
1899 w = 0
1899 w = 0
1900 elif f in "sort":
1900 elif f in "sort":
1901 w = 10 # assume most sorts look at changelog
1901 w = 10 # assume most sorts look at changelog
1902 else:
1902 else:
1903 w = 1
1903 w = 1
1904 return w + wa, (op, x[1], ta)
1904 return w + wa, (op, x[1], ta)
1905 return 1, x
1905 return 1, x
1906
1906
1907 _aliasarg = ('func', ('symbol', '_aliasarg'))
1907 _aliasarg = ('func', ('symbol', '_aliasarg'))
1908 def _getaliasarg(tree):
1908 def _getaliasarg(tree):
1909 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
1909 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
1910 return X, None otherwise.
1910 return X, None otherwise.
1911 """
1911 """
1912 if (len(tree) == 3 and tree[:2] == _aliasarg
1912 if (len(tree) == 3 and tree[:2] == _aliasarg
1913 and tree[2][0] == 'string'):
1913 and tree[2][0] == 'string'):
1914 return tree[2][1]
1914 return tree[2][1]
1915 return None
1915 return None
1916
1916
1917 def _checkaliasarg(tree, known=None):
1917 def _checkaliasarg(tree, known=None):
1918 """Check tree contains no _aliasarg construct or only ones which
1918 """Check tree contains no _aliasarg construct or only ones which
1919 value is in known. Used to avoid alias placeholders injection.
1919 value is in known. Used to avoid alias placeholders injection.
1920 """
1920 """
1921 if isinstance(tree, tuple):
1921 if isinstance(tree, tuple):
1922 arg = _getaliasarg(tree)
1922 arg = _getaliasarg(tree)
1923 if arg is not None and (not known or arg not in known):
1923 if arg is not None and (not known or arg not in known):
1924 raise error.ParseError(_("not a function: %s") % '_aliasarg')
1924 raise error.ParseError(_("not a function: %s") % '_aliasarg')
1925 for t in tree:
1925 for t in tree:
1926 _checkaliasarg(t, known)
1926 _checkaliasarg(t, known)
1927
1927
1928 class revsetalias(object):
1928 class revsetalias(object):
1929 funcre = re.compile('^([^(]+)\(([^)]+)\)$')
1929 funcre = re.compile('^([^(]+)\(([^)]+)\)$')
1930 args = None
1930 args = None
1931
1931
1932 def __init__(self, name, value):
1932 def __init__(self, name, value):
1933 '''Aliases like:
1933 '''Aliases like:
1934
1934
1935 h = heads(default)
1935 h = heads(default)
1936 b($1) = ancestors($1) - ancestors(default)
1936 b($1) = ancestors($1) - ancestors(default)
1937 '''
1937 '''
1938 m = self.funcre.search(name)
1938 m = self.funcre.search(name)
1939 if m:
1939 if m:
1940 self.name = m.group(1)
1940 self.name = m.group(1)
1941 self.tree = ('func', ('symbol', m.group(1)))
1941 self.tree = ('func', ('symbol', m.group(1)))
1942 self.args = [x.strip() for x in m.group(2).split(',')]
1942 self.args = [x.strip() for x in m.group(2).split(',')]
1943 for arg in self.args:
1943 for arg in self.args:
1944 # _aliasarg() is an unknown symbol only used separate
1944 # _aliasarg() is an unknown symbol only used separate
1945 # alias argument placeholders from regular strings.
1945 # alias argument placeholders from regular strings.
1946 value = value.replace(arg, '_aliasarg(%r)' % (arg,))
1946 value = value.replace(arg, '_aliasarg(%r)' % (arg,))
1947 else:
1947 else:
1948 self.name = name
1948 self.name = name
1949 self.tree = ('symbol', name)
1949 self.tree = ('symbol', name)
1950
1950
1951 self.replacement, pos = parse(value)
1951 self.replacement, pos = parse(value)
1952 if pos != len(value):
1952 if pos != len(value):
1953 raise error.ParseError(_('invalid token'), pos)
1953 raise error.ParseError(_('invalid token'), pos)
1954 # Check for placeholder injection
1954 # Check for placeholder injection
1955 _checkaliasarg(self.replacement, self.args)
1955 _checkaliasarg(self.replacement, self.args)
1956
1956
1957 def _getalias(aliases, tree):
1957 def _getalias(aliases, tree):
1958 """If tree looks like an unexpanded alias, return it. Return None
1958 """If tree looks like an unexpanded alias, return it. Return None
1959 otherwise.
1959 otherwise.
1960 """
1960 """
1961 if isinstance(tree, tuple) and tree:
1961 if isinstance(tree, tuple) and tree:
1962 if tree[0] == 'symbol' and len(tree) == 2:
1962 if tree[0] == 'symbol' and len(tree) == 2:
1963 name = tree[1]
1963 name = tree[1]
1964 alias = aliases.get(name)
1964 alias = aliases.get(name)
1965 if alias and alias.args is None and alias.tree == tree:
1965 if alias and alias.args is None and alias.tree == tree:
1966 return alias
1966 return alias
1967 if tree[0] == 'func' and len(tree) > 1:
1967 if tree[0] == 'func' and len(tree) > 1:
1968 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
1968 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
1969 name = tree[1][1]
1969 name = tree[1][1]
1970 alias = aliases.get(name)
1970 alias = aliases.get(name)
1971 if alias and alias.args is not None and alias.tree == tree[:2]:
1971 if alias and alias.args is not None and alias.tree == tree[:2]:
1972 return alias
1972 return alias
1973 return None
1973 return None
1974
1974
1975 def _expandargs(tree, args):
1975 def _expandargs(tree, args):
1976 """Replace _aliasarg instances with the substitution value of the
1976 """Replace _aliasarg instances with the substitution value of the
1977 same name in args, recursively.
1977 same name in args, recursively.
1978 """
1978 """
1979 if not tree or not isinstance(tree, tuple):
1979 if not tree or not isinstance(tree, tuple):
1980 return tree
1980 return tree
1981 arg = _getaliasarg(tree)
1981 arg = _getaliasarg(tree)
1982 if arg is not None:
1982 if arg is not None:
1983 return args[arg]
1983 return args[arg]
1984 return tuple(_expandargs(t, args) for t in tree)
1984 return tuple(_expandargs(t, args) for t in tree)
1985
1985
1986 def _expandaliases(aliases, tree, expanding, cache):
1986 def _expandaliases(aliases, tree, expanding, cache):
1987 """Expand aliases in tree, recursively.
1987 """Expand aliases in tree, recursively.
1988
1988
1989 'aliases' is a dictionary mapping user defined aliases to
1989 'aliases' is a dictionary mapping user defined aliases to
1990 revsetalias objects.
1990 revsetalias objects.
1991 """
1991 """
1992 if not isinstance(tree, tuple):
1992 if not isinstance(tree, tuple):
1993 # Do not expand raw strings
1993 # Do not expand raw strings
1994 return tree
1994 return tree
1995 alias = _getalias(aliases, tree)
1995 alias = _getalias(aliases, tree)
1996 if alias is not None:
1996 if alias is not None:
1997 if alias in expanding:
1997 if alias in expanding:
1998 raise error.ParseError(_('infinite expansion of revset alias "%s" '
1998 raise error.ParseError(_('infinite expansion of revset alias "%s" '
1999 'detected') % alias.name)
1999 'detected') % alias.name)
2000 expanding.append(alias)
2000 expanding.append(alias)
2001 if alias.name not in cache:
2001 if alias.name not in cache:
2002 cache[alias.name] = _expandaliases(aliases, alias.replacement,
2002 cache[alias.name] = _expandaliases(aliases, alias.replacement,
2003 expanding, cache)
2003 expanding, cache)
2004 result = cache[alias.name]
2004 result = cache[alias.name]
2005 expanding.pop()
2005 expanding.pop()
2006 if alias.args is not None:
2006 if alias.args is not None:
2007 l = getlist(tree[2])
2007 l = getlist(tree[2])
2008 if len(l) != len(alias.args):
2008 if len(l) != len(alias.args):
2009 raise error.ParseError(
2009 raise error.ParseError(
2010 _('invalid number of arguments: %s') % len(l))
2010 _('invalid number of arguments: %s') % len(l))
2011 l = [_expandaliases(aliases, a, [], cache) for a in l]
2011 l = [_expandaliases(aliases, a, [], cache) for a in l]
2012 result = _expandargs(result, dict(zip(alias.args, l)))
2012 result = _expandargs(result, dict(zip(alias.args, l)))
2013 else:
2013 else:
2014 result = tuple(_expandaliases(aliases, t, expanding, cache)
2014 result = tuple(_expandaliases(aliases, t, expanding, cache)
2015 for t in tree)
2015 for t in tree)
2016 return result
2016 return result
2017
2017
2018 def findaliases(ui, tree):
2018 def findaliases(ui, tree):
2019 _checkaliasarg(tree)
2019 _checkaliasarg(tree)
2020 aliases = {}
2020 aliases = {}
2021 for k, v in ui.configitems('revsetalias'):
2021 for k, v in ui.configitems('revsetalias'):
2022 alias = revsetalias(k, v)
2022 alias = revsetalias(k, v)
2023 aliases[alias.name] = alias
2023 aliases[alias.name] = alias
2024 return _expandaliases(aliases, tree, [], {})
2024 return _expandaliases(aliases, tree, [], {})
2025
2025
2026 def parse(spec):
2026 def parse(spec):
2027 p = parser.parser(tokenize, elements)
2027 p = parser.parser(tokenize, elements)
2028 return p.parse(spec)
2028 return p.parse(spec)
2029
2029
2030 def match(ui, spec):
2030 def match(ui, spec):
2031 if not spec:
2031 if not spec:
2032 raise error.ParseError(_("empty query"))
2032 raise error.ParseError(_("empty query"))
2033 tree, pos = parse(spec)
2033 tree, pos = parse(spec)
2034 if (pos != len(spec)):
2034 if (pos != len(spec)):
2035 raise error.ParseError(_("invalid token"), pos)
2035 raise error.ParseError(_("invalid token"), pos)
2036 if ui:
2036 if ui:
2037 tree = findaliases(ui, tree)
2037 tree = findaliases(ui, tree)
2038 weight, tree = optimize(tree, True)
2038 weight, tree = optimize(tree, True)
2039 def mfunc(repo, subset):
2039 def mfunc(repo, subset):
2040 if util.safehasattr(subset, 'set'):
2040 if util.safehasattr(subset, 'set'):
2041 return getset(repo, subset, tree)
2041 return getset(repo, subset, tree)
2042 return getset(repo, baseset(subset), tree)
2042 return getset(repo, baseset(subset), tree)
2043 return mfunc
2043 return mfunc
2044
2044
2045 def formatspec(expr, *args):
2045 def formatspec(expr, *args):
2046 '''
2046 '''
2047 This is a convenience function for using revsets internally, and
2047 This is a convenience function for using revsets internally, and
2048 escapes arguments appropriately. Aliases are intentionally ignored
2048 escapes arguments appropriately. Aliases are intentionally ignored
2049 so that intended expression behavior isn't accidentally subverted.
2049 so that intended expression behavior isn't accidentally subverted.
2050
2050
2051 Supported arguments:
2051 Supported arguments:
2052
2052
2053 %r = revset expression, parenthesized
2053 %r = revset expression, parenthesized
2054 %d = int(arg), no quoting
2054 %d = int(arg), no quoting
2055 %s = string(arg), escaped and single-quoted
2055 %s = string(arg), escaped and single-quoted
2056 %b = arg.branch(), escaped and single-quoted
2056 %b = arg.branch(), escaped and single-quoted
2057 %n = hex(arg), single-quoted
2057 %n = hex(arg), single-quoted
2058 %% = a literal '%'
2058 %% = a literal '%'
2059
2059
2060 Prefixing the type with 'l' specifies a parenthesized list of that type.
2060 Prefixing the type with 'l' specifies a parenthesized list of that type.
2061
2061
2062 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
2062 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
2063 '(10 or 11):: and ((this()) or (that()))'
2063 '(10 or 11):: and ((this()) or (that()))'
2064 >>> formatspec('%d:: and not %d::', 10, 20)
2064 >>> formatspec('%d:: and not %d::', 10, 20)
2065 '10:: and not 20::'
2065 '10:: and not 20::'
2066 >>> formatspec('%ld or %ld', [], [1])
2066 >>> formatspec('%ld or %ld', [], [1])
2067 "_list('') or 1"
2067 "_list('') or 1"
2068 >>> formatspec('keyword(%s)', 'foo\\xe9')
2068 >>> formatspec('keyword(%s)', 'foo\\xe9')
2069 "keyword('foo\\\\xe9')"
2069 "keyword('foo\\\\xe9')"
2070 >>> b = lambda: 'default'
2070 >>> b = lambda: 'default'
2071 >>> b.branch = b
2071 >>> b.branch = b
2072 >>> formatspec('branch(%b)', b)
2072 >>> formatspec('branch(%b)', b)
2073 "branch('default')"
2073 "branch('default')"
2074 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
2074 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
2075 "root(_list('a\\x00b\\x00c\\x00d'))"
2075 "root(_list('a\\x00b\\x00c\\x00d'))"
2076 '''
2076 '''
2077
2077
2078 def quote(s):
2078 def quote(s):
2079 return repr(str(s))
2079 return repr(str(s))
2080
2080
2081 def argtype(c, arg):
2081 def argtype(c, arg):
2082 if c == 'd':
2082 if c == 'd':
2083 return str(int(arg))
2083 return str(int(arg))
2084 elif c == 's':
2084 elif c == 's':
2085 return quote(arg)
2085 return quote(arg)
2086 elif c == 'r':
2086 elif c == 'r':
2087 parse(arg) # make sure syntax errors are confined
2087 parse(arg) # make sure syntax errors are confined
2088 return '(%s)' % arg
2088 return '(%s)' % arg
2089 elif c == 'n':
2089 elif c == 'n':
2090 return quote(node.hex(arg))
2090 return quote(node.hex(arg))
2091 elif c == 'b':
2091 elif c == 'b':
2092 return quote(arg.branch())
2092 return quote(arg.branch())
2093
2093
2094 def listexp(s, t):
2094 def listexp(s, t):
2095 l = len(s)
2095 l = len(s)
2096 if l == 0:
2096 if l == 0:
2097 return "_list('')"
2097 return "_list('')"
2098 elif l == 1:
2098 elif l == 1:
2099 return argtype(t, s[0])
2099 return argtype(t, s[0])
2100 elif t == 'd':
2100 elif t == 'd':
2101 return "_intlist('%s')" % "\0".join(str(int(a)) for a in s)
2101 return "_intlist('%s')" % "\0".join(str(int(a)) for a in s)
2102 elif t == 's':
2102 elif t == 's':
2103 return "_list('%s')" % "\0".join(s)
2103 return "_list('%s')" % "\0".join(s)
2104 elif t == 'n':
2104 elif t == 'n':
2105 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
2105 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
2106 elif t == 'b':
2106 elif t == 'b':
2107 return "_list('%s')" % "\0".join(a.branch() for a in s)
2107 return "_list('%s')" % "\0".join(a.branch() for a in s)
2108
2108
2109 m = l // 2
2109 m = l // 2
2110 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2110 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2111
2111
2112 ret = ''
2112 ret = ''
2113 pos = 0
2113 pos = 0
2114 arg = 0
2114 arg = 0
2115 while pos < len(expr):
2115 while pos < len(expr):
2116 c = expr[pos]
2116 c = expr[pos]
2117 if c == '%':
2117 if c == '%':
2118 pos += 1
2118 pos += 1
2119 d = expr[pos]
2119 d = expr[pos]
2120 if d == '%':
2120 if d == '%':
2121 ret += d
2121 ret += d
2122 elif d in 'dsnbr':
2122 elif d in 'dsnbr':
2123 ret += argtype(d, args[arg])
2123 ret += argtype(d, args[arg])
2124 arg += 1
2124 arg += 1
2125 elif d == 'l':
2125 elif d == 'l':
2126 # a list of some type
2126 # a list of some type
2127 pos += 1
2127 pos += 1
2128 d = expr[pos]
2128 d = expr[pos]
2129 ret += listexp(list(args[arg]), d)
2129 ret += listexp(list(args[arg]), d)
2130 arg += 1
2130 arg += 1
2131 else:
2131 else:
2132 raise util.Abort('unexpected revspec format character %s' % d)
2132 raise util.Abort('unexpected revspec format character %s' % d)
2133 else:
2133 else:
2134 ret += c
2134 ret += c
2135 pos += 1
2135 pos += 1
2136
2136
2137 return ret
2137 return ret
2138
2138
2139 def prettyformat(tree):
2139 def prettyformat(tree):
2140 def _prettyformat(tree, level, lines):
2140 def _prettyformat(tree, level, lines):
2141 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2141 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2142 lines.append((level, str(tree)))
2142 lines.append((level, str(tree)))
2143 else:
2143 else:
2144 lines.append((level, '(%s' % tree[0]))
2144 lines.append((level, '(%s' % tree[0]))
2145 for s in tree[1:]:
2145 for s in tree[1:]:
2146 _prettyformat(s, level + 1, lines)
2146 _prettyformat(s, level + 1, lines)
2147 lines[-1:] = [(lines[-1][0], lines[-1][1] + ')')]
2147 lines[-1:] = [(lines[-1][0], lines[-1][1] + ')')]
2148
2148
2149 lines = []
2149 lines = []
2150 _prettyformat(tree, 0, lines)
2150 _prettyformat(tree, 0, lines)
2151 output = '\n'.join((' '*l + s) for l, s in lines)
2151 output = '\n'.join((' '*l + s) for l, s in lines)
2152 return output
2152 return output
2153
2153
2154 def depth(tree):
2154 def depth(tree):
2155 if isinstance(tree, tuple):
2155 if isinstance(tree, tuple):
2156 return max(map(depth, tree)) + 1
2156 return max(map(depth, tree)) + 1
2157 else:
2157 else:
2158 return 0
2158 return 0
2159
2159
2160 def funcsused(tree):
2160 def funcsused(tree):
2161 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2161 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2162 return set()
2162 return set()
2163 else:
2163 else:
2164 funcs = set()
2164 funcs = set()
2165 for s in tree[1:]:
2165 for s in tree[1:]:
2166 funcs |= funcsused(s)
2166 funcs |= funcsused(s)
2167 if tree[0] == 'func':
2167 if tree[0] == 'func':
2168 funcs.add(tree[1][1])
2168 funcs.add(tree[1][1])
2169 return funcs
2169 return funcs
2170
2170
2171 class baseset(list):
2171 class baseset(list):
2172 """Basic data structure that represents a revset and contains the basic
2172 """Basic data structure that represents a revset and contains the basic
2173 operation that it should be able to perform.
2173 operation that it should be able to perform.
2174
2174
2175 Every method in this class should be implemented by any smartset class.
2175 Every method in this class should be implemented by any smartset class.
2176 """
2176 """
2177 def __init__(self, data):
2177 def __init__(self, data):
2178 super(baseset, self).__init__(data)
2178 super(baseset, self).__init__(data)
2179 self._set = None
2179 self._set = None
2180
2180
2181 def ascending(self):
2181 def ascending(self):
2182 """Sorts the set in ascending order (in place).
2182 """Sorts the set in ascending order (in place).
2183
2183
2184 This is part of the mandatory API for smartset."""
2184 This is part of the mandatory API for smartset."""
2185 self.sort()
2185 self.sort()
2186
2186
2187 def descending(self):
2187 def descending(self):
2188 """Sorts the set in descending order (in place).
2188 """Sorts the set in descending order (in place).
2189
2189
2190 This is part of the mandatory API for smartset."""
2190 This is part of the mandatory API for smartset."""
2191 self.sort(reverse=True)
2191 self.sort(reverse=True)
2192
2192
2193 def set(self):
2193 def set(self):
2194 """Returns a set or a smartset containing all the elements.
2194 """Returns a set or a smartset containing all the elements.
2195
2195
2196 The returned structure should be the fastest option for membership
2196 The returned structure should be the fastest option for membership
2197 testing.
2197 testing.
2198
2198
2199 This is part of the mandatory API for smartset."""
2199 This is part of the mandatory API for smartset."""
2200 if not self._set:
2200 if not self._set:
2201 self._set = set(self)
2201 self._set = set(self)
2202 return self._set
2202 return self._set
2203
2203
2204 def __sub__(self, other):
2204 def __sub__(self, other):
2205 """Returns a new object with the substraction of the two collections.
2205 """Returns a new object with the substraction of the two collections.
2206
2206
2207 This is part of the mandatory API for smartset."""
2207 This is part of the mandatory API for smartset."""
2208 if isinstance(other, baseset):
2208 if isinstance(other, baseset):
2209 s = other.set()
2209 s = other.set()
2210 else:
2210 else:
2211 s = set(other)
2211 s = set(other)
2212 return baseset(self.set() - s)
2212 return baseset(self.set() - s)
2213
2213
2214 def __and__(self, other):
2214 def __and__(self, other):
2215 """Returns a new object with the intersection of the two collections.
2215 """Returns a new object with the intersection of the two collections.
2216
2216
2217 This is part of the mandatory API for smartset."""
2217 This is part of the mandatory API for smartset."""
2218 if isinstance(other, baseset):
2218 if isinstance(other, baseset):
2219 other = other.set()
2219 other = other.set()
2220 return baseset([y for y in self if y in other])
2220 return baseset([y for y in self if y in other])
2221
2221
2222 def __add__(self, other):
2222 def __add__(self, other):
2223 """Returns a new object with the union of the two collections.
2223 """Returns a new object with the union of the two collections.
2224
2224
2225 This is part of the mandatory API for smartset."""
2225 This is part of the mandatory API for smartset."""
2226 s = self.set()
2226 s = self.set()
2227 l = [r for r in other if r not in s]
2227 l = [r for r in other if r not in s]
2228 return baseset(list(self) + l)
2228 return baseset(list(self) + l)
2229
2229
2230 def isascending(self):
2230 def isascending(self):
2231 """Returns True if the collection is ascending order, False if not.
2231 """Returns True if the collection is ascending order, False if not.
2232
2232
2233 This is part of the mandatory API for smartset."""
2233 This is part of the mandatory API for smartset."""
2234 return False
2234 return False
2235
2235
2236 def isdescending(self):
2236 def isdescending(self):
2237 """Returns True if the collection is descending order, False if not.
2237 """Returns True if the collection is descending order, False if not.
2238
2238
2239 This is part of the mandatory API for smartset."""
2239 This is part of the mandatory API for smartset."""
2240 return False
2240 return False
2241
2241
2242 def filter(self, condition):
2242 def filter(self, condition):
2243 """Returns this smartset filtered by condition as a new smartset.
2243 """Returns this smartset filtered by condition as a new smartset.
2244
2244
2245 `condition` is a callable which takes a revision number and returns a
2245 `condition` is a callable which takes a revision number and returns a
2246 boolean.
2246 boolean.
2247
2247
2248 This is part of the mandatory API for smartset."""
2248 This is part of the mandatory API for smartset."""
2249 return lazyset(self, condition)
2249 return lazyset(self, condition)
2250
2250
2251 class lazyset(object):
2251 class lazyset(object):
2252 """Duck type for baseset class which iterates lazily over the revisions in
2252 """Duck type for baseset class which iterates lazily over the revisions in
2253 the subset and contains a function which tests for membership in the
2253 the subset and contains a function which tests for membership in the
2254 revset
2254 revset
2255 """
2255 """
2256 def __init__(self, subset, condition=lambda x: True):
2256 def __init__(self, subset, condition=lambda x: True):
2257 """
2257 """
2258 condition: a function that decide whether a revision in the subset
2258 condition: a function that decide whether a revision in the subset
2259 belongs to the revset or not.
2259 belongs to the revset or not.
2260 """
2260 """
2261 self._subset = subset
2261 self._subset = subset
2262 self._condition = condition
2262 self._condition = condition
2263 self._cache = {}
2263 self._cache = {}
2264
2264
2265 def ascending(self):
2265 def ascending(self):
2266 self._subset.sort()
2266 self._subset.sort()
2267
2267
2268 def descending(self):
2268 def descending(self):
2269 self._subset.sort(reverse=True)
2269 self._subset.sort(reverse=True)
2270
2270
2271 def __contains__(self, x):
2271 def __contains__(self, x):
2272 c = self._cache
2272 c = self._cache
2273 if x not in c:
2273 if x not in c:
2274 c[x] = x in self._subset and self._condition(x)
2274 c[x] = x in self._subset and self._condition(x)
2275 return c[x]
2275 return c[x]
2276
2276
2277 def __iter__(self):
2277 def __iter__(self):
2278 cond = self._condition
2278 cond = self._condition
2279 for x in self._subset:
2279 for x in self._subset:
2280 if cond(x):
2280 if cond(x):
2281 yield x
2281 yield x
2282
2282
2283 def __and__(self, x):
2283 def __and__(self, x):
2284 return lazyset(self, lambda r: r in x)
2284 return lazyset(self, lambda r: r in x)
2285
2285
2286 def __sub__(self, x):
2286 def __sub__(self, x):
2287 return lazyset(self, lambda r: r not in x)
2287 return lazyset(self, lambda r: r not in x)
2288
2288
2289 def __add__(self, x):
2289 def __add__(self, x):
2290 return _addset(self, x)
2290 return _addset(self, x)
2291
2291
2292 def __nonzero__(self):
2292 def __nonzero__(self):
2293 for r in self:
2293 for r in self:
2294 return True
2294 return True
2295 return False
2295 return False
2296
2296
2297 def __len__(self):
2297 def __len__(self):
2298 # Basic implementation to be changed in future patches.
2298 # Basic implementation to be changed in future patches.
2299 l = baseset([r for r in self])
2299 l = baseset([r for r in self])
2300 return len(l)
2300 return len(l)
2301
2301
2302 def __getitem__(self, x):
2302 def __getitem__(self, x):
2303 # Basic implementation to be changed in future patches.
2303 # Basic implementation to be changed in future patches.
2304 l = baseset([r for r in self])
2304 l = baseset([r for r in self])
2305 return l[x]
2305 return l[x]
2306
2306
2307 def sort(self, reverse=False):
2307 def sort(self, reverse=False):
2308 if not util.safehasattr(self._subset, 'sort'):
2308 if not util.safehasattr(self._subset, 'sort'):
2309 self._subset = baseset(self._subset)
2309 self._subset = baseset(self._subset)
2310 self._subset.sort(reverse=reverse)
2310 self._subset.sort(reverse=reverse)
2311
2311
2312 def reverse(self):
2312 def reverse(self):
2313 self._subset.reverse()
2313 self._subset.reverse()
2314
2314
2315 def set(self):
2315 def set(self):
2316 return set([r for r in self])
2316 return set([r for r in self])
2317
2317
2318 def isascending(self):
2318 def isascending(self):
2319 return False
2319 return False
2320
2320
2321 def isdescending(self):
2321 def isdescending(self):
2322 return False
2322 return False
2323
2323
2324 def filter(self, l):
2324 def filter(self, l):
2325 return lazyset(self, l)
2325 return lazyset(self, l)
2326
2326
2327 class orderedlazyset(lazyset):
2327 class orderedlazyset(lazyset):
2328 """Subclass of lazyset which subset can be ordered either ascending or
2328 """Subclass of lazyset which subset can be ordered either ascending or
2329 descendingly
2329 descendingly
2330 """
2330 """
2331 def __init__(self, subset, condition, ascending=True):
2331 def __init__(self, subset, condition, ascending=True):
2332 super(orderedlazyset, self).__init__(subset, condition)
2332 super(orderedlazyset, self).__init__(subset, condition)
2333 self._ascending = ascending
2333 self._ascending = ascending
2334
2334
2335 def filter(self, l):
2335 def filter(self, l):
2336 return orderedlazyset(self, l, ascending=self._ascending)
2336 return orderedlazyset(self, l, ascending=self._ascending)
2337
2337
2338 def ascending(self):
2338 def ascending(self):
2339 if not self._ascending:
2339 if not self._ascending:
2340 self.reverse()
2340 self.reverse()
2341
2341
2342 def descending(self):
2342 def descending(self):
2343 if self._ascending:
2343 if self._ascending:
2344 self.reverse()
2344 self.reverse()
2345
2345
2346 def __and__(self, x):
2346 def __and__(self, x):
2347 return orderedlazyset(self, lambda r: r in x,
2347 return orderedlazyset(self, lambda r: r in x,
2348 ascending=self._ascending)
2348 ascending=self._ascending)
2349
2349
2350 def __sub__(self, x):
2350 def __sub__(self, x):
2351 return orderedlazyset(self, lambda r: r not in x,
2351 return orderedlazyset(self, lambda r: r not in x,
2352 ascending=self._ascending)
2352 ascending=self._ascending)
2353
2353
2354 def __add__(self, x):
2354 def __add__(self, x):
2355 kwargs = {}
2355 kwargs = {}
2356 if self.isascending() and x.isascending():
2356 if self.isascending() and x.isascending():
2357 kwargs['ascending'] = True
2357 kwargs['ascending'] = True
2358 if self.isdescending() and x.isdescending():
2358 if self.isdescending() and x.isdescending():
2359 kwargs['ascending'] = False
2359 kwargs['ascending'] = False
2360 return _addset(self, x, **kwargs)
2360 return _addset(self, x, **kwargs)
2361
2361
2362 def sort(self, reverse=False):
2362 def sort(self, reverse=False):
2363 if reverse:
2363 if reverse:
2364 if self._ascending:
2364 if self._ascending:
2365 self._subset.sort(reverse=reverse)
2365 self._subset.sort(reverse=reverse)
2366 else:
2366 else:
2367 if not self._ascending:
2367 if not self._ascending:
2368 self._subset.sort(reverse=reverse)
2368 self._subset.sort(reverse=reverse)
2369 self._ascending = not reverse
2369 self._ascending = not reverse
2370
2370
2371 def isascending(self):
2371 def isascending(self):
2372 return self._ascending
2372 return self._ascending
2373
2373
2374 def isdescending(self):
2374 def isdescending(self):
2375 return not self._ascending
2375 return not self._ascending
2376
2376
2377 def reverse(self):
2377 def reverse(self):
2378 self._subset.reverse()
2378 self._subset.reverse()
2379 self._ascending = not self._ascending
2379 self._ascending = not self._ascending
2380
2380
2381 class _addset(object):
2381 class _addset(object):
2382 """Represent the addition of two sets
2382 """Represent the addition of two sets
2383
2383
2384 Wrapper structure for lazily adding two structures without losing much
2384 Wrapper structure for lazily adding two structures without losing much
2385 performance on the __contains__ method
2385 performance on the __contains__ method
2386
2386
2387 If the ascending attribute is set, that means the two structures are
2387 If the ascending attribute is set, that means the two structures are
2388 ordered in either an ascending or descending way. Therefore, we can add
2388 ordered in either an ascending or descending way. Therefore, we can add
2389 them mantaining the order by iterating over both at the same time
2389 them mantaining the order by iterating over both at the same time
2390
2390
2391 This class does not duck-type baseset and it's only supposed to be used
2391 This class does not duck-type baseset and it's only supposed to be used
2392 internally
2392 internally
2393 """
2393 """
2394 def __init__(self, revs1, revs2, ascending=None):
2394 def __init__(self, revs1, revs2, ascending=None):
2395 self._r1 = revs1
2395 self._r1 = revs1
2396 self._r2 = revs2
2396 self._r2 = revs2
2397 self._iter = None
2397 self._iter = None
2398 self._ascending = ascending
2398 self._ascending = ascending
2399 self._genlist = None
2399 self._genlist = None
2400
2400
2401 @util.propertycache
2401 @util.propertycache
2402 def _list(self):
2402 def _list(self):
2403 if not self._genlist:
2403 if not self._genlist:
2404 self._genlist = baseset(self._iterator())
2404 self._genlist = baseset(self._iterator())
2405 return self._genlist
2405 return self._genlist
2406
2406
2407 def filter(self, condition):
2407 def filter(self, condition):
2408 if self._ascending is not None:
2408 if self._ascending is not None:
2409 return orderedlazyset(self, condition, ascending=self._ascending)
2409 return orderedlazyset(self, condition, ascending=self._ascending)
2410 return lazyset(self, condition)
2410 return lazyset(self, condition)
2411
2411
2412 def ascending(self):
2412 def ascending(self):
2413 if self._ascending is None:
2413 if self._ascending is None:
2414 self.sort()
2414 self.sort()
2415 self._ascending = True
2415 self._ascending = True
2416 else:
2416 else:
2417 if not self._ascending:
2417 if not self._ascending:
2418 self.reverse()
2418 self.reverse()
2419
2419
2420 def descending(self):
2420 def descending(self):
2421 if self._ascending is None:
2421 if self._ascending is None:
2422 self.sort(reverse=True)
2422 self.sort(reverse=True)
2423 self._ascending = False
2423 self._ascending = False
2424 else:
2424 else:
2425 if self._ascending:
2425 if self._ascending:
2426 self.reverse()
2426 self.reverse()
2427
2427
2428 def __and__(self, other):
2428 def __and__(self, other):
2429 filterfunc = other.__contains__
2429 filterfunc = other.__contains__
2430 if self._ascending is not None:
2430 if self._ascending is not None:
2431 return orderedlazyset(self, filterfunc, ascending=self._ascending)
2431 return orderedlazyset(self, filterfunc, ascending=self._ascending)
2432 return lazyset(self, filterfunc)
2432 return lazyset(self, filterfunc)
2433
2433
2434 def __sub__(self, other):
2434 def __sub__(self, other):
2435 filterfunc = lambda r: r not in other
2435 filterfunc = lambda r: r not in other
2436 if self._ascending is not None:
2436 if self._ascending is not None:
2437 return orderedlazyset(self, filterfunc, ascending=self._ascending)
2437 return orderedlazyset(self, filterfunc, ascending=self._ascending)
2438 return lazyset(self, filterfunc)
2438 return lazyset(self, filterfunc)
2439
2439
2440 def __add__(self, other):
2440 def __add__(self, other):
2441 """When both collections are ascending or descending, preserve the order
2441 """When both collections are ascending or descending, preserve the order
2442 """
2442 """
2443 kwargs = {}
2443 kwargs = {}
2444 if self._ascending is not None:
2444 if self._ascending is not None:
2445 if self.isascending() and other.isascending():
2445 if self.isascending() and other.isascending():
2446 kwargs['ascending'] = True
2446 kwargs['ascending'] = True
2447 if self.isdescending() and other.isdescending():
2447 if self.isdescending() and other.isdescending():
2448 kwargs['ascending'] = False
2448 kwargs['ascending'] = False
2449 return _addset(self, other, **kwargs)
2449 return _addset(self, other, **kwargs)
2450
2450
2451 def _iterator(self):
2451 def _iterator(self):
2452 """Iterate over both collections without repeating elements
2452 """Iterate over both collections without repeating elements
2453
2453
2454 If the ascending attribute is not set, iterate over the first one and
2454 If the ascending attribute is not set, iterate over the first one and
2455 then over the second one checking for membership on the first one so we
2455 then over the second one checking for membership on the first one so we
2456 dont yield any duplicates.
2456 dont yield any duplicates.
2457
2457
2458 If the ascending attribute is set, iterate over both collections at the
2458 If the ascending attribute is set, iterate over both collections at the
2459 same time, yielding only one value at a time in the given order.
2459 same time, yielding only one value at a time in the given order.
2460 """
2460 """
2461 if not self._iter:
2461 if not self._iter:
2462 def gen():
2462 def gen():
2463 if self._ascending is None:
2463 if self._ascending is None:
2464 for r in self._r1:
2464 for r in self._r1:
2465 yield r
2465 yield r
2466 s = self._r1.set()
2466 s = self._r1.set()
2467 for r in self._r2:
2467 for r in self._r2:
2468 if r not in s:
2468 if r not in s:
2469 yield r
2469 yield r
2470 else:
2470 else:
2471 iter1 = iter(self._r1)
2471 iter1 = iter(self._r1)
2472 iter2 = iter(self._r2)
2472 iter2 = iter(self._r2)
2473
2473
2474 val1 = None
2474 val1 = None
2475 val2 = None
2475 val2 = None
2476
2476
2477 choice = max
2477 choice = max
2478 if self._ascending:
2478 if self._ascending:
2479 choice = min
2479 choice = min
2480 try:
2480 try:
2481 # Consume both iterators in an ordered way until one is
2481 # Consume both iterators in an ordered way until one is
2482 # empty
2482 # empty
2483 while True:
2483 while True:
2484 if val1 is None:
2484 if val1 is None:
2485 val1 = iter1.next()
2485 val1 = iter1.next()
2486 if val2 is None:
2486 if val2 is None:
2487 val2 = iter2.next()
2487 val2 = iter2.next()
2488 next = choice(val1, val2)
2488 next = choice(val1, val2)
2489 yield next
2489 yield next
2490 if val1 == next:
2490 if val1 == next:
2491 val1 = None
2491 val1 = None
2492 if val2 == next:
2492 if val2 == next:
2493 val2 = None
2493 val2 = None
2494 except StopIteration:
2494 except StopIteration:
2495 # Flush any remaining values and consume the other one
2495 # Flush any remaining values and consume the other one
2496 it = iter2
2496 it = iter2
2497 if val1 is not None:
2497 if val1 is not None:
2498 yield val1
2498 yield val1
2499 it = iter1
2499 it = iter1
2500 elif val2 is not None:
2500 elif val2 is not None:
2501 # might have been equality and both are empty
2501 # might have been equality and both are empty
2502 yield val2
2502 yield val2
2503 for val in it:
2503 for val in it:
2504 yield val
2504 yield val
2505
2505
2506 self._iter = _generatorset(gen())
2506 self._iter = _generatorset(gen())
2507
2507
2508 return self._iter
2508 return self._iter
2509
2509
2510 def __iter__(self):
2510 def __iter__(self):
2511 if self._genlist:
2511 if self._genlist:
2512 return iter(self._genlist)
2512 return iter(self._genlist)
2513 return iter(self._iterator())
2513 return iter(self._iterator())
2514
2514
2515 def __contains__(self, x):
2515 def __contains__(self, x):
2516 return x in self._r1 or x in self._r2
2516 return x in self._r1 or x in self._r2
2517
2517
2518 def set(self):
2518 def set(self):
2519 return self
2519 return self
2520
2520
2521 def sort(self, reverse=False):
2521 def sort(self, reverse=False):
2522 """Sort the added set
2522 """Sort the added set
2523
2523
2524 For this we use the cached list with all the generated values and if we
2524 For this we use the cached list with all the generated values and if we
2525 know they are ascending or descending we can sort them in a smart way.
2525 know they are ascending or descending we can sort them in a smart way.
2526 """
2526 """
2527 if self._ascending is None:
2527 if self._ascending is None:
2528 self._list.sort(reverse=reverse)
2528 self._list.sort(reverse=reverse)
2529 self._ascending = not reverse
2529 self._ascending = not reverse
2530 else:
2530 else:
2531 if bool(self._ascending) == bool(reverse):
2531 if bool(self._ascending) == bool(reverse):
2532 self.reverse()
2532 self.reverse()
2533
2533
2534 def isascending(self):
2534 def isascending(self):
2535 return self._ascending is not None and self._ascending
2535 return self._ascending is not None and self._ascending
2536
2536
2537 def isdescending(self):
2537 def isdescending(self):
2538 return self._ascending is not None and not self._ascending
2538 return self._ascending is not None and not self._ascending
2539
2539
2540 def reverse(self):
2540 def reverse(self):
2541 self._list.reverse()
2541 self._list.reverse()
2542 if self._ascending is not None:
2542 if self._ascending is not None:
2543 self._ascending = not self._ascending
2543 self._ascending = not self._ascending
2544
2544
2545 class _generatorset(object):
2545 class _generatorset(object):
2546 """Wrap a generator for lazy iteration
2546 """Wrap a generator for lazy iteration
2547
2547
2548 Wrapper structure for generators that provides lazy membership and can
2548 Wrapper structure for generators that provides lazy membership and can
2549 be iterated more than once.
2549 be iterated more than once.
2550 When asked for membership it generates values until either it finds the
2550 When asked for membership it generates values until either it finds the
2551 requested one or has gone through all the elements in the generator
2551 requested one or has gone through all the elements in the generator
2552
2552
2553 This class does not duck-type baseset and it's only supposed to be used
2553 This class does not duck-type baseset and it's only supposed to be used
2554 internally
2554 internally
2555 """
2555 """
2556 def __init__(self, gen):
2556 def __init__(self, gen):
2557 """
2558 gen: a generator producing the values for the generatorset.
2559 """
2557 self._gen = gen
2560 self._gen = gen
2558 self._iter = iter(gen)
2561 self._iter = iter(gen)
2559 self._cache = {}
2562 self._cache = {}
2560 self._genlist = baseset([])
2563 self._genlist = baseset([])
2561 self._iterated = False
2564 self._iterated = False
2562 self._finished = False
2565 self._finished = False
2563
2566
2564 def __contains__(self, x):
2567 def __contains__(self, x):
2565 if x in self._cache:
2568 if x in self._cache:
2566 return self._cache[x]
2569 return self._cache[x]
2567
2570
2571 # Use __iter__ which caches values and stores them into self._genlist
2568 for l in self:
2572 for l in self:
2569 if l == x:
2573 if l == x:
2570 return True
2574 return True
2571
2575
2572 self._finished = True
2576 self._finished = True
2573 self._cache[x] = False
2577 self._cache[x] = False
2574 return False
2578 return False
2575
2579
2576 def __iter__(self):
2580 def __iter__(self):
2577 if self._iterated:
2581 if self._iterated:
2582 # At least a part of the list should be cached if iteration has
2583 # started over the generatorset.
2578 for l in self._genlist:
2584 for l in self._genlist:
2579 yield l
2585 yield l
2580 else:
2586 else:
2587 # Starting iteration over the generatorset.
2581 self._iterated = True
2588 self._iterated = True
2582
2589
2583 for item in self._gen:
2590 for item in self._gen:
2584 self._cache[item] = True
2591 self._cache[item] = True
2585 self._genlist.append(item)
2592 self._genlist.append(item)
2586 yield item
2593 yield item
2587
2594
2595 # Iteration over the generator has finished. Whole value list should be
2596 # cached in self._genlist
2588 self._finished = True
2597 self._finished = True
2589
2598
2590 def set(self):
2599 def set(self):
2591 return self
2600 return self
2592
2601
2593 def sort(self, reverse=False):
2602 def sort(self, reverse=False):
2594 # Basic implementation to be changed in future patches
2595 if not self._finished:
2603 if not self._finished:
2596 for i in self:
2604 for i in self:
2597 continue
2605 continue
2598 self._genlist.sort(reverse=reverse)
2606 self._genlist.sort(reverse=reverse)
2599
2607
2600 class _ascgeneratorset(_generatorset):
2608 class _ascgeneratorset(_generatorset):
2601 """Wrap a generator of ascending elements for lazy iteration
2609 """Wrap a generator of ascending elements for lazy iteration
2602
2610
2603 Same structure as _generatorset but stops iterating after it goes past
2611 Same structure as _generatorset but stops iterating after it goes past
2604 the value when asked for membership and the element is not contained
2612 the value when asked for membership and the element is not contained
2605
2613
2606 This class does not duck-type baseset and it's only supposed to be used
2614 This class does not duck-type baseset and it's only supposed to be used
2607 internally
2615 internally
2608 """
2616 """
2609 def __contains__(self, x):
2617 def __contains__(self, x):
2610 if x in self._cache:
2618 if x in self._cache:
2611 return self._cache[x]
2619 return self._cache[x]
2612
2620
2613 for l in self:
2621 for l in self:
2614 if l == x:
2622 if l == x:
2615 return True
2623 return True
2616 if l > x:
2624 if l > x:
2617 break
2625 break
2618
2626
2619 self._cache[x] = False
2627 self._cache[x] = False
2620 return False
2628 return False
2621
2629
2622 class _descgeneratorset(_generatorset):
2630 class _descgeneratorset(_generatorset):
2623 """Wrap a generator of descending elements for lazy iteration
2631 """Wrap a generator of descending elements for lazy iteration
2624
2632
2625 Same structure as _generatorset but stops iterating after it goes past
2633 Same structure as _generatorset but stops iterating after it goes past
2626 the value when asked for membership and the element is not contained
2634 the value when asked for membership and the element is not contained
2627
2635
2628 This class does not duck-type baseset and it's only supposed to be used
2636 This class does not duck-type baseset and it's only supposed to be used
2629 internally
2637 internally
2630 """
2638 """
2631 def __contains__(self, x):
2639 def __contains__(self, x):
2632 if x in self._cache:
2640 if x in self._cache:
2633 return self._cache[x]
2641 return self._cache[x]
2634
2642
2635 for l in self:
2643 for l in self:
2636 if l == x:
2644 if l == x:
2637 return True
2645 return True
2638 if l < x:
2646 if l < x:
2639 break
2647 break
2640
2648
2641 self._cache[x] = False
2649 self._cache[x] = False
2642 return False
2650 return False
2643
2651
2644 class spanset(object):
2652 class spanset(object):
2645 """Duck type for baseset class which represents a range of revisions and
2653 """Duck type for baseset class which represents a range of revisions and
2646 can work lazily and without having all the range in memory
2654 can work lazily and without having all the range in memory
2647
2655
2648 Note that spanset(x, y) behave almost like xrange(x, y) except for two
2656 Note that spanset(x, y) behave almost like xrange(x, y) except for two
2649 notable points:
2657 notable points:
2650 - when x < y it will be automatically descending,
2658 - when x < y it will be automatically descending,
2651 - revision filtered with this repoview will be skipped.
2659 - revision filtered with this repoview will be skipped.
2652
2660
2653 """
2661 """
2654 def __init__(self, repo, start=0, end=None):
2662 def __init__(self, repo, start=0, end=None):
2655 """
2663 """
2656 start: first revision included the set
2664 start: first revision included the set
2657 (default to 0)
2665 (default to 0)
2658 end: first revision excluded (last+1)
2666 end: first revision excluded (last+1)
2659 (default to len(repo)
2667 (default to len(repo)
2660
2668
2661 Spanset will be descending if `end` < `start`.
2669 Spanset will be descending if `end` < `start`.
2662 """
2670 """
2663 self._start = start
2671 self._start = start
2664 if end is not None:
2672 if end is not None:
2665 self._end = end
2673 self._end = end
2666 else:
2674 else:
2667 self._end = len(repo)
2675 self._end = len(repo)
2668 self._hiddenrevs = repo.changelog.filteredrevs
2676 self._hiddenrevs = repo.changelog.filteredrevs
2669
2677
2670 def ascending(self):
2678 def ascending(self):
2671 if self._start > self._end:
2679 if self._start > self._end:
2672 self.reverse()
2680 self.reverse()
2673
2681
2674 def descending(self):
2682 def descending(self):
2675 if self._start < self._end:
2683 if self._start < self._end:
2676 self.reverse()
2684 self.reverse()
2677
2685
2678 def _contained(self, rev):
2686 def _contained(self, rev):
2679 return (rev <= self._start and rev > self._end) or (rev >= self._start
2687 return (rev <= self._start and rev > self._end) or (rev >= self._start
2680 and rev < self._end)
2688 and rev < self._end)
2681
2689
2682 def __iter__(self):
2690 def __iter__(self):
2683 if self._start <= self._end:
2691 if self._start <= self._end:
2684 iterrange = xrange(self._start, self._end)
2692 iterrange = xrange(self._start, self._end)
2685 else:
2693 else:
2686 iterrange = xrange(self._start, self._end, -1)
2694 iterrange = xrange(self._start, self._end, -1)
2687
2695
2688 if self._hiddenrevs:
2696 if self._hiddenrevs:
2689 s = self._hiddenrevs
2697 s = self._hiddenrevs
2690 for r in iterrange:
2698 for r in iterrange:
2691 if r not in s:
2699 if r not in s:
2692 yield r
2700 yield r
2693 else:
2701 else:
2694 for r in iterrange:
2702 for r in iterrange:
2695 yield r
2703 yield r
2696
2704
2697 def __contains__(self, x):
2705 def __contains__(self, x):
2698 return self._contained(x) and not (self._hiddenrevs and rev in
2706 return self._contained(x) and not (self._hiddenrevs and rev in
2699 self._hiddenrevs)
2707 self._hiddenrevs)
2700
2708
2701 def __nonzero__(self):
2709 def __nonzero__(self):
2702 for r in self:
2710 for r in self:
2703 return True
2711 return True
2704 return False
2712 return False
2705
2713
2706 def __and__(self, x):
2714 def __and__(self, x):
2707 if isinstance(x, baseset):
2715 if isinstance(x, baseset):
2708 x = x.set()
2716 x = x.set()
2709 if self._start <= self._end:
2717 if self._start <= self._end:
2710 return orderedlazyset(self, lambda r: r in x)
2718 return orderedlazyset(self, lambda r: r in x)
2711 else:
2719 else:
2712 return orderedlazyset(self, lambda r: r in x, ascending=False)
2720 return orderedlazyset(self, lambda r: r in x, ascending=False)
2713
2721
2714 def __sub__(self, x):
2722 def __sub__(self, x):
2715 if isinstance(x, baseset):
2723 if isinstance(x, baseset):
2716 x = x.set()
2724 x = x.set()
2717 if self._start <= self._end:
2725 if self._start <= self._end:
2718 return orderedlazyset(self, lambda r: r not in x)
2726 return orderedlazyset(self, lambda r: r not in x)
2719 else:
2727 else:
2720 return orderedlazyset(self, lambda r: r not in x, ascending=False)
2728 return orderedlazyset(self, lambda r: r not in x, ascending=False)
2721
2729
2722 def __add__(self, x):
2730 def __add__(self, x):
2723 kwargs = {}
2731 kwargs = {}
2724 if self.isascending() and x.isascending():
2732 if self.isascending() and x.isascending():
2725 kwargs['ascending'] = True
2733 kwargs['ascending'] = True
2726 if self.isdescending() and x.isdescending():
2734 if self.isdescending() and x.isdescending():
2727 kwargs['ascending'] = False
2735 kwargs['ascending'] = False
2728 return _addset(self, x, **kwargs)
2736 return _addset(self, x, **kwargs)
2729
2737
2730 def __len__(self):
2738 def __len__(self):
2731 if not self._hiddenrevs:
2739 if not self._hiddenrevs:
2732 return abs(self._end - self._start)
2740 return abs(self._end - self._start)
2733 else:
2741 else:
2734 count = 0
2742 count = 0
2735 for rev in self._hiddenrevs:
2743 for rev in self._hiddenrevs:
2736 if self._contained(rev):
2744 if self._contained(rev):
2737 count += 1
2745 count += 1
2738 return abs(self._end - self._start) - count
2746 return abs(self._end - self._start) - count
2739
2747
2740 def __getitem__(self, x):
2748 def __getitem__(self, x):
2741 # Basic implementation to be changed in future patches.
2749 # Basic implementation to be changed in future patches.
2742 l = baseset([r for r in self])
2750 l = baseset([r for r in self])
2743 return l[x]
2751 return l[x]
2744
2752
2745 def sort(self, reverse=False):
2753 def sort(self, reverse=False):
2746 if bool(reverse) != (self._start > self._end):
2754 if bool(reverse) != (self._start > self._end):
2747 self.reverse()
2755 self.reverse()
2748
2756
2749 def reverse(self):
2757 def reverse(self):
2750 # Just switch the _start and _end parameters
2758 # Just switch the _start and _end parameters
2751 if self._start <= self._end:
2759 if self._start <= self._end:
2752 self._start, self._end = self._end - 1, self._start - 1
2760 self._start, self._end = self._end - 1, self._start - 1
2753 else:
2761 else:
2754 self._start, self._end = self._end + 1, self._start + 1
2762 self._start, self._end = self._end + 1, self._start + 1
2755
2763
2756 def set(self):
2764 def set(self):
2757 return self
2765 return self
2758
2766
2759 def isascending(self):
2767 def isascending(self):
2760 return self._start < self._end
2768 return self._start < self._end
2761
2769
2762 def isdescending(self):
2770 def isdescending(self):
2763 return self._start > self._end
2771 return self._start > self._end
2764
2772
2765 def filter(self, l):
2773 def filter(self, l):
2766 if self._start <= self._end:
2774 if self._start <= self._end:
2767 return orderedlazyset(self, l)
2775 return orderedlazyset(self, l)
2768 else:
2776 else:
2769 return orderedlazyset(self, l, ascending=False)
2777 return orderedlazyset(self, l, ascending=False)
2770
2778
2771 # tell hggettext to extract docstrings from these functions:
2779 # tell hggettext to extract docstrings from these functions:
2772 i18nfunctions = symbols.values()
2780 i18nfunctions = symbols.values()
General Comments 0
You need to be logged in to leave comments. Login now