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