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