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