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