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