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