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