##// END OF EJS Templates
revset: added _hexlist method to replace _list for %ln...
Lucas Moscovicz -
r20569:0d4be103 default
parent child Browse files
Show More
@@ -1,2329 +1,2341 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, discovery, hbisect, phases
9 import parser, util, error, discovery, hbisect, phases
10 import node
10 import node
11 import match as matchmod
11 import match as matchmod
12 from i18n import _
12 from i18n import _
13 import encoding
13 import encoding
14 import obsolete as obsmod
14 import obsolete as obsmod
15 import pathutil
15 import pathutil
16 import repoview
16 import repoview
17
17
18 def _revancestors(repo, revs, followfirst):
18 def _revancestors(repo, revs, followfirst):
19 """Like revlog.ancestors(), but supports followfirst."""
19 """Like revlog.ancestors(), but supports followfirst."""
20 cut = followfirst and 1 or None
20 cut = followfirst and 1 or None
21 cl = repo.changelog
21 cl = repo.changelog
22 visit = util.deque(revs)
22 visit = util.deque(revs)
23 seen = set([node.nullrev])
23 seen = set([node.nullrev])
24 while visit:
24 while visit:
25 for parent in cl.parentrevs(visit.popleft())[:cut]:
25 for parent in cl.parentrevs(visit.popleft())[:cut]:
26 if parent not in seen:
26 if parent not in seen:
27 visit.append(parent)
27 visit.append(parent)
28 seen.add(parent)
28 seen.add(parent)
29 yield parent
29 yield parent
30
30
31 def _revdescendants(repo, revs, followfirst):
31 def _revdescendants(repo, revs, followfirst):
32 """Like revlog.descendants() but supports followfirst."""
32 """Like revlog.descendants() but supports followfirst."""
33 cut = followfirst and 1 or None
33 cut = followfirst and 1 or None
34 cl = repo.changelog
34 cl = repo.changelog
35 first = min(revs)
35 first = min(revs)
36 nullrev = node.nullrev
36 nullrev = node.nullrev
37 if first == nullrev:
37 if first == nullrev:
38 # Are there nodes with a null first parent and a non-null
38 # Are there nodes with a null first parent and a non-null
39 # second one? Maybe. Do we care? Probably not.
39 # second one? Maybe. Do we care? Probably not.
40 for i in cl:
40 for i in cl:
41 yield i
41 yield i
42 return
42 return
43
43
44 seen = set(revs)
44 seen = set(revs)
45 for i in cl.revs(first + 1):
45 for i in cl.revs(first + 1):
46 for x in cl.parentrevs(i)[:cut]:
46 for x in cl.parentrevs(i)[:cut]:
47 if x != nullrev and x in seen:
47 if x != nullrev and x in seen:
48 seen.add(i)
48 seen.add(i)
49 yield i
49 yield i
50 break
50 break
51
51
52 def _revsbetween(repo, roots, heads):
52 def _revsbetween(repo, roots, heads):
53 """Return all paths between roots and heads, inclusive of both endpoint
53 """Return all paths between roots and heads, inclusive of both endpoint
54 sets."""
54 sets."""
55 if not roots:
55 if not roots:
56 return baseset([])
56 return baseset([])
57 parentrevs = repo.changelog.parentrevs
57 parentrevs = repo.changelog.parentrevs
58 visit = baseset(heads)
58 visit = baseset(heads)
59 reachable = set()
59 reachable = set()
60 seen = {}
60 seen = {}
61 minroot = min(roots)
61 minroot = min(roots)
62 roots = set(roots)
62 roots = set(roots)
63 # open-code the post-order traversal due to the tiny size of
63 # open-code the post-order traversal due to the tiny size of
64 # sys.getrecursionlimit()
64 # sys.getrecursionlimit()
65 while visit:
65 while visit:
66 rev = visit.pop()
66 rev = visit.pop()
67 if rev in roots:
67 if rev in roots:
68 reachable.add(rev)
68 reachable.add(rev)
69 parents = parentrevs(rev)
69 parents = parentrevs(rev)
70 seen[rev] = parents
70 seen[rev] = parents
71 for parent in parents:
71 for parent in parents:
72 if parent >= minroot and parent not in seen:
72 if parent >= minroot and parent not in seen:
73 visit.append(parent)
73 visit.append(parent)
74 if not reachable:
74 if not reachable:
75 return baseset([])
75 return baseset([])
76 for rev in sorted(seen):
76 for rev in sorted(seen):
77 for parent in seen[rev]:
77 for parent in seen[rev]:
78 if parent in reachable:
78 if parent in reachable:
79 reachable.add(rev)
79 reachable.add(rev)
80 return baseset(sorted(reachable))
80 return baseset(sorted(reachable))
81
81
82 elements = {
82 elements = {
83 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
83 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
84 "~": (18, None, ("ancestor", 18)),
84 "~": (18, None, ("ancestor", 18)),
85 "^": (18, None, ("parent", 18), ("parentpost", 18)),
85 "^": (18, None, ("parent", 18), ("parentpost", 18)),
86 "-": (5, ("negate", 19), ("minus", 5)),
86 "-": (5, ("negate", 19), ("minus", 5)),
87 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
87 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
88 ("dagrangepost", 17)),
88 ("dagrangepost", 17)),
89 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
89 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
90 ("dagrangepost", 17)),
90 ("dagrangepost", 17)),
91 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
91 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
92 "not": (10, ("not", 10)),
92 "not": (10, ("not", 10)),
93 "!": (10, ("not", 10)),
93 "!": (10, ("not", 10)),
94 "and": (5, None, ("and", 5)),
94 "and": (5, None, ("and", 5)),
95 "&": (5, None, ("and", 5)),
95 "&": (5, None, ("and", 5)),
96 "or": (4, None, ("or", 4)),
96 "or": (4, None, ("or", 4)),
97 "|": (4, None, ("or", 4)),
97 "|": (4, None, ("or", 4)),
98 "+": (4, None, ("or", 4)),
98 "+": (4, None, ("or", 4)),
99 ",": (2, None, ("list", 2)),
99 ",": (2, None, ("list", 2)),
100 ")": (0, None, None),
100 ")": (0, None, None),
101 "symbol": (0, ("symbol",), None),
101 "symbol": (0, ("symbol",), None),
102 "string": (0, ("string",), None),
102 "string": (0, ("string",), None),
103 "end": (0, None, None),
103 "end": (0, None, None),
104 }
104 }
105
105
106 keywords = set(['and', 'or', 'not'])
106 keywords = set(['and', 'or', 'not'])
107
107
108 def tokenize(program):
108 def tokenize(program):
109 '''
109 '''
110 Parse a revset statement into a stream of tokens
110 Parse a revset statement into a stream of tokens
111
111
112 Check that @ is a valid unquoted token character (issue3686):
112 Check that @ is a valid unquoted token character (issue3686):
113 >>> list(tokenize("@::"))
113 >>> list(tokenize("@::"))
114 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
114 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
115
115
116 '''
116 '''
117
117
118 pos, l = 0, len(program)
118 pos, l = 0, len(program)
119 while pos < l:
119 while pos < l:
120 c = program[pos]
120 c = program[pos]
121 if c.isspace(): # skip inter-token whitespace
121 if c.isspace(): # skip inter-token whitespace
122 pass
122 pass
123 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
123 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
124 yield ('::', None, pos)
124 yield ('::', None, pos)
125 pos += 1 # skip ahead
125 pos += 1 # skip ahead
126 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
126 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
127 yield ('..', None, pos)
127 yield ('..', None, pos)
128 pos += 1 # skip ahead
128 pos += 1 # skip ahead
129 elif c in "():,-|&+!~^": # handle simple operators
129 elif c in "():,-|&+!~^": # handle simple operators
130 yield (c, None, pos)
130 yield (c, None, pos)
131 elif (c in '"\'' or c == 'r' and
131 elif (c in '"\'' or c == 'r' and
132 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
132 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
133 if c == 'r':
133 if c == 'r':
134 pos += 1
134 pos += 1
135 c = program[pos]
135 c = program[pos]
136 decode = lambda x: x
136 decode = lambda x: x
137 else:
137 else:
138 decode = lambda x: x.decode('string-escape')
138 decode = lambda x: x.decode('string-escape')
139 pos += 1
139 pos += 1
140 s = pos
140 s = pos
141 while pos < l: # find closing quote
141 while pos < l: # find closing quote
142 d = program[pos]
142 d = program[pos]
143 if d == '\\': # skip over escaped characters
143 if d == '\\': # skip over escaped characters
144 pos += 2
144 pos += 2
145 continue
145 continue
146 if d == c:
146 if d == c:
147 yield ('string', decode(program[s:pos]), s)
147 yield ('string', decode(program[s:pos]), s)
148 break
148 break
149 pos += 1
149 pos += 1
150 else:
150 else:
151 raise error.ParseError(_("unterminated string"), s)
151 raise error.ParseError(_("unterminated string"), s)
152 # gather up a symbol/keyword
152 # gather up a symbol/keyword
153 elif c.isalnum() or c in '._@' or ord(c) > 127:
153 elif c.isalnum() or c in '._@' or ord(c) > 127:
154 s = pos
154 s = pos
155 pos += 1
155 pos += 1
156 while pos < l: # find end of symbol
156 while pos < l: # find end of symbol
157 d = program[pos]
157 d = program[pos]
158 if not (d.isalnum() or d in "._/@" or ord(d) > 127):
158 if not (d.isalnum() or d in "._/@" or ord(d) > 127):
159 break
159 break
160 if d == '.' and program[pos - 1] == '.': # special case for ..
160 if d == '.' and program[pos - 1] == '.': # special case for ..
161 pos -= 1
161 pos -= 1
162 break
162 break
163 pos += 1
163 pos += 1
164 sym = program[s:pos]
164 sym = program[s:pos]
165 if sym in keywords: # operator keywords
165 if sym in keywords: # operator keywords
166 yield (sym, None, s)
166 yield (sym, None, s)
167 else:
167 else:
168 yield ('symbol', sym, s)
168 yield ('symbol', sym, s)
169 pos -= 1
169 pos -= 1
170 else:
170 else:
171 raise error.ParseError(_("syntax error"), pos)
171 raise error.ParseError(_("syntax error"), pos)
172 pos += 1
172 pos += 1
173 yield ('end', None, pos)
173 yield ('end', None, pos)
174
174
175 # helpers
175 # helpers
176
176
177 def getstring(x, err):
177 def getstring(x, err):
178 if x and (x[0] == 'string' or x[0] == 'symbol'):
178 if x and (x[0] == 'string' or x[0] == 'symbol'):
179 return x[1]
179 return x[1]
180 raise error.ParseError(err)
180 raise error.ParseError(err)
181
181
182 def getlist(x):
182 def getlist(x):
183 if not x:
183 if not x:
184 return []
184 return []
185 if x[0] == 'list':
185 if x[0] == 'list':
186 return getlist(x[1]) + [x[2]]
186 return getlist(x[1]) + [x[2]]
187 return [x]
187 return [x]
188
188
189 def getargs(x, min, max, err):
189 def getargs(x, min, max, err):
190 l = getlist(x)
190 l = getlist(x)
191 if len(l) < min or (max >= 0 and len(l) > max):
191 if len(l) < min or (max >= 0 and len(l) > max):
192 raise error.ParseError(err)
192 raise error.ParseError(err)
193 return l
193 return l
194
194
195 def getset(repo, subset, x):
195 def getset(repo, subset, x):
196 if not x:
196 if not x:
197 raise error.ParseError(_("missing argument"))
197 raise error.ParseError(_("missing argument"))
198 s = methods[x[0]](repo, subset, *x[1:])
198 s = methods[x[0]](repo, subset, *x[1:])
199 if util.safehasattr(s, 'set'):
199 if util.safehasattr(s, 'set'):
200 return s
200 return s
201 return baseset(s)
201 return baseset(s)
202
202
203 def _getrevsource(repo, r):
203 def _getrevsource(repo, r):
204 extra = repo[r].extra()
204 extra = repo[r].extra()
205 for label in ('source', 'transplant_source', 'rebase_source'):
205 for label in ('source', 'transplant_source', 'rebase_source'):
206 if label in extra:
206 if label in extra:
207 try:
207 try:
208 return repo[extra[label]].rev()
208 return repo[extra[label]].rev()
209 except error.RepoLookupError:
209 except error.RepoLookupError:
210 pass
210 pass
211 return None
211 return None
212
212
213 # operator methods
213 # operator methods
214
214
215 def stringset(repo, subset, x):
215 def stringset(repo, subset, x):
216 x = repo[x].rev()
216 x = repo[x].rev()
217 if x == -1 and len(subset) == len(repo):
217 if x == -1 and len(subset) == len(repo):
218 return baseset([-1])
218 return baseset([-1])
219 if len(subset) == len(repo) or x in subset:
219 if len(subset) == len(repo) or x in subset:
220 return baseset([x])
220 return baseset([x])
221 return baseset([])
221 return baseset([])
222
222
223 def symbolset(repo, subset, x):
223 def symbolset(repo, subset, x):
224 if x in symbols:
224 if x in symbols:
225 raise error.ParseError(_("can't use %s here") % x)
225 raise error.ParseError(_("can't use %s here") % x)
226 return stringset(repo, subset, x)
226 return stringset(repo, subset, x)
227
227
228 def rangeset(repo, subset, x, y):
228 def rangeset(repo, subset, x, y):
229 cl = baseset(repo.changelog)
229 cl = baseset(repo.changelog)
230 m = getset(repo, cl, x)
230 m = getset(repo, cl, x)
231 n = getset(repo, cl, y)
231 n = getset(repo, cl, y)
232
232
233 if not m or not n:
233 if not m or not n:
234 return baseset([])
234 return baseset([])
235 m, n = m[0], n[-1]
235 m, n = m[0], n[-1]
236
236
237 if m < n:
237 if m < n:
238 r = spanset(repo, m, n + 1)
238 r = spanset(repo, m, n + 1)
239 else:
239 else:
240 r = spanset(repo, m, n - 1)
240 r = spanset(repo, m, n - 1)
241 return r & subset
241 return r & subset
242
242
243 def dagrange(repo, subset, x, y):
243 def dagrange(repo, subset, x, y):
244 r = spanset(repo)
244 r = spanset(repo)
245 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
245 xs = _revsbetween(repo, getset(repo, r, x), getset(repo, r, y))
246 s = subset.set()
246 s = subset.set()
247 return baseset([r for r in xs if r in s])
247 return baseset([r for r in xs if r in s])
248
248
249 def andset(repo, subset, x, y):
249 def andset(repo, subset, x, y):
250 return getset(repo, getset(repo, subset, x), y)
250 return getset(repo, getset(repo, subset, x), y)
251
251
252 def orset(repo, subset, x, y):
252 def orset(repo, subset, x, y):
253 xl = getset(repo, subset, x)
253 xl = getset(repo, subset, x)
254 yl = getset(repo, subset - xl, y)
254 yl = getset(repo, subset - xl, y)
255 return xl + yl
255 return xl + yl
256
256
257 def notset(repo, subset, x):
257 def notset(repo, subset, x):
258 return subset - getset(repo, subset, x)
258 return subset - getset(repo, subset, x)
259
259
260 def listset(repo, subset, a, b):
260 def listset(repo, subset, a, b):
261 raise error.ParseError(_("can't use a list in this context"))
261 raise error.ParseError(_("can't use a list in this context"))
262
262
263 def func(repo, subset, a, b):
263 def func(repo, subset, a, b):
264 if a[0] == 'symbol' and a[1] in symbols:
264 if a[0] == 'symbol' and a[1] in symbols:
265 return symbols[a[1]](repo, subset, b)
265 return symbols[a[1]](repo, subset, b)
266 raise error.ParseError(_("not a function: %s") % a[1])
266 raise error.ParseError(_("not a function: %s") % a[1])
267
267
268 # functions
268 # functions
269
269
270 def adds(repo, subset, x):
270 def adds(repo, subset, x):
271 """``adds(pattern)``
271 """``adds(pattern)``
272 Changesets that add a file matching pattern.
272 Changesets that add a file matching pattern.
273
273
274 The pattern without explicit kind like ``glob:`` is expected to be
274 The pattern without explicit kind like ``glob:`` is expected to be
275 relative to the current directory and match against a file or a
275 relative to the current directory and match against a file or a
276 directory.
276 directory.
277 """
277 """
278 # i18n: "adds" is a keyword
278 # i18n: "adds" is a keyword
279 pat = getstring(x, _("adds requires a pattern"))
279 pat = getstring(x, _("adds requires a pattern"))
280 return checkstatus(repo, subset, pat, 1)
280 return checkstatus(repo, subset, pat, 1)
281
281
282 def ancestor(repo, subset, x):
282 def ancestor(repo, subset, x):
283 """``ancestor(*changeset)``
283 """``ancestor(*changeset)``
284 Greatest common ancestor of the changesets.
284 Greatest common ancestor of the changesets.
285
285
286 Accepts 0 or more changesets.
286 Accepts 0 or more changesets.
287 Will return empty list when passed no args.
287 Will return empty list when passed no args.
288 Greatest common ancestor of a single changeset is that changeset.
288 Greatest common ancestor of a single changeset is that changeset.
289 """
289 """
290 # i18n: "ancestor" is a keyword
290 # i18n: "ancestor" is a keyword
291 l = getlist(x)
291 l = getlist(x)
292 rl = spanset(repo)
292 rl = spanset(repo)
293 anc = None
293 anc = None
294
294
295 # (getset(repo, rl, i) for i in l) generates a list of lists
295 # (getset(repo, rl, i) for i in l) generates a list of lists
296 rev = repo.changelog.rev
296 rev = repo.changelog.rev
297 ancestor = repo.changelog.ancestor
297 ancestor = repo.changelog.ancestor
298 node = repo.changelog.node
298 node = repo.changelog.node
299 for revs in (getset(repo, rl, i) for i in l):
299 for revs in (getset(repo, rl, i) for i in l):
300 for r in revs:
300 for r in revs:
301 if anc is None:
301 if anc is None:
302 anc = r
302 anc = r
303 else:
303 else:
304 anc = rev(ancestor(node(anc), node(r)))
304 anc = rev(ancestor(node(anc), node(r)))
305
305
306 if anc is not None and anc in subset:
306 if anc is not None and anc in subset:
307 return baseset([anc])
307 return baseset([anc])
308 return baseset([])
308 return baseset([])
309
309
310 def _ancestors(repo, subset, x, followfirst=False):
310 def _ancestors(repo, subset, x, followfirst=False):
311 args = getset(repo, spanset(repo), x)
311 args = getset(repo, spanset(repo), x)
312 if not args:
312 if not args:
313 return baseset([])
313 return baseset([])
314 s = set(_revancestors(repo, args, followfirst)) | set(args)
314 s = set(_revancestors(repo, args, followfirst)) | set(args)
315 return baseset([r for r in subset if r in s])
315 return baseset([r for r in subset if r in s])
316
316
317 def ancestors(repo, subset, x):
317 def ancestors(repo, subset, x):
318 """``ancestors(set)``
318 """``ancestors(set)``
319 Changesets that are ancestors of a changeset in set.
319 Changesets that are ancestors of a changeset in set.
320 """
320 """
321 return _ancestors(repo, subset, x)
321 return _ancestors(repo, subset, x)
322
322
323 def _firstancestors(repo, subset, x):
323 def _firstancestors(repo, subset, x):
324 # ``_firstancestors(set)``
324 # ``_firstancestors(set)``
325 # Like ``ancestors(set)`` but follows only the first parents.
325 # Like ``ancestors(set)`` but follows only the first parents.
326 return _ancestors(repo, subset, x, followfirst=True)
326 return _ancestors(repo, subset, x, followfirst=True)
327
327
328 def ancestorspec(repo, subset, x, n):
328 def ancestorspec(repo, subset, x, n):
329 """``set~n``
329 """``set~n``
330 Changesets that are the Nth ancestor (first parents only) of a changeset
330 Changesets that are the Nth ancestor (first parents only) of a changeset
331 in set.
331 in set.
332 """
332 """
333 try:
333 try:
334 n = int(n[1])
334 n = int(n[1])
335 except (TypeError, ValueError):
335 except (TypeError, ValueError):
336 raise error.ParseError(_("~ expects a number"))
336 raise error.ParseError(_("~ expects a number"))
337 ps = set()
337 ps = set()
338 cl = repo.changelog
338 cl = repo.changelog
339 for r in getset(repo, baseset(cl), x):
339 for r in getset(repo, baseset(cl), x):
340 for i in range(n):
340 for i in range(n):
341 r = cl.parentrevs(r)[0]
341 r = cl.parentrevs(r)[0]
342 ps.add(r)
342 ps.add(r)
343 return baseset([r for r in subset if r in ps])
343 return baseset([r for r in subset if r in ps])
344
344
345 def author(repo, subset, x):
345 def author(repo, subset, x):
346 """``author(string)``
346 """``author(string)``
347 Alias for ``user(string)``.
347 Alias for ``user(string)``.
348 """
348 """
349 # i18n: "author" is a keyword
349 # i18n: "author" is a keyword
350 n = encoding.lower(getstring(x, _("author requires a string")))
350 n = encoding.lower(getstring(x, _("author requires a string")))
351 kind, pattern, matcher = _substringmatcher(n)
351 kind, pattern, matcher = _substringmatcher(n)
352 return lazyset(subset, lambda x: matcher(encoding.lower(repo[x].user())))
352 return lazyset(subset, lambda x: matcher(encoding.lower(repo[x].user())))
353
353
354 def bisect(repo, subset, x):
354 def bisect(repo, subset, x):
355 """``bisect(string)``
355 """``bisect(string)``
356 Changesets marked in the specified bisect status:
356 Changesets marked in the specified bisect status:
357
357
358 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
358 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
359 - ``goods``, ``bads`` : csets topologically good/bad
359 - ``goods``, ``bads`` : csets topologically good/bad
360 - ``range`` : csets taking part in the bisection
360 - ``range`` : csets taking part in the bisection
361 - ``pruned`` : csets that are goods, bads or skipped
361 - ``pruned`` : csets that are goods, bads or skipped
362 - ``untested`` : csets whose fate is yet unknown
362 - ``untested`` : csets whose fate is yet unknown
363 - ``ignored`` : csets ignored due to DAG topology
363 - ``ignored`` : csets ignored due to DAG topology
364 - ``current`` : the cset currently being bisected
364 - ``current`` : the cset currently being bisected
365 """
365 """
366 # i18n: "bisect" is a keyword
366 # i18n: "bisect" is a keyword
367 status = getstring(x, _("bisect requires a string")).lower()
367 status = getstring(x, _("bisect requires a string")).lower()
368 state = set(hbisect.get(repo, status))
368 state = set(hbisect.get(repo, status))
369 return baseset([r for r in subset if r in state])
369 return baseset([r for r in subset if r in state])
370
370
371 # Backward-compatibility
371 # Backward-compatibility
372 # - no help entry so that we do not advertise it any more
372 # - no help entry so that we do not advertise it any more
373 def bisected(repo, subset, x):
373 def bisected(repo, subset, x):
374 return bisect(repo, subset, x)
374 return bisect(repo, subset, x)
375
375
376 def bookmark(repo, subset, x):
376 def bookmark(repo, subset, x):
377 """``bookmark([name])``
377 """``bookmark([name])``
378 The named bookmark or all bookmarks.
378 The named bookmark or all bookmarks.
379
379
380 If `name` starts with `re:`, the remainder of the name is treated as
380 If `name` starts with `re:`, the remainder of the name is treated as
381 a regular expression. To match a bookmark that actually starts with `re:`,
381 a regular expression. To match a bookmark that actually starts with `re:`,
382 use the prefix `literal:`.
382 use the prefix `literal:`.
383 """
383 """
384 # i18n: "bookmark" is a keyword
384 # i18n: "bookmark" is a keyword
385 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
385 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
386 if args:
386 if args:
387 bm = getstring(args[0],
387 bm = getstring(args[0],
388 # i18n: "bookmark" is a keyword
388 # i18n: "bookmark" is a keyword
389 _('the argument to bookmark must be a string'))
389 _('the argument to bookmark must be a string'))
390 kind, pattern, matcher = _stringmatcher(bm)
390 kind, pattern, matcher = _stringmatcher(bm)
391 if kind == 'literal':
391 if kind == 'literal':
392 bmrev = repo._bookmarks.get(bm, None)
392 bmrev = repo._bookmarks.get(bm, None)
393 if not bmrev:
393 if not bmrev:
394 raise util.Abort(_("bookmark '%s' does not exist") % bm)
394 raise util.Abort(_("bookmark '%s' does not exist") % bm)
395 bmrev = repo[bmrev].rev()
395 bmrev = repo[bmrev].rev()
396 return lazyset(subset, lambda r: r == bmrev)
396 return lazyset(subset, lambda r: r == bmrev)
397 else:
397 else:
398 matchrevs = set()
398 matchrevs = set()
399 for name, bmrev in repo._bookmarks.iteritems():
399 for name, bmrev in repo._bookmarks.iteritems():
400 if matcher(name):
400 if matcher(name):
401 matchrevs.add(bmrev)
401 matchrevs.add(bmrev)
402 if not matchrevs:
402 if not matchrevs:
403 raise util.Abort(_("no bookmarks exist that match '%s'")
403 raise util.Abort(_("no bookmarks exist that match '%s'")
404 % pattern)
404 % pattern)
405 bmrevs = set()
405 bmrevs = set()
406 for bmrev in matchrevs:
406 for bmrev in matchrevs:
407 bmrevs.add(repo[bmrev].rev())
407 bmrevs.add(repo[bmrev].rev())
408 return subset & bmrevs
408 return subset & bmrevs
409
409
410 bms = set([repo[r].rev()
410 bms = set([repo[r].rev()
411 for r in repo._bookmarks.values()])
411 for r in repo._bookmarks.values()])
412 return lazyset(subset, lambda r: r in bms)
412 return lazyset(subset, lambda r: r in bms)
413
413
414 def branch(repo, subset, x):
414 def branch(repo, subset, x):
415 """``branch(string or set)``
415 """``branch(string or set)``
416 All changesets belonging to the given branch or the branches of the given
416 All changesets belonging to the given branch or the branches of the given
417 changesets.
417 changesets.
418
418
419 If `string` starts with `re:`, the remainder of the name is treated as
419 If `string` starts with `re:`, the remainder of the name is treated as
420 a regular expression. To match a branch that actually starts with `re:`,
420 a regular expression. To match a branch that actually starts with `re:`,
421 use the prefix `literal:`.
421 use the prefix `literal:`.
422 """
422 """
423 try:
423 try:
424 b = getstring(x, '')
424 b = getstring(x, '')
425 except error.ParseError:
425 except error.ParseError:
426 # not a string, but another revspec, e.g. tip()
426 # not a string, but another revspec, e.g. tip()
427 pass
427 pass
428 else:
428 else:
429 kind, pattern, matcher = _stringmatcher(b)
429 kind, pattern, matcher = _stringmatcher(b)
430 if kind == 'literal':
430 if kind == 'literal':
431 # note: falls through to the revspec case if no branch with
431 # note: falls through to the revspec case if no branch with
432 # this name exists
432 # this name exists
433 if pattern in repo.branchmap():
433 if pattern in repo.branchmap():
434 return lazyset(subset, lambda r: matcher(repo[r].branch()))
434 return lazyset(subset, lambda r: matcher(repo[r].branch()))
435 else:
435 else:
436 return lazyset(subset, lambda r: matcher(repo[r].branch()))
436 return lazyset(subset, lambda r: matcher(repo[r].branch()))
437
437
438 s = getset(repo, spanset(repo), x)
438 s = getset(repo, spanset(repo), x)
439 b = set()
439 b = set()
440 for r in s:
440 for r in s:
441 b.add(repo[r].branch())
441 b.add(repo[r].branch())
442 s = s.set()
442 s = s.set()
443 return lazyset(subset, lambda r: r in s or repo[r].branch() in b)
443 return lazyset(subset, lambda r: r in s or repo[r].branch() in b)
444
444
445 def bumped(repo, subset, x):
445 def bumped(repo, subset, x):
446 """``bumped()``
446 """``bumped()``
447 Mutable changesets marked as successors of public changesets.
447 Mutable changesets marked as successors of public changesets.
448
448
449 Only non-public and non-obsolete changesets can be `bumped`.
449 Only non-public and non-obsolete changesets can be `bumped`.
450 """
450 """
451 # i18n: "bumped" is a keyword
451 # i18n: "bumped" is a keyword
452 getargs(x, 0, 0, _("bumped takes no arguments"))
452 getargs(x, 0, 0, _("bumped takes no arguments"))
453 bumped = obsmod.getrevs(repo, 'bumped')
453 bumped = obsmod.getrevs(repo, 'bumped')
454 return subset & bumped
454 return subset & bumped
455
455
456 def bundle(repo, subset, x):
456 def bundle(repo, subset, x):
457 """``bundle()``
457 """``bundle()``
458 Changesets in the bundle.
458 Changesets in the bundle.
459
459
460 Bundle must be specified by the -R option."""
460 Bundle must be specified by the -R option."""
461
461
462 try:
462 try:
463 bundlerevs = repo.changelog.bundlerevs
463 bundlerevs = repo.changelog.bundlerevs
464 except AttributeError:
464 except AttributeError:
465 raise util.Abort(_("no bundle provided - specify with -R"))
465 raise util.Abort(_("no bundle provided - specify with -R"))
466 return subset & bundlerevs
466 return subset & bundlerevs
467
467
468 def checkstatus(repo, subset, pat, field):
468 def checkstatus(repo, subset, pat, field):
469 hasset = matchmod.patkind(pat) == 'set'
469 hasset = matchmod.patkind(pat) == 'set'
470
470
471 def matches(x):
471 def matches(x):
472 m = None
472 m = None
473 fname = None
473 fname = None
474 c = repo[x]
474 c = repo[x]
475 if not m or hasset:
475 if not m or hasset:
476 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
476 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
477 if not m.anypats() and len(m.files()) == 1:
477 if not m.anypats() and len(m.files()) == 1:
478 fname = m.files()[0]
478 fname = m.files()[0]
479 if fname is not None:
479 if fname is not None:
480 if fname not in c.files():
480 if fname not in c.files():
481 return False
481 return False
482 else:
482 else:
483 for f in c.files():
483 for f in c.files():
484 if m(f):
484 if m(f):
485 break
485 break
486 else:
486 else:
487 return False
487 return False
488 files = repo.status(c.p1().node(), c.node())[field]
488 files = repo.status(c.p1().node(), c.node())[field]
489 if fname is not None:
489 if fname is not None:
490 if fname in files:
490 if fname in files:
491 return True
491 return True
492 else:
492 else:
493 for f in files:
493 for f in files:
494 if m(f):
494 if m(f):
495 return True
495 return True
496
496
497 return lazyset(subset, matches)
497 return lazyset(subset, matches)
498
498
499 def _children(repo, narrow, parentset):
499 def _children(repo, narrow, parentset):
500 cs = set()
500 cs = set()
501 if not parentset:
501 if not parentset:
502 return baseset(cs)
502 return baseset(cs)
503 pr = repo.changelog.parentrevs
503 pr = repo.changelog.parentrevs
504 minrev = min(parentset)
504 minrev = min(parentset)
505 for r in narrow:
505 for r in narrow:
506 if r <= minrev:
506 if r <= minrev:
507 continue
507 continue
508 for p in pr(r):
508 for p in pr(r):
509 if p in parentset:
509 if p in parentset:
510 cs.add(r)
510 cs.add(r)
511 return baseset(cs)
511 return baseset(cs)
512
512
513 def children(repo, subset, x):
513 def children(repo, subset, x):
514 """``children(set)``
514 """``children(set)``
515 Child changesets of changesets in set.
515 Child changesets of changesets in set.
516 """
516 """
517 s = getset(repo, baseset(repo), x).set()
517 s = getset(repo, baseset(repo), x).set()
518 cs = _children(repo, subset, s)
518 cs = _children(repo, subset, s)
519 return subset & cs
519 return subset & cs
520
520
521 def closed(repo, subset, x):
521 def closed(repo, subset, x):
522 """``closed()``
522 """``closed()``
523 Changeset is closed.
523 Changeset is closed.
524 """
524 """
525 # i18n: "closed" is a keyword
525 # i18n: "closed" is a keyword
526 getargs(x, 0, 0, _("closed takes no arguments"))
526 getargs(x, 0, 0, _("closed takes no arguments"))
527 return lazyset(subset, lambda r: repo[r].closesbranch())
527 return lazyset(subset, lambda r: repo[r].closesbranch())
528
528
529 def contains(repo, subset, x):
529 def contains(repo, subset, x):
530 """``contains(pattern)``
530 """``contains(pattern)``
531 Revision contains a file matching pattern. See :hg:`help patterns`
531 Revision contains a file matching pattern. See :hg:`help patterns`
532 for information about file patterns.
532 for information about file patterns.
533
533
534 The pattern without explicit kind like ``glob:`` is expected to be
534 The pattern without explicit kind like ``glob:`` is expected to be
535 relative to the current directory and match against a file exactly
535 relative to the current directory and match against a file exactly
536 for efficiency.
536 for efficiency.
537 """
537 """
538 # i18n: "contains" is a keyword
538 # i18n: "contains" is a keyword
539 pat = getstring(x, _("contains requires a pattern"))
539 pat = getstring(x, _("contains requires a pattern"))
540
540
541 def matches(x):
541 def matches(x):
542 if not matchmod.patkind(pat):
542 if not matchmod.patkind(pat):
543 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
543 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
544 if pats in repo[x]:
544 if pats in repo[x]:
545 return True
545 return True
546 else:
546 else:
547 c = repo[x]
547 c = repo[x]
548 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
548 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
549 for f in c.manifest():
549 for f in c.manifest():
550 if m(f):
550 if m(f):
551 return True
551 return True
552 return False
552 return False
553
553
554 return lazyset(subset, matches)
554 return lazyset(subset, matches)
555
555
556 def converted(repo, subset, x):
556 def converted(repo, subset, x):
557 """``converted([id])``
557 """``converted([id])``
558 Changesets converted from the given identifier in the old repository if
558 Changesets converted from the given identifier in the old repository if
559 present, or all converted changesets if no identifier is specified.
559 present, or all converted changesets if no identifier is specified.
560 """
560 """
561
561
562 # There is exactly no chance of resolving the revision, so do a simple
562 # There is exactly no chance of resolving the revision, so do a simple
563 # string compare and hope for the best
563 # string compare and hope for the best
564
564
565 rev = None
565 rev = None
566 # i18n: "converted" is a keyword
566 # i18n: "converted" is a keyword
567 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
567 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
568 if l:
568 if l:
569 # i18n: "converted" is a keyword
569 # i18n: "converted" is a keyword
570 rev = getstring(l[0], _('converted requires a revision'))
570 rev = getstring(l[0], _('converted requires a revision'))
571
571
572 def _matchvalue(r):
572 def _matchvalue(r):
573 source = repo[r].extra().get('convert_revision', None)
573 source = repo[r].extra().get('convert_revision', None)
574 return source is not None and (rev is None or source.startswith(rev))
574 return source is not None and (rev is None or source.startswith(rev))
575
575
576 return lazyset(subset, lambda r: _matchvalue(r))
576 return lazyset(subset, lambda r: _matchvalue(r))
577
577
578 def date(repo, subset, x):
578 def date(repo, subset, x):
579 """``date(interval)``
579 """``date(interval)``
580 Changesets within the interval, see :hg:`help dates`.
580 Changesets within the interval, see :hg:`help dates`.
581 """
581 """
582 # i18n: "date" is a keyword
582 # i18n: "date" is a keyword
583 ds = getstring(x, _("date requires a string"))
583 ds = getstring(x, _("date requires a string"))
584 dm = util.matchdate(ds)
584 dm = util.matchdate(ds)
585 return lazyset(subset, lambda x: dm(repo[x].date()[0]))
585 return lazyset(subset, lambda x: dm(repo[x].date()[0]))
586
586
587 def desc(repo, subset, x):
587 def desc(repo, subset, x):
588 """``desc(string)``
588 """``desc(string)``
589 Search commit message for string. The match is case-insensitive.
589 Search commit message for string. The match is case-insensitive.
590 """
590 """
591 # i18n: "desc" is a keyword
591 # i18n: "desc" is a keyword
592 ds = encoding.lower(getstring(x, _("desc requires a string")))
592 ds = encoding.lower(getstring(x, _("desc requires a string")))
593
593
594 def matches(x):
594 def matches(x):
595 c = repo[x]
595 c = repo[x]
596 return ds in encoding.lower(c.description())
596 return ds in encoding.lower(c.description())
597
597
598 return lazyset(subset, matches)
598 return lazyset(subset, matches)
599
599
600 def _descendants(repo, subset, x, followfirst=False):
600 def _descendants(repo, subset, x, followfirst=False):
601 args = getset(repo, spanset(repo), x)
601 args = getset(repo, spanset(repo), x)
602 if not args:
602 if not args:
603 return baseset([])
603 return baseset([])
604 s = set(_revdescendants(repo, args, followfirst)) | set(args)
604 s = set(_revdescendants(repo, args, followfirst)) | set(args)
605 return subset & s
605 return subset & s
606
606
607 def descendants(repo, subset, x):
607 def descendants(repo, subset, x):
608 """``descendants(set)``
608 """``descendants(set)``
609 Changesets which are descendants of changesets in set.
609 Changesets which are descendants of changesets in set.
610 """
610 """
611 return _descendants(repo, subset, x)
611 return _descendants(repo, subset, x)
612
612
613 def _firstdescendants(repo, subset, x):
613 def _firstdescendants(repo, subset, x):
614 # ``_firstdescendants(set)``
614 # ``_firstdescendants(set)``
615 # Like ``descendants(set)`` but follows only the first parents.
615 # Like ``descendants(set)`` but follows only the first parents.
616 return _descendants(repo, subset, x, followfirst=True)
616 return _descendants(repo, subset, x, followfirst=True)
617
617
618 def destination(repo, subset, x):
618 def destination(repo, subset, x):
619 """``destination([set])``
619 """``destination([set])``
620 Changesets that were created by a graft, transplant or rebase operation,
620 Changesets that were created by a graft, transplant or rebase operation,
621 with the given revisions specified as the source. Omitting the optional set
621 with the given revisions specified as the source. Omitting the optional set
622 is the same as passing all().
622 is the same as passing all().
623 """
623 """
624 if x is not None:
624 if x is not None:
625 args = getset(repo, spanset(repo), x).set()
625 args = getset(repo, spanset(repo), x).set()
626 else:
626 else:
627 args = getall(repo, spanset(repo), x).set()
627 args = getall(repo, spanset(repo), x).set()
628
628
629 dests = set()
629 dests = set()
630
630
631 # subset contains all of the possible destinations that can be returned, so
631 # subset contains all of the possible destinations that can be returned, so
632 # iterate over them and see if their source(s) were provided in the args.
632 # iterate over them and see if their source(s) were provided in the args.
633 # Even if the immediate src of r is not in the args, src's source (or
633 # Even if the immediate src of r is not in the args, src's source (or
634 # further back) may be. Scanning back further than the immediate src allows
634 # further back) may be. Scanning back further than the immediate src allows
635 # transitive transplants and rebases to yield the same results as transitive
635 # transitive transplants and rebases to yield the same results as transitive
636 # grafts.
636 # grafts.
637 for r in subset:
637 for r in subset:
638 src = _getrevsource(repo, r)
638 src = _getrevsource(repo, r)
639 lineage = None
639 lineage = None
640
640
641 while src is not None:
641 while src is not None:
642 if lineage is None:
642 if lineage is None:
643 lineage = list()
643 lineage = list()
644
644
645 lineage.append(r)
645 lineage.append(r)
646
646
647 # The visited lineage is a match if the current source is in the arg
647 # The visited lineage is a match if the current source is in the arg
648 # set. Since every candidate dest is visited by way of iterating
648 # set. Since every candidate dest is visited by way of iterating
649 # subset, any dests further back in the lineage will be tested by a
649 # subset, any dests further back in the lineage will be tested by a
650 # different iteration over subset. Likewise, if the src was already
650 # different iteration over subset. Likewise, if the src was already
651 # selected, the current lineage can be selected without going back
651 # selected, the current lineage can be selected without going back
652 # further.
652 # further.
653 if src in args or src in dests:
653 if src in args or src in dests:
654 dests.update(lineage)
654 dests.update(lineage)
655 break
655 break
656
656
657 r = src
657 r = src
658 src = _getrevsource(repo, r)
658 src = _getrevsource(repo, r)
659
659
660 return baseset([r for r in subset if r in dests])
660 return baseset([r for r in subset if r in dests])
661
661
662 def divergent(repo, subset, x):
662 def divergent(repo, subset, x):
663 """``divergent()``
663 """``divergent()``
664 Final successors of changesets with an alternative set of final successors.
664 Final successors of changesets with an alternative set of final successors.
665 """
665 """
666 # i18n: "divergent" is a keyword
666 # i18n: "divergent" is a keyword
667 getargs(x, 0, 0, _("divergent takes no arguments"))
667 getargs(x, 0, 0, _("divergent takes no arguments"))
668 divergent = obsmod.getrevs(repo, 'divergent')
668 divergent = obsmod.getrevs(repo, 'divergent')
669 return baseset([r for r in subset if r in divergent])
669 return baseset([r for r in subset if r in divergent])
670
670
671 def draft(repo, subset, x):
671 def draft(repo, subset, x):
672 """``draft()``
672 """``draft()``
673 Changeset in draft phase."""
673 Changeset in draft phase."""
674 # i18n: "draft" is a keyword
674 # i18n: "draft" is a keyword
675 getargs(x, 0, 0, _("draft takes no arguments"))
675 getargs(x, 0, 0, _("draft takes no arguments"))
676 pc = repo._phasecache
676 pc = repo._phasecache
677 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.draft)
677 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.draft)
678
678
679 def extinct(repo, subset, x):
679 def extinct(repo, subset, x):
680 """``extinct()``
680 """``extinct()``
681 Obsolete changesets with obsolete descendants only.
681 Obsolete changesets with obsolete descendants only.
682 """
682 """
683 # i18n: "extinct" is a keyword
683 # i18n: "extinct" is a keyword
684 getargs(x, 0, 0, _("extinct takes no arguments"))
684 getargs(x, 0, 0, _("extinct takes no arguments"))
685 extincts = obsmod.getrevs(repo, 'extinct')
685 extincts = obsmod.getrevs(repo, 'extinct')
686 return subset & extincts
686 return subset & extincts
687
687
688 def extra(repo, subset, x):
688 def extra(repo, subset, x):
689 """``extra(label, [value])``
689 """``extra(label, [value])``
690 Changesets with the given label in the extra metadata, with the given
690 Changesets with the given label in the extra metadata, with the given
691 optional value.
691 optional value.
692
692
693 If `value` starts with `re:`, the remainder of the value is treated as
693 If `value` starts with `re:`, the remainder of the value is treated as
694 a regular expression. To match a value that actually starts with `re:`,
694 a regular expression. To match a value that actually starts with `re:`,
695 use the prefix `literal:`.
695 use the prefix `literal:`.
696 """
696 """
697
697
698 # i18n: "extra" is a keyword
698 # i18n: "extra" is a keyword
699 l = getargs(x, 1, 2, _('extra takes at least 1 and at most 2 arguments'))
699 l = getargs(x, 1, 2, _('extra takes at least 1 and at most 2 arguments'))
700 # i18n: "extra" is a keyword
700 # i18n: "extra" is a keyword
701 label = getstring(l[0], _('first argument to extra must be a string'))
701 label = getstring(l[0], _('first argument to extra must be a string'))
702 value = None
702 value = None
703
703
704 if len(l) > 1:
704 if len(l) > 1:
705 # i18n: "extra" is a keyword
705 # i18n: "extra" is a keyword
706 value = getstring(l[1], _('second argument to extra must be a string'))
706 value = getstring(l[1], _('second argument to extra must be a string'))
707 kind, value, matcher = _stringmatcher(value)
707 kind, value, matcher = _stringmatcher(value)
708
708
709 def _matchvalue(r):
709 def _matchvalue(r):
710 extra = repo[r].extra()
710 extra = repo[r].extra()
711 return label in extra and (value is None or matcher(extra[label]))
711 return label in extra and (value is None or matcher(extra[label]))
712
712
713 return lazyset(subset, lambda r: _matchvalue(r))
713 return lazyset(subset, lambda r: _matchvalue(r))
714
714
715 def filelog(repo, subset, x):
715 def filelog(repo, subset, x):
716 """``filelog(pattern)``
716 """``filelog(pattern)``
717 Changesets connected to the specified filelog.
717 Changesets connected to the specified filelog.
718
718
719 For performance reasons, ``filelog()`` does not show every changeset
719 For performance reasons, ``filelog()`` does not show every changeset
720 that affects the requested file(s). See :hg:`help log` for details. For
720 that affects the requested file(s). See :hg:`help log` for details. For
721 a slower, more accurate result, use ``file()``.
721 a slower, more accurate result, use ``file()``.
722
722
723 The pattern without explicit kind like ``glob:`` is expected to be
723 The pattern without explicit kind like ``glob:`` is expected to be
724 relative to the current directory and match against a file exactly
724 relative to the current directory and match against a file exactly
725 for efficiency.
725 for efficiency.
726 """
726 """
727
727
728 # i18n: "filelog" is a keyword
728 # i18n: "filelog" is a keyword
729 pat = getstring(x, _("filelog requires a pattern"))
729 pat = getstring(x, _("filelog requires a pattern"))
730 s = set()
730 s = set()
731
731
732 if not matchmod.patkind(pat):
732 if not matchmod.patkind(pat):
733 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
733 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
734 fl = repo.file(f)
734 fl = repo.file(f)
735 for fr in fl:
735 for fr in fl:
736 s.add(fl.linkrev(fr))
736 s.add(fl.linkrev(fr))
737 else:
737 else:
738 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
738 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
739 for f in repo[None]:
739 for f in repo[None]:
740 if m(f):
740 if m(f):
741 fl = repo.file(f)
741 fl = repo.file(f)
742 for fr in fl:
742 for fr in fl:
743 s.add(fl.linkrev(fr))
743 s.add(fl.linkrev(fr))
744
744
745 return baseset([r for r in subset if r in s])
745 return baseset([r for r in subset if r in s])
746
746
747 def first(repo, subset, x):
747 def first(repo, subset, x):
748 """``first(set, [n])``
748 """``first(set, [n])``
749 An alias for limit().
749 An alias for limit().
750 """
750 """
751 return limit(repo, subset, x)
751 return limit(repo, subset, x)
752
752
753 def _follow(repo, subset, x, name, followfirst=False):
753 def _follow(repo, subset, x, name, followfirst=False):
754 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
754 l = getargs(x, 0, 1, _("%s takes no arguments or a filename") % name)
755 c = repo['.']
755 c = repo['.']
756 if l:
756 if l:
757 x = getstring(l[0], _("%s expected a filename") % name)
757 x = getstring(l[0], _("%s expected a filename") % name)
758 if x in c:
758 if x in c:
759 cx = c[x]
759 cx = c[x]
760 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
760 s = set(ctx.rev() for ctx in cx.ancestors(followfirst=followfirst))
761 # include the revision responsible for the most recent version
761 # include the revision responsible for the most recent version
762 s.add(cx.linkrev())
762 s.add(cx.linkrev())
763 else:
763 else:
764 return baseset([])
764 return baseset([])
765 else:
765 else:
766 s = set(_revancestors(repo, [c.rev()], followfirst)) | set([c.rev()])
766 s = set(_revancestors(repo, [c.rev()], followfirst)) | set([c.rev()])
767
767
768 return baseset([r for r in subset if r in s])
768 return baseset([r for r in subset if r in s])
769
769
770 def follow(repo, subset, x):
770 def follow(repo, subset, x):
771 """``follow([file])``
771 """``follow([file])``
772 An alias for ``::.`` (ancestors of the working copy's first parent).
772 An alias for ``::.`` (ancestors of the working copy's first parent).
773 If a filename is specified, the history of the given file is followed,
773 If a filename is specified, the history of the given file is followed,
774 including copies.
774 including copies.
775 """
775 """
776 return _follow(repo, subset, x, 'follow')
776 return _follow(repo, subset, x, 'follow')
777
777
778 def _followfirst(repo, subset, x):
778 def _followfirst(repo, subset, x):
779 # ``followfirst([file])``
779 # ``followfirst([file])``
780 # Like ``follow([file])`` but follows only the first parent of
780 # Like ``follow([file])`` but follows only the first parent of
781 # every revision or file revision.
781 # every revision or file revision.
782 return _follow(repo, subset, x, '_followfirst', followfirst=True)
782 return _follow(repo, subset, x, '_followfirst', followfirst=True)
783
783
784 def getall(repo, subset, x):
784 def getall(repo, subset, x):
785 """``all()``
785 """``all()``
786 All changesets, the same as ``0:tip``.
786 All changesets, the same as ``0:tip``.
787 """
787 """
788 # i18n: "all" is a keyword
788 # i18n: "all" is a keyword
789 getargs(x, 0, 0, _("all takes no arguments"))
789 getargs(x, 0, 0, _("all takes no arguments"))
790 return subset
790 return subset
791
791
792 def grep(repo, subset, x):
792 def grep(repo, subset, x):
793 """``grep(regex)``
793 """``grep(regex)``
794 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
794 Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
795 to ensure special escape characters are handled correctly. Unlike
795 to ensure special escape characters are handled correctly. Unlike
796 ``keyword(string)``, the match is case-sensitive.
796 ``keyword(string)``, the match is case-sensitive.
797 """
797 """
798 try:
798 try:
799 # i18n: "grep" is a keyword
799 # i18n: "grep" is a keyword
800 gr = re.compile(getstring(x, _("grep requires a string")))
800 gr = re.compile(getstring(x, _("grep requires a string")))
801 except re.error, e:
801 except re.error, e:
802 raise error.ParseError(_('invalid match pattern: %s') % e)
802 raise error.ParseError(_('invalid match pattern: %s') % e)
803
803
804 def matches(x):
804 def matches(x):
805 c = repo[x]
805 c = repo[x]
806 for e in c.files() + [c.user(), c.description()]:
806 for e in c.files() + [c.user(), c.description()]:
807 if gr.search(e):
807 if gr.search(e):
808 return True
808 return True
809 return False
809 return False
810
810
811 return lazyset(subset, matches)
811 return lazyset(subset, matches)
812
812
813 def _matchfiles(repo, subset, x):
813 def _matchfiles(repo, subset, x):
814 # _matchfiles takes a revset list of prefixed arguments:
814 # _matchfiles takes a revset list of prefixed arguments:
815 #
815 #
816 # [p:foo, i:bar, x:baz]
816 # [p:foo, i:bar, x:baz]
817 #
817 #
818 # builds a match object from them and filters subset. Allowed
818 # builds a match object from them and filters subset. Allowed
819 # prefixes are 'p:' for regular patterns, 'i:' for include
819 # prefixes are 'p:' for regular patterns, 'i:' for include
820 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
820 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
821 # a revision identifier, or the empty string to reference the
821 # a revision identifier, or the empty string to reference the
822 # working directory, from which the match object is
822 # working directory, from which the match object is
823 # initialized. Use 'd:' to set the default matching mode, default
823 # initialized. Use 'd:' to set the default matching mode, default
824 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
824 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
825
825
826 # i18n: "_matchfiles" is a keyword
826 # i18n: "_matchfiles" is a keyword
827 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
827 l = getargs(x, 1, -1, _("_matchfiles requires at least one argument"))
828 pats, inc, exc = [], [], []
828 pats, inc, exc = [], [], []
829 hasset = False
829 hasset = False
830 rev, default = None, None
830 rev, default = None, None
831 for arg in l:
831 for arg in l:
832 # i18n: "_matchfiles" is a keyword
832 # i18n: "_matchfiles" is a keyword
833 s = getstring(arg, _("_matchfiles requires string arguments"))
833 s = getstring(arg, _("_matchfiles requires string arguments"))
834 prefix, value = s[:2], s[2:]
834 prefix, value = s[:2], s[2:]
835 if prefix == 'p:':
835 if prefix == 'p:':
836 pats.append(value)
836 pats.append(value)
837 elif prefix == 'i:':
837 elif prefix == 'i:':
838 inc.append(value)
838 inc.append(value)
839 elif prefix == 'x:':
839 elif prefix == 'x:':
840 exc.append(value)
840 exc.append(value)
841 elif prefix == 'r:':
841 elif prefix == 'r:':
842 if rev is not None:
842 if rev is not None:
843 # i18n: "_matchfiles" is a keyword
843 # i18n: "_matchfiles" is a keyword
844 raise error.ParseError(_('_matchfiles expected at most one '
844 raise error.ParseError(_('_matchfiles expected at most one '
845 'revision'))
845 'revision'))
846 rev = value
846 rev = value
847 elif prefix == 'd:':
847 elif prefix == 'd:':
848 if default is not None:
848 if default is not None:
849 # i18n: "_matchfiles" is a keyword
849 # i18n: "_matchfiles" is a keyword
850 raise error.ParseError(_('_matchfiles expected at most one '
850 raise error.ParseError(_('_matchfiles expected at most one '
851 'default mode'))
851 'default mode'))
852 default = value
852 default = value
853 else:
853 else:
854 # i18n: "_matchfiles" is a keyword
854 # i18n: "_matchfiles" is a keyword
855 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
855 raise error.ParseError(_('invalid _matchfiles prefix: %s') % prefix)
856 if not hasset and matchmod.patkind(value) == 'set':
856 if not hasset and matchmod.patkind(value) == 'set':
857 hasset = True
857 hasset = True
858 if not default:
858 if not default:
859 default = 'glob'
859 default = 'glob'
860
860
861 def matches(x):
861 def matches(x):
862 m = None
862 m = None
863 c = repo[x]
863 c = repo[x]
864 if not m or (hasset and rev is None):
864 if not m or (hasset and rev is None):
865 ctx = c
865 ctx = c
866 if rev is not None:
866 if rev is not None:
867 ctx = repo[rev or None]
867 ctx = repo[rev or None]
868 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
868 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
869 exclude=exc, ctx=ctx, default=default)
869 exclude=exc, ctx=ctx, default=default)
870 for f in c.files():
870 for f in c.files():
871 if m(f):
871 if m(f):
872 return True
872 return True
873 return False
873 return False
874
874
875 return lazyset(subset, matches)
875 return lazyset(subset, matches)
876
876
877 def hasfile(repo, subset, x):
877 def hasfile(repo, subset, x):
878 """``file(pattern)``
878 """``file(pattern)``
879 Changesets affecting files matched by pattern.
879 Changesets affecting files matched by pattern.
880
880
881 For a faster but less accurate result, consider using ``filelog()``
881 For a faster but less accurate result, consider using ``filelog()``
882 instead.
882 instead.
883
883
884 This predicate uses ``glob:`` as the default kind of pattern.
884 This predicate uses ``glob:`` as the default kind of pattern.
885 """
885 """
886 # i18n: "file" is a keyword
886 # i18n: "file" is a keyword
887 pat = getstring(x, _("file requires a pattern"))
887 pat = getstring(x, _("file requires a pattern"))
888 return _matchfiles(repo, subset, ('string', 'p:' + pat))
888 return _matchfiles(repo, subset, ('string', 'p:' + pat))
889
889
890 def head(repo, subset, x):
890 def head(repo, subset, x):
891 """``head()``
891 """``head()``
892 Changeset is a named branch head.
892 Changeset is a named branch head.
893 """
893 """
894 # i18n: "head" is a keyword
894 # i18n: "head" is a keyword
895 getargs(x, 0, 0, _("head takes no arguments"))
895 getargs(x, 0, 0, _("head takes no arguments"))
896 hs = set()
896 hs = set()
897 for b, ls in repo.branchmap().iteritems():
897 for b, ls in repo.branchmap().iteritems():
898 hs.update(repo[h].rev() for h in ls)
898 hs.update(repo[h].rev() for h in ls)
899 return baseset([r for r in subset if r in hs])
899 return baseset([r for r in subset if r in hs])
900
900
901 def heads(repo, subset, x):
901 def heads(repo, subset, x):
902 """``heads(set)``
902 """``heads(set)``
903 Members of set with no children in set.
903 Members of set with no children in set.
904 """
904 """
905 s = getset(repo, subset, x)
905 s = getset(repo, subset, x)
906 ps = parents(repo, subset, x)
906 ps = parents(repo, subset, x)
907 return s - ps
907 return s - ps
908
908
909 def hidden(repo, subset, x):
909 def hidden(repo, subset, x):
910 """``hidden()``
910 """``hidden()``
911 Hidden changesets.
911 Hidden changesets.
912 """
912 """
913 # i18n: "hidden" is a keyword
913 # i18n: "hidden" is a keyword
914 getargs(x, 0, 0, _("hidden takes no arguments"))
914 getargs(x, 0, 0, _("hidden takes no arguments"))
915 hiddenrevs = repoview.filterrevs(repo, 'visible')
915 hiddenrevs = repoview.filterrevs(repo, 'visible')
916 return subset & hiddenrevs
916 return subset & hiddenrevs
917
917
918 def keyword(repo, subset, x):
918 def keyword(repo, subset, x):
919 """``keyword(string)``
919 """``keyword(string)``
920 Search commit message, user name, and names of changed files for
920 Search commit message, user name, and names of changed files for
921 string. The match is case-insensitive.
921 string. The match is case-insensitive.
922 """
922 """
923 # i18n: "keyword" is a keyword
923 # i18n: "keyword" is a keyword
924 kw = encoding.lower(getstring(x, _("keyword requires a string")))
924 kw = encoding.lower(getstring(x, _("keyword requires a string")))
925
925
926 def matches(r):
926 def matches(r):
927 c = repo[r]
927 c = repo[r]
928 return util.any(kw in encoding.lower(t) for t in c.files() + [c.user(),
928 return util.any(kw in encoding.lower(t) for t in c.files() + [c.user(),
929 c.description()])
929 c.description()])
930
930
931 return lazyset(subset, matches)
931 return lazyset(subset, matches)
932
932
933 def limit(repo, subset, x):
933 def limit(repo, subset, x):
934 """``limit(set, [n])``
934 """``limit(set, [n])``
935 First n members of set, defaulting to 1.
935 First n members of set, defaulting to 1.
936 """
936 """
937 # i18n: "limit" is a keyword
937 # i18n: "limit" is a keyword
938 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
938 l = getargs(x, 1, 2, _("limit requires one or two arguments"))
939 try:
939 try:
940 lim = 1
940 lim = 1
941 if len(l) == 2:
941 if len(l) == 2:
942 # i18n: "limit" is a keyword
942 # i18n: "limit" is a keyword
943 lim = int(getstring(l[1], _("limit requires a number")))
943 lim = int(getstring(l[1], _("limit requires a number")))
944 except (TypeError, ValueError):
944 except (TypeError, ValueError):
945 # i18n: "limit" is a keyword
945 # i18n: "limit" is a keyword
946 raise error.ParseError(_("limit expects a number"))
946 raise error.ParseError(_("limit expects a number"))
947 ss = subset.set()
947 ss = subset.set()
948 os = getset(repo, spanset(repo), l[0])
948 os = getset(repo, spanset(repo), l[0])
949 bs = baseset([])
949 bs = baseset([])
950 it = iter(os)
950 it = iter(os)
951 for x in xrange(lim):
951 for x in xrange(lim):
952 try:
952 try:
953 y = it.next()
953 y = it.next()
954 if y in ss:
954 if y in ss:
955 bs.append(y)
955 bs.append(y)
956 except (StopIteration):
956 except (StopIteration):
957 break
957 break
958 return bs
958 return bs
959
959
960 def last(repo, subset, x):
960 def last(repo, subset, x):
961 """``last(set, [n])``
961 """``last(set, [n])``
962 Last n members of set, defaulting to 1.
962 Last n members of set, defaulting to 1.
963 """
963 """
964 # i18n: "last" is a keyword
964 # i18n: "last" is a keyword
965 l = getargs(x, 1, 2, _("last requires one or two arguments"))
965 l = getargs(x, 1, 2, _("last requires one or two arguments"))
966 try:
966 try:
967 lim = 1
967 lim = 1
968 if len(l) == 2:
968 if len(l) == 2:
969 # i18n: "last" is a keyword
969 # i18n: "last" is a keyword
970 lim = int(getstring(l[1], _("last requires a number")))
970 lim = int(getstring(l[1], _("last requires a number")))
971 except (TypeError, ValueError):
971 except (TypeError, ValueError):
972 # i18n: "last" is a keyword
972 # i18n: "last" is a keyword
973 raise error.ParseError(_("last expects a number"))
973 raise error.ParseError(_("last expects a number"))
974 ss = subset.set()
974 ss = subset.set()
975 os = getset(repo, spanset(repo), l[0])
975 os = getset(repo, spanset(repo), l[0])
976 os.reverse()
976 os.reverse()
977 bs = baseset([])
977 bs = baseset([])
978 it = iter(os)
978 it = iter(os)
979 for x in xrange(lim):
979 for x in xrange(lim):
980 try:
980 try:
981 y = it.next()
981 y = it.next()
982 if y in ss:
982 if y in ss:
983 bs.append(y)
983 bs.append(y)
984 except (StopIteration):
984 except (StopIteration):
985 break
985 break
986 return bs
986 return bs
987
987
988 def maxrev(repo, subset, x):
988 def maxrev(repo, subset, x):
989 """``max(set)``
989 """``max(set)``
990 Changeset with highest revision number in set.
990 Changeset with highest revision number in set.
991 """
991 """
992 os = getset(repo, spanset(repo), x)
992 os = getset(repo, spanset(repo), x)
993 if os:
993 if os:
994 m = max(os)
994 m = max(os)
995 if m in subset:
995 if m in subset:
996 return baseset([m])
996 return baseset([m])
997 return baseset([])
997 return baseset([])
998
998
999 def merge(repo, subset, x):
999 def merge(repo, subset, x):
1000 """``merge()``
1000 """``merge()``
1001 Changeset is a merge changeset.
1001 Changeset is a merge changeset.
1002 """
1002 """
1003 # i18n: "merge" is a keyword
1003 # i18n: "merge" is a keyword
1004 getargs(x, 0, 0, _("merge takes no arguments"))
1004 getargs(x, 0, 0, _("merge takes no arguments"))
1005 cl = repo.changelog
1005 cl = repo.changelog
1006 return lazyset(subset, lambda r: cl.parentrevs(r)[1] != -1)
1006 return lazyset(subset, lambda r: cl.parentrevs(r)[1] != -1)
1007
1007
1008 def branchpoint(repo, subset, x):
1008 def branchpoint(repo, subset, x):
1009 """``branchpoint()``
1009 """``branchpoint()``
1010 Changesets with more than one child.
1010 Changesets with more than one child.
1011 """
1011 """
1012 # i18n: "branchpoint" is a keyword
1012 # i18n: "branchpoint" is a keyword
1013 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1013 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1014 cl = repo.changelog
1014 cl = repo.changelog
1015 if not subset:
1015 if not subset:
1016 return baseset([])
1016 return baseset([])
1017 baserev = min(subset)
1017 baserev = min(subset)
1018 parentscount = [0]*(len(repo) - baserev)
1018 parentscount = [0]*(len(repo) - baserev)
1019 for r in cl.revs(start=baserev + 1):
1019 for r in cl.revs(start=baserev + 1):
1020 for p in cl.parentrevs(r):
1020 for p in cl.parentrevs(r):
1021 if p >= baserev:
1021 if p >= baserev:
1022 parentscount[p - baserev] += 1
1022 parentscount[p - baserev] += 1
1023 return baseset([r for r in subset if (parentscount[r - baserev] > 1)])
1023 return baseset([r for r in subset if (parentscount[r - baserev] > 1)])
1024
1024
1025 def minrev(repo, subset, x):
1025 def minrev(repo, subset, x):
1026 """``min(set)``
1026 """``min(set)``
1027 Changeset with lowest revision number in set.
1027 Changeset with lowest revision number in set.
1028 """
1028 """
1029 os = getset(repo, spanset(repo), x)
1029 os = getset(repo, spanset(repo), x)
1030 if os:
1030 if os:
1031 m = min(os)
1031 m = min(os)
1032 if m in subset:
1032 if m in subset:
1033 return baseset([m])
1033 return baseset([m])
1034 return baseset([])
1034 return baseset([])
1035
1035
1036 def _missingancestors(repo, subset, x):
1036 def _missingancestors(repo, subset, x):
1037 # i18n: "_missingancestors" is a keyword
1037 # i18n: "_missingancestors" is a keyword
1038 revs, bases = getargs(x, 2, 2,
1038 revs, bases = getargs(x, 2, 2,
1039 _("_missingancestors requires two arguments"))
1039 _("_missingancestors requires two arguments"))
1040 rs = baseset(repo)
1040 rs = baseset(repo)
1041 revs = getset(repo, rs, revs)
1041 revs = getset(repo, rs, revs)
1042 bases = getset(repo, rs, bases)
1042 bases = getset(repo, rs, bases)
1043 missing = set(repo.changelog.findmissingrevs(bases, revs))
1043 missing = set(repo.changelog.findmissingrevs(bases, revs))
1044 return baseset([r for r in subset if r in missing])
1044 return baseset([r for r in subset if r in missing])
1045
1045
1046 def modifies(repo, subset, x):
1046 def modifies(repo, subset, x):
1047 """``modifies(pattern)``
1047 """``modifies(pattern)``
1048 Changesets modifying files matched by pattern.
1048 Changesets modifying files matched by pattern.
1049
1049
1050 The pattern without explicit kind like ``glob:`` is expected to be
1050 The pattern without explicit kind like ``glob:`` is expected to be
1051 relative to the current directory and match against a file or a
1051 relative to the current directory and match against a file or a
1052 directory.
1052 directory.
1053 """
1053 """
1054 # i18n: "modifies" is a keyword
1054 # i18n: "modifies" is a keyword
1055 pat = getstring(x, _("modifies requires a pattern"))
1055 pat = getstring(x, _("modifies requires a pattern"))
1056 return checkstatus(repo, subset, pat, 0)
1056 return checkstatus(repo, subset, pat, 0)
1057
1057
1058 def node_(repo, subset, x):
1058 def node_(repo, subset, x):
1059 """``id(string)``
1059 """``id(string)``
1060 Revision non-ambiguously specified by the given hex string prefix.
1060 Revision non-ambiguously specified by the given hex string prefix.
1061 """
1061 """
1062 # i18n: "id" is a keyword
1062 # i18n: "id" is a keyword
1063 l = getargs(x, 1, 1, _("id requires one argument"))
1063 l = getargs(x, 1, 1, _("id requires one argument"))
1064 # i18n: "id" is a keyword
1064 # i18n: "id" is a keyword
1065 n = getstring(l[0], _("id requires a string"))
1065 n = getstring(l[0], _("id requires a string"))
1066 if len(n) == 40:
1066 if len(n) == 40:
1067 rn = repo[n].rev()
1067 rn = repo[n].rev()
1068 else:
1068 else:
1069 rn = None
1069 rn = None
1070 pm = repo.changelog._partialmatch(n)
1070 pm = repo.changelog._partialmatch(n)
1071 if pm is not None:
1071 if pm is not None:
1072 rn = repo.changelog.rev(pm)
1072 rn = repo.changelog.rev(pm)
1073
1073
1074 return baseset([r for r in subset if r == rn])
1074 return baseset([r for r in subset if r == rn])
1075
1075
1076 def obsolete(repo, subset, x):
1076 def obsolete(repo, subset, x):
1077 """``obsolete()``
1077 """``obsolete()``
1078 Mutable changeset with a newer version."""
1078 Mutable changeset with a newer version."""
1079 # i18n: "obsolete" is a keyword
1079 # i18n: "obsolete" is a keyword
1080 getargs(x, 0, 0, _("obsolete takes no arguments"))
1080 getargs(x, 0, 0, _("obsolete takes no arguments"))
1081 obsoletes = obsmod.getrevs(repo, 'obsolete')
1081 obsoletes = obsmod.getrevs(repo, 'obsolete')
1082 return subset & obsoletes
1082 return subset & obsoletes
1083
1083
1084 def origin(repo, subset, x):
1084 def origin(repo, subset, x):
1085 """``origin([set])``
1085 """``origin([set])``
1086 Changesets that were specified as a source for the grafts, transplants or
1086 Changesets that were specified as a source for the grafts, transplants or
1087 rebases that created the given revisions. Omitting the optional set is the
1087 rebases that created the given revisions. Omitting the optional set is the
1088 same as passing all(). If a changeset created by these operations is itself
1088 same as passing all(). If a changeset created by these operations is itself
1089 specified as a source for one of these operations, only the source changeset
1089 specified as a source for one of these operations, only the source changeset
1090 for the first operation is selected.
1090 for the first operation is selected.
1091 """
1091 """
1092 if x is not None:
1092 if x is not None:
1093 args = getset(repo, spanset(repo), x).set()
1093 args = getset(repo, spanset(repo), x).set()
1094 else:
1094 else:
1095 args = getall(repo, spanset(repo), x).set()
1095 args = getall(repo, spanset(repo), x).set()
1096
1096
1097 def _firstsrc(rev):
1097 def _firstsrc(rev):
1098 src = _getrevsource(repo, rev)
1098 src = _getrevsource(repo, rev)
1099 if src is None:
1099 if src is None:
1100 return None
1100 return None
1101
1101
1102 while True:
1102 while True:
1103 prev = _getrevsource(repo, src)
1103 prev = _getrevsource(repo, src)
1104
1104
1105 if prev is None:
1105 if prev is None:
1106 return src
1106 return src
1107 src = prev
1107 src = prev
1108
1108
1109 o = set([_firstsrc(r) for r in args])
1109 o = set([_firstsrc(r) for r in args])
1110 return baseset([r for r in subset if r in o])
1110 return baseset([r for r in subset if r in o])
1111
1111
1112 def outgoing(repo, subset, x):
1112 def outgoing(repo, subset, x):
1113 """``outgoing([path])``
1113 """``outgoing([path])``
1114 Changesets not found in the specified destination repository, or the
1114 Changesets not found in the specified destination repository, or the
1115 default push location.
1115 default push location.
1116 """
1116 """
1117 import hg # avoid start-up nasties
1117 import hg # avoid start-up nasties
1118 # i18n: "outgoing" is a keyword
1118 # i18n: "outgoing" is a keyword
1119 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1119 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1120 # i18n: "outgoing" is a keyword
1120 # i18n: "outgoing" is a keyword
1121 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1121 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1122 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1122 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1123 dest, branches = hg.parseurl(dest)
1123 dest, branches = hg.parseurl(dest)
1124 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1124 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1125 if revs:
1125 if revs:
1126 revs = [repo.lookup(rev) for rev in revs]
1126 revs = [repo.lookup(rev) for rev in revs]
1127 other = hg.peer(repo, {}, dest)
1127 other = hg.peer(repo, {}, dest)
1128 repo.ui.pushbuffer()
1128 repo.ui.pushbuffer()
1129 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1129 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1130 repo.ui.popbuffer()
1130 repo.ui.popbuffer()
1131 cl = repo.changelog
1131 cl = repo.changelog
1132 o = set([cl.rev(r) for r in outgoing.missing])
1132 o = set([cl.rev(r) for r in outgoing.missing])
1133 return baseset([r for r in subset if r in o])
1133 return baseset([r for r in subset if r in o])
1134
1134
1135 def p1(repo, subset, x):
1135 def p1(repo, subset, x):
1136 """``p1([set])``
1136 """``p1([set])``
1137 First parent of changesets in set, or the working directory.
1137 First parent of changesets in set, or the working directory.
1138 """
1138 """
1139 if x is None:
1139 if x is None:
1140 p = repo[x].p1().rev()
1140 p = repo[x].p1().rev()
1141 return baseset([r for r in subset if r == p])
1141 return baseset([r for r in subset if r == p])
1142
1142
1143 ps = set()
1143 ps = set()
1144 cl = repo.changelog
1144 cl = repo.changelog
1145 for r in getset(repo, spanset(repo), x):
1145 for r in getset(repo, spanset(repo), x):
1146 ps.add(cl.parentrevs(r)[0])
1146 ps.add(cl.parentrevs(r)[0])
1147 return subset & ps
1147 return subset & ps
1148
1148
1149 def p2(repo, subset, x):
1149 def p2(repo, subset, x):
1150 """``p2([set])``
1150 """``p2([set])``
1151 Second parent of changesets in set, or the working directory.
1151 Second parent of changesets in set, or the working directory.
1152 """
1152 """
1153 if x is None:
1153 if x is None:
1154 ps = repo[x].parents()
1154 ps = repo[x].parents()
1155 try:
1155 try:
1156 p = ps[1].rev()
1156 p = ps[1].rev()
1157 return baseset([r for r in subset if r == p])
1157 return baseset([r for r in subset if r == p])
1158 except IndexError:
1158 except IndexError:
1159 return baseset([])
1159 return baseset([])
1160
1160
1161 ps = set()
1161 ps = set()
1162 cl = repo.changelog
1162 cl = repo.changelog
1163 for r in getset(repo, spanset(repo), x):
1163 for r in getset(repo, spanset(repo), x):
1164 ps.add(cl.parentrevs(r)[1])
1164 ps.add(cl.parentrevs(r)[1])
1165 return subset & ps
1165 return subset & ps
1166
1166
1167 def parents(repo, subset, x):
1167 def parents(repo, subset, x):
1168 """``parents([set])``
1168 """``parents([set])``
1169 The set of all parents for all changesets in set, or the working directory.
1169 The set of all parents for all changesets in set, or the working directory.
1170 """
1170 """
1171 if x is None:
1171 if x is None:
1172 ps = tuple(p.rev() for p in repo[x].parents())
1172 ps = tuple(p.rev() for p in repo[x].parents())
1173 return subset & ps
1173 return subset & ps
1174
1174
1175 ps = set()
1175 ps = set()
1176 cl = repo.changelog
1176 cl = repo.changelog
1177 for r in getset(repo, spanset(repo), x):
1177 for r in getset(repo, spanset(repo), x):
1178 ps.update(cl.parentrevs(r))
1178 ps.update(cl.parentrevs(r))
1179 return subset & ps
1179 return subset & ps
1180
1180
1181 def parentspec(repo, subset, x, n):
1181 def parentspec(repo, subset, x, n):
1182 """``set^0``
1182 """``set^0``
1183 The set.
1183 The set.
1184 ``set^1`` (or ``set^``), ``set^2``
1184 ``set^1`` (or ``set^``), ``set^2``
1185 First or second parent, respectively, of all changesets in set.
1185 First or second parent, respectively, of all changesets in set.
1186 """
1186 """
1187 try:
1187 try:
1188 n = int(n[1])
1188 n = int(n[1])
1189 if n not in (0, 1, 2):
1189 if n not in (0, 1, 2):
1190 raise ValueError
1190 raise ValueError
1191 except (TypeError, ValueError):
1191 except (TypeError, ValueError):
1192 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1192 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1193 ps = set()
1193 ps = set()
1194 cl = repo.changelog
1194 cl = repo.changelog
1195 for r in getset(repo, baseset(cl), x):
1195 for r in getset(repo, baseset(cl), x):
1196 if n == 0:
1196 if n == 0:
1197 ps.add(r)
1197 ps.add(r)
1198 elif n == 1:
1198 elif n == 1:
1199 ps.add(cl.parentrevs(r)[0])
1199 ps.add(cl.parentrevs(r)[0])
1200 elif n == 2:
1200 elif n == 2:
1201 parents = cl.parentrevs(r)
1201 parents = cl.parentrevs(r)
1202 if len(parents) > 1:
1202 if len(parents) > 1:
1203 ps.add(parents[1])
1203 ps.add(parents[1])
1204 return subset & ps
1204 return subset & ps
1205
1205
1206 def present(repo, subset, x):
1206 def present(repo, subset, x):
1207 """``present(set)``
1207 """``present(set)``
1208 An empty set, if any revision in set isn't found; otherwise,
1208 An empty set, if any revision in set isn't found; otherwise,
1209 all revisions in set.
1209 all revisions in set.
1210
1210
1211 If any of specified revisions is not present in the local repository,
1211 If any of specified revisions is not present in the local repository,
1212 the query is normally aborted. But this predicate allows the query
1212 the query is normally aborted. But this predicate allows the query
1213 to continue even in such cases.
1213 to continue even in such cases.
1214 """
1214 """
1215 try:
1215 try:
1216 return getset(repo, subset, x)
1216 return getset(repo, subset, x)
1217 except error.RepoLookupError:
1217 except error.RepoLookupError:
1218 return baseset([])
1218 return baseset([])
1219
1219
1220 def public(repo, subset, x):
1220 def public(repo, subset, x):
1221 """``public()``
1221 """``public()``
1222 Changeset in public phase."""
1222 Changeset in public phase."""
1223 # i18n: "public" is a keyword
1223 # i18n: "public" is a keyword
1224 getargs(x, 0, 0, _("public takes no arguments"))
1224 getargs(x, 0, 0, _("public takes no arguments"))
1225 pc = repo._phasecache
1225 pc = repo._phasecache
1226 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.public)
1226 return lazyset(subset, lambda r: pc.phase(repo, r) == phases.public)
1227
1227
1228 def remote(repo, subset, x):
1228 def remote(repo, subset, x):
1229 """``remote([id [,path]])``
1229 """``remote([id [,path]])``
1230 Local revision that corresponds to the given identifier in a
1230 Local revision that corresponds to the given identifier in a
1231 remote repository, if present. Here, the '.' identifier is a
1231 remote repository, if present. Here, the '.' identifier is a
1232 synonym for the current local branch.
1232 synonym for the current local branch.
1233 """
1233 """
1234
1234
1235 import hg # avoid start-up nasties
1235 import hg # avoid start-up nasties
1236 # i18n: "remote" is a keyword
1236 # i18n: "remote" is a keyword
1237 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1237 l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))
1238
1238
1239 q = '.'
1239 q = '.'
1240 if len(l) > 0:
1240 if len(l) > 0:
1241 # i18n: "remote" is a keyword
1241 # i18n: "remote" is a keyword
1242 q = getstring(l[0], _("remote requires a string id"))
1242 q = getstring(l[0], _("remote requires a string id"))
1243 if q == '.':
1243 if q == '.':
1244 q = repo['.'].branch()
1244 q = repo['.'].branch()
1245
1245
1246 dest = ''
1246 dest = ''
1247 if len(l) > 1:
1247 if len(l) > 1:
1248 # i18n: "remote" is a keyword
1248 # i18n: "remote" is a keyword
1249 dest = getstring(l[1], _("remote requires a repository path"))
1249 dest = getstring(l[1], _("remote requires a repository path"))
1250 dest = repo.ui.expandpath(dest or 'default')
1250 dest = repo.ui.expandpath(dest or 'default')
1251 dest, branches = hg.parseurl(dest)
1251 dest, branches = hg.parseurl(dest)
1252 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1252 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1253 if revs:
1253 if revs:
1254 revs = [repo.lookup(rev) for rev in revs]
1254 revs = [repo.lookup(rev) for rev in revs]
1255 other = hg.peer(repo, {}, dest)
1255 other = hg.peer(repo, {}, dest)
1256 n = other.lookup(q)
1256 n = other.lookup(q)
1257 if n in repo:
1257 if n in repo:
1258 r = repo[n].rev()
1258 r = repo[n].rev()
1259 if r in subset:
1259 if r in subset:
1260 return baseset([r])
1260 return baseset([r])
1261 return baseset([])
1261 return baseset([])
1262
1262
1263 def removes(repo, subset, x):
1263 def removes(repo, subset, x):
1264 """``removes(pattern)``
1264 """``removes(pattern)``
1265 Changesets which remove files matching pattern.
1265 Changesets which remove files matching pattern.
1266
1266
1267 The pattern without explicit kind like ``glob:`` is expected to be
1267 The pattern without explicit kind like ``glob:`` is expected to be
1268 relative to the current directory and match against a file or a
1268 relative to the current directory and match against a file or a
1269 directory.
1269 directory.
1270 """
1270 """
1271 # i18n: "removes" is a keyword
1271 # i18n: "removes" is a keyword
1272 pat = getstring(x, _("removes requires a pattern"))
1272 pat = getstring(x, _("removes requires a pattern"))
1273 return checkstatus(repo, subset, pat, 2)
1273 return checkstatus(repo, subset, pat, 2)
1274
1274
1275 def rev(repo, subset, x):
1275 def rev(repo, subset, x):
1276 """``rev(number)``
1276 """``rev(number)``
1277 Revision with the given numeric identifier.
1277 Revision with the given numeric identifier.
1278 """
1278 """
1279 # i18n: "rev" is a keyword
1279 # i18n: "rev" is a keyword
1280 l = getargs(x, 1, 1, _("rev requires one argument"))
1280 l = getargs(x, 1, 1, _("rev requires one argument"))
1281 try:
1281 try:
1282 # i18n: "rev" is a keyword
1282 # i18n: "rev" is a keyword
1283 l = int(getstring(l[0], _("rev requires a number")))
1283 l = int(getstring(l[0], _("rev requires a number")))
1284 except (TypeError, ValueError):
1284 except (TypeError, ValueError):
1285 # i18n: "rev" is a keyword
1285 # i18n: "rev" is a keyword
1286 raise error.ParseError(_("rev expects a number"))
1286 raise error.ParseError(_("rev expects a number"))
1287 return baseset([r for r in subset if r == l])
1287 return baseset([r for r in subset if r == l])
1288
1288
1289 def matching(repo, subset, x):
1289 def matching(repo, subset, x):
1290 """``matching(revision [, field])``
1290 """``matching(revision [, field])``
1291 Changesets in which a given set of fields match the set of fields in the
1291 Changesets in which a given set of fields match the set of fields in the
1292 selected revision or set.
1292 selected revision or set.
1293
1293
1294 To match more than one field pass the list of fields to match separated
1294 To match more than one field pass the list of fields to match separated
1295 by spaces (e.g. ``author description``).
1295 by spaces (e.g. ``author description``).
1296
1296
1297 Valid fields are most regular revision fields and some special fields.
1297 Valid fields are most regular revision fields and some special fields.
1298
1298
1299 Regular revision fields are ``description``, ``author``, ``branch``,
1299 Regular revision fields are ``description``, ``author``, ``branch``,
1300 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1300 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1301 and ``diff``.
1301 and ``diff``.
1302 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1302 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1303 contents of the revision. Two revisions matching their ``diff`` will
1303 contents of the revision. Two revisions matching their ``diff`` will
1304 also match their ``files``.
1304 also match their ``files``.
1305
1305
1306 Special fields are ``summary`` and ``metadata``:
1306 Special fields are ``summary`` and ``metadata``:
1307 ``summary`` matches the first line of the description.
1307 ``summary`` matches the first line of the description.
1308 ``metadata`` is equivalent to matching ``description user date``
1308 ``metadata`` is equivalent to matching ``description user date``
1309 (i.e. it matches the main metadata fields).
1309 (i.e. it matches the main metadata fields).
1310
1310
1311 ``metadata`` is the default field which is used when no fields are
1311 ``metadata`` is the default field which is used when no fields are
1312 specified. You can match more than one field at a time.
1312 specified. You can match more than one field at a time.
1313 """
1313 """
1314 # i18n: "matching" is a keyword
1314 # i18n: "matching" is a keyword
1315 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1315 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1316
1316
1317 revs = getset(repo, baseset(repo.changelog), l[0])
1317 revs = getset(repo, baseset(repo.changelog), l[0])
1318
1318
1319 fieldlist = ['metadata']
1319 fieldlist = ['metadata']
1320 if len(l) > 1:
1320 if len(l) > 1:
1321 fieldlist = getstring(l[1],
1321 fieldlist = getstring(l[1],
1322 # i18n: "matching" is a keyword
1322 # i18n: "matching" is a keyword
1323 _("matching requires a string "
1323 _("matching requires a string "
1324 "as its second argument")).split()
1324 "as its second argument")).split()
1325
1325
1326 # Make sure that there are no repeated fields,
1326 # Make sure that there are no repeated fields,
1327 # expand the 'special' 'metadata' field type
1327 # expand the 'special' 'metadata' field type
1328 # and check the 'files' whenever we check the 'diff'
1328 # and check the 'files' whenever we check the 'diff'
1329 fields = []
1329 fields = []
1330 for field in fieldlist:
1330 for field in fieldlist:
1331 if field == 'metadata':
1331 if field == 'metadata':
1332 fields += ['user', 'description', 'date']
1332 fields += ['user', 'description', 'date']
1333 elif field == 'diff':
1333 elif field == 'diff':
1334 # a revision matching the diff must also match the files
1334 # a revision matching the diff must also match the files
1335 # since matching the diff is very costly, make sure to
1335 # since matching the diff is very costly, make sure to
1336 # also match the files first
1336 # also match the files first
1337 fields += ['files', 'diff']
1337 fields += ['files', 'diff']
1338 else:
1338 else:
1339 if field == 'author':
1339 if field == 'author':
1340 field = 'user'
1340 field = 'user'
1341 fields.append(field)
1341 fields.append(field)
1342 fields = set(fields)
1342 fields = set(fields)
1343 if 'summary' in fields and 'description' in fields:
1343 if 'summary' in fields and 'description' in fields:
1344 # If a revision matches its description it also matches its summary
1344 # If a revision matches its description it also matches its summary
1345 fields.discard('summary')
1345 fields.discard('summary')
1346
1346
1347 # We may want to match more than one field
1347 # We may want to match more than one field
1348 # Not all fields take the same amount of time to be matched
1348 # Not all fields take the same amount of time to be matched
1349 # Sort the selected fields in order of increasing matching cost
1349 # Sort the selected fields in order of increasing matching cost
1350 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1350 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1351 'files', 'description', 'substate', 'diff']
1351 'files', 'description', 'substate', 'diff']
1352 def fieldkeyfunc(f):
1352 def fieldkeyfunc(f):
1353 try:
1353 try:
1354 return fieldorder.index(f)
1354 return fieldorder.index(f)
1355 except ValueError:
1355 except ValueError:
1356 # assume an unknown field is very costly
1356 # assume an unknown field is very costly
1357 return len(fieldorder)
1357 return len(fieldorder)
1358 fields = list(fields)
1358 fields = list(fields)
1359 fields.sort(key=fieldkeyfunc)
1359 fields.sort(key=fieldkeyfunc)
1360
1360
1361 # Each field will be matched with its own "getfield" function
1361 # Each field will be matched with its own "getfield" function
1362 # which will be added to the getfieldfuncs array of functions
1362 # which will be added to the getfieldfuncs array of functions
1363 getfieldfuncs = []
1363 getfieldfuncs = []
1364 _funcs = {
1364 _funcs = {
1365 'user': lambda r: repo[r].user(),
1365 'user': lambda r: repo[r].user(),
1366 'branch': lambda r: repo[r].branch(),
1366 'branch': lambda r: repo[r].branch(),
1367 'date': lambda r: repo[r].date(),
1367 'date': lambda r: repo[r].date(),
1368 'description': lambda r: repo[r].description(),
1368 'description': lambda r: repo[r].description(),
1369 'files': lambda r: repo[r].files(),
1369 'files': lambda r: repo[r].files(),
1370 'parents': lambda r: repo[r].parents(),
1370 'parents': lambda r: repo[r].parents(),
1371 'phase': lambda r: repo[r].phase(),
1371 'phase': lambda r: repo[r].phase(),
1372 'substate': lambda r: repo[r].substate,
1372 'substate': lambda r: repo[r].substate,
1373 'summary': lambda r: repo[r].description().splitlines()[0],
1373 'summary': lambda r: repo[r].description().splitlines()[0],
1374 'diff': lambda r: list(repo[r].diff(git=True),)
1374 'diff': lambda r: list(repo[r].diff(git=True),)
1375 }
1375 }
1376 for info in fields:
1376 for info in fields:
1377 getfield = _funcs.get(info, None)
1377 getfield = _funcs.get(info, None)
1378 if getfield is None:
1378 if getfield is None:
1379 raise error.ParseError(
1379 raise error.ParseError(
1380 # i18n: "matching" is a keyword
1380 # i18n: "matching" is a keyword
1381 _("unexpected field name passed to matching: %s") % info)
1381 _("unexpected field name passed to matching: %s") % info)
1382 getfieldfuncs.append(getfield)
1382 getfieldfuncs.append(getfield)
1383 # convert the getfield array of functions into a "getinfo" function
1383 # convert the getfield array of functions into a "getinfo" function
1384 # which returns an array of field values (or a single value if there
1384 # which returns an array of field values (or a single value if there
1385 # is only one field to match)
1385 # is only one field to match)
1386 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1386 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1387
1387
1388 def matches(x):
1388 def matches(x):
1389 for rev in revs:
1389 for rev in revs:
1390 target = getinfo(rev)
1390 target = getinfo(rev)
1391 match = True
1391 match = True
1392 for n, f in enumerate(getfieldfuncs):
1392 for n, f in enumerate(getfieldfuncs):
1393 if target[n] != f(x):
1393 if target[n] != f(x):
1394 match = False
1394 match = False
1395 if match:
1395 if match:
1396 return True
1396 return True
1397 return False
1397 return False
1398
1398
1399 return lazyset(subset, matches)
1399 return lazyset(subset, matches)
1400
1400
1401 def reverse(repo, subset, x):
1401 def reverse(repo, subset, x):
1402 """``reverse(set)``
1402 """``reverse(set)``
1403 Reverse order of set.
1403 Reverse order of set.
1404 """
1404 """
1405 l = getset(repo, subset, x)
1405 l = getset(repo, subset, x)
1406 l.reverse()
1406 l.reverse()
1407 return l
1407 return l
1408
1408
1409 def roots(repo, subset, x):
1409 def roots(repo, subset, x):
1410 """``roots(set)``
1410 """``roots(set)``
1411 Changesets in set with no parent changeset in set.
1411 Changesets in set with no parent changeset in set.
1412 """
1412 """
1413 s = getset(repo, baseset(repo.changelog), x).set()
1413 s = getset(repo, baseset(repo.changelog), x).set()
1414 subset = baseset([r for r in subset if r in s])
1414 subset = baseset([r for r in subset if r in s])
1415 cs = _children(repo, subset, s)
1415 cs = _children(repo, subset, s)
1416 return subset - cs
1416 return subset - cs
1417
1417
1418 def secret(repo, subset, x):
1418 def secret(repo, subset, x):
1419 """``secret()``
1419 """``secret()``
1420 Changeset in secret phase."""
1420 Changeset in secret phase."""
1421 # i18n: "secret" is a keyword
1421 # i18n: "secret" is a keyword
1422 getargs(x, 0, 0, _("secret takes no arguments"))
1422 getargs(x, 0, 0, _("secret takes no arguments"))
1423 pc = repo._phasecache
1423 pc = repo._phasecache
1424 return lazyset(subset, lambda x: pc.phase(repo, x) == phases.secret)
1424 return lazyset(subset, lambda x: pc.phase(repo, x) == phases.secret)
1425
1425
1426 def sort(repo, subset, x):
1426 def sort(repo, subset, x):
1427 """``sort(set[, [-]key...])``
1427 """``sort(set[, [-]key...])``
1428 Sort set by keys. The default sort order is ascending, specify a key
1428 Sort set by keys. The default sort order is ascending, specify a key
1429 as ``-key`` to sort in descending order.
1429 as ``-key`` to sort in descending order.
1430
1430
1431 The keys can be:
1431 The keys can be:
1432
1432
1433 - ``rev`` for the revision number,
1433 - ``rev`` for the revision number,
1434 - ``branch`` for the branch name,
1434 - ``branch`` for the branch name,
1435 - ``desc`` for the commit message (description),
1435 - ``desc`` for the commit message (description),
1436 - ``user`` for user name (``author`` can be used as an alias),
1436 - ``user`` for user name (``author`` can be used as an alias),
1437 - ``date`` for the commit date
1437 - ``date`` for the commit date
1438 """
1438 """
1439 # i18n: "sort" is a keyword
1439 # i18n: "sort" is a keyword
1440 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1440 l = getargs(x, 1, 2, _("sort requires one or two arguments"))
1441 keys = "rev"
1441 keys = "rev"
1442 if len(l) == 2:
1442 if len(l) == 2:
1443 # i18n: "sort" is a keyword
1443 # i18n: "sort" is a keyword
1444 keys = getstring(l[1], _("sort spec must be a string"))
1444 keys = getstring(l[1], _("sort spec must be a string"))
1445
1445
1446 s = l[0]
1446 s = l[0]
1447 keys = keys.split()
1447 keys = keys.split()
1448 l = []
1448 l = []
1449 def invert(s):
1449 def invert(s):
1450 return "".join(chr(255 - ord(c)) for c in s)
1450 return "".join(chr(255 - ord(c)) for c in s)
1451 for r in getset(repo, subset, s):
1451 for r in getset(repo, subset, s):
1452 c = repo[r]
1452 c = repo[r]
1453 e = []
1453 e = []
1454 for k in keys:
1454 for k in keys:
1455 if k == 'rev':
1455 if k == 'rev':
1456 e.append(r)
1456 e.append(r)
1457 elif k == '-rev':
1457 elif k == '-rev':
1458 e.append(-r)
1458 e.append(-r)
1459 elif k == 'branch':
1459 elif k == 'branch':
1460 e.append(c.branch())
1460 e.append(c.branch())
1461 elif k == '-branch':
1461 elif k == '-branch':
1462 e.append(invert(c.branch()))
1462 e.append(invert(c.branch()))
1463 elif k == 'desc':
1463 elif k == 'desc':
1464 e.append(c.description())
1464 e.append(c.description())
1465 elif k == '-desc':
1465 elif k == '-desc':
1466 e.append(invert(c.description()))
1466 e.append(invert(c.description()))
1467 elif k in 'user author':
1467 elif k in 'user author':
1468 e.append(c.user())
1468 e.append(c.user())
1469 elif k in '-user -author':
1469 elif k in '-user -author':
1470 e.append(invert(c.user()))
1470 e.append(invert(c.user()))
1471 elif k == 'date':
1471 elif k == 'date':
1472 e.append(c.date()[0])
1472 e.append(c.date()[0])
1473 elif k == '-date':
1473 elif k == '-date':
1474 e.append(-c.date()[0])
1474 e.append(-c.date()[0])
1475 else:
1475 else:
1476 raise error.ParseError(_("unknown sort key %r") % k)
1476 raise error.ParseError(_("unknown sort key %r") % k)
1477 e.append(r)
1477 e.append(r)
1478 l.append(e)
1478 l.append(e)
1479 l.sort()
1479 l.sort()
1480 return baseset([e[-1] for e in l])
1480 return baseset([e[-1] for e in l])
1481
1481
1482 def _stringmatcher(pattern):
1482 def _stringmatcher(pattern):
1483 """
1483 """
1484 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1484 accepts a string, possibly starting with 're:' or 'literal:' prefix.
1485 returns the matcher name, pattern, and matcher function.
1485 returns the matcher name, pattern, and matcher function.
1486 missing or unknown prefixes are treated as literal matches.
1486 missing or unknown prefixes are treated as literal matches.
1487
1487
1488 helper for tests:
1488 helper for tests:
1489 >>> def test(pattern, *tests):
1489 >>> def test(pattern, *tests):
1490 ... kind, pattern, matcher = _stringmatcher(pattern)
1490 ... kind, pattern, matcher = _stringmatcher(pattern)
1491 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1491 ... return (kind, pattern, [bool(matcher(t)) for t in tests])
1492
1492
1493 exact matching (no prefix):
1493 exact matching (no prefix):
1494 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1494 >>> test('abcdefg', 'abc', 'def', 'abcdefg')
1495 ('literal', 'abcdefg', [False, False, True])
1495 ('literal', 'abcdefg', [False, False, True])
1496
1496
1497 regex matching ('re:' prefix)
1497 regex matching ('re:' prefix)
1498 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1498 >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
1499 ('re', 'a.+b', [False, False, True])
1499 ('re', 'a.+b', [False, False, True])
1500
1500
1501 force exact matches ('literal:' prefix)
1501 force exact matches ('literal:' prefix)
1502 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1502 >>> test('literal:re:foobar', 'foobar', 're:foobar')
1503 ('literal', 're:foobar', [False, True])
1503 ('literal', 're:foobar', [False, True])
1504
1504
1505 unknown prefixes are ignored and treated as literals
1505 unknown prefixes are ignored and treated as literals
1506 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1506 >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
1507 ('literal', 'foo:bar', [False, False, True])
1507 ('literal', 'foo:bar', [False, False, True])
1508 """
1508 """
1509 if pattern.startswith('re:'):
1509 if pattern.startswith('re:'):
1510 pattern = pattern[3:]
1510 pattern = pattern[3:]
1511 try:
1511 try:
1512 regex = re.compile(pattern)
1512 regex = re.compile(pattern)
1513 except re.error, e:
1513 except re.error, e:
1514 raise error.ParseError(_('invalid regular expression: %s')
1514 raise error.ParseError(_('invalid regular expression: %s')
1515 % e)
1515 % e)
1516 return 're', pattern, regex.search
1516 return 're', pattern, regex.search
1517 elif pattern.startswith('literal:'):
1517 elif pattern.startswith('literal:'):
1518 pattern = pattern[8:]
1518 pattern = pattern[8:]
1519 return 'literal', pattern, pattern.__eq__
1519 return 'literal', pattern, pattern.__eq__
1520
1520
1521 def _substringmatcher(pattern):
1521 def _substringmatcher(pattern):
1522 kind, pattern, matcher = _stringmatcher(pattern)
1522 kind, pattern, matcher = _stringmatcher(pattern)
1523 if kind == 'literal':
1523 if kind == 'literal':
1524 matcher = lambda s: pattern in s
1524 matcher = lambda s: pattern in s
1525 return kind, pattern, matcher
1525 return kind, pattern, matcher
1526
1526
1527 def tag(repo, subset, x):
1527 def tag(repo, subset, x):
1528 """``tag([name])``
1528 """``tag([name])``
1529 The specified tag by name, or all tagged revisions if no name is given.
1529 The specified tag by name, or all tagged revisions if no name is given.
1530 """
1530 """
1531 # i18n: "tag" is a keyword
1531 # i18n: "tag" is a keyword
1532 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1532 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1533 cl = repo.changelog
1533 cl = repo.changelog
1534 if args:
1534 if args:
1535 pattern = getstring(args[0],
1535 pattern = getstring(args[0],
1536 # i18n: "tag" is a keyword
1536 # i18n: "tag" is a keyword
1537 _('the argument to tag must be a string'))
1537 _('the argument to tag must be a string'))
1538 kind, pattern, matcher = _stringmatcher(pattern)
1538 kind, pattern, matcher = _stringmatcher(pattern)
1539 if kind == 'literal':
1539 if kind == 'literal':
1540 # avoid resolving all tags
1540 # avoid resolving all tags
1541 tn = repo._tagscache.tags.get(pattern, None)
1541 tn = repo._tagscache.tags.get(pattern, None)
1542 if tn is None:
1542 if tn is None:
1543 raise util.Abort(_("tag '%s' does not exist") % pattern)
1543 raise util.Abort(_("tag '%s' does not exist") % pattern)
1544 s = set([repo[tn].rev()])
1544 s = set([repo[tn].rev()])
1545 else:
1545 else:
1546 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1546 s = set([cl.rev(n) for t, n in repo.tagslist() if matcher(t)])
1547 else:
1547 else:
1548 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1548 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
1549 return subset & s
1549 return subset & s
1550
1550
1551 def tagged(repo, subset, x):
1551 def tagged(repo, subset, x):
1552 return tag(repo, subset, x)
1552 return tag(repo, subset, x)
1553
1553
1554 def unstable(repo, subset, x):
1554 def unstable(repo, subset, x):
1555 """``unstable()``
1555 """``unstable()``
1556 Non-obsolete changesets with obsolete ancestors.
1556 Non-obsolete changesets with obsolete ancestors.
1557 """
1557 """
1558 # i18n: "unstable" is a keyword
1558 # i18n: "unstable" is a keyword
1559 getargs(x, 0, 0, _("unstable takes no arguments"))
1559 getargs(x, 0, 0, _("unstable takes no arguments"))
1560 unstables = obsmod.getrevs(repo, 'unstable')
1560 unstables = obsmod.getrevs(repo, 'unstable')
1561 return subset & unstables
1561 return subset & unstables
1562
1562
1563
1563
1564 def user(repo, subset, x):
1564 def user(repo, subset, x):
1565 """``user(string)``
1565 """``user(string)``
1566 User name contains string. The match is case-insensitive.
1566 User name contains string. The match is case-insensitive.
1567
1567
1568 If `string` starts with `re:`, the remainder of the string is treated as
1568 If `string` starts with `re:`, the remainder of the string is treated as
1569 a regular expression. To match a user that actually contains `re:`, use
1569 a regular expression. To match a user that actually contains `re:`, use
1570 the prefix `literal:`.
1570 the prefix `literal:`.
1571 """
1571 """
1572 return author(repo, subset, x)
1572 return author(repo, subset, x)
1573
1573
1574 # for internal use
1574 # for internal use
1575 def _list(repo, subset, x):
1575 def _list(repo, subset, x):
1576 s = getstring(x, "internal error")
1576 s = getstring(x, "internal error")
1577 if not s:
1577 if not s:
1578 return baseset([])
1578 return baseset([])
1579 ls = [repo[r].rev() for r in s.split('\0')]
1579 ls = [repo[r].rev() for r in s.split('\0')]
1580 s = subset.set()
1580 s = subset.set()
1581 return baseset([r for r in ls if r in s])
1581 return baseset([r for r in ls if r in s])
1582
1582
1583 # for internal use
1583 # for internal use
1584 def _intlist(repo, subset, x):
1584 def _intlist(repo, subset, x):
1585 s = getstring(x, "internal error")
1585 s = getstring(x, "internal error")
1586 if not s:
1586 if not s:
1587 return baseset([])
1587 return baseset([])
1588 ls = [int(r) for r in s.split('\0')]
1588 ls = [int(r) for r in s.split('\0')]
1589 s = subset.set()
1589 s = subset.set()
1590 return baseset([r for r in ls if r in s])
1590 return baseset([r for r in ls if r in s])
1591
1591
1592 # for internal use
1593 def _hexlist(repo, subset, x):
1594 s = getstring(x, "internal error")
1595 if not s:
1596 return baseset([])
1597 cl = repo.changelog
1598 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
1599 s = subset.set()
1600 return baseset([r for r in ls if r in s])
1601
1592 symbols = {
1602 symbols = {
1593 "adds": adds,
1603 "adds": adds,
1594 "all": getall,
1604 "all": getall,
1595 "ancestor": ancestor,
1605 "ancestor": ancestor,
1596 "ancestors": ancestors,
1606 "ancestors": ancestors,
1597 "_firstancestors": _firstancestors,
1607 "_firstancestors": _firstancestors,
1598 "author": author,
1608 "author": author,
1599 "bisect": bisect,
1609 "bisect": bisect,
1600 "bisected": bisected,
1610 "bisected": bisected,
1601 "bookmark": bookmark,
1611 "bookmark": bookmark,
1602 "branch": branch,
1612 "branch": branch,
1603 "branchpoint": branchpoint,
1613 "branchpoint": branchpoint,
1604 "bumped": bumped,
1614 "bumped": bumped,
1605 "bundle": bundle,
1615 "bundle": bundle,
1606 "children": children,
1616 "children": children,
1607 "closed": closed,
1617 "closed": closed,
1608 "contains": contains,
1618 "contains": contains,
1609 "converted": converted,
1619 "converted": converted,
1610 "date": date,
1620 "date": date,
1611 "desc": desc,
1621 "desc": desc,
1612 "descendants": descendants,
1622 "descendants": descendants,
1613 "_firstdescendants": _firstdescendants,
1623 "_firstdescendants": _firstdescendants,
1614 "destination": destination,
1624 "destination": destination,
1615 "divergent": divergent,
1625 "divergent": divergent,
1616 "draft": draft,
1626 "draft": draft,
1617 "extinct": extinct,
1627 "extinct": extinct,
1618 "extra": extra,
1628 "extra": extra,
1619 "file": hasfile,
1629 "file": hasfile,
1620 "filelog": filelog,
1630 "filelog": filelog,
1621 "first": first,
1631 "first": first,
1622 "follow": follow,
1632 "follow": follow,
1623 "_followfirst": _followfirst,
1633 "_followfirst": _followfirst,
1624 "grep": grep,
1634 "grep": grep,
1625 "head": head,
1635 "head": head,
1626 "heads": heads,
1636 "heads": heads,
1627 "hidden": hidden,
1637 "hidden": hidden,
1628 "id": node_,
1638 "id": node_,
1629 "keyword": keyword,
1639 "keyword": keyword,
1630 "last": last,
1640 "last": last,
1631 "limit": limit,
1641 "limit": limit,
1632 "_matchfiles": _matchfiles,
1642 "_matchfiles": _matchfiles,
1633 "max": maxrev,
1643 "max": maxrev,
1634 "merge": merge,
1644 "merge": merge,
1635 "min": minrev,
1645 "min": minrev,
1636 "_missingancestors": _missingancestors,
1646 "_missingancestors": _missingancestors,
1637 "modifies": modifies,
1647 "modifies": modifies,
1638 "obsolete": obsolete,
1648 "obsolete": obsolete,
1639 "origin": origin,
1649 "origin": origin,
1640 "outgoing": outgoing,
1650 "outgoing": outgoing,
1641 "p1": p1,
1651 "p1": p1,
1642 "p2": p2,
1652 "p2": p2,
1643 "parents": parents,
1653 "parents": parents,
1644 "present": present,
1654 "present": present,
1645 "public": public,
1655 "public": public,
1646 "remote": remote,
1656 "remote": remote,
1647 "removes": removes,
1657 "removes": removes,
1648 "rev": rev,
1658 "rev": rev,
1649 "reverse": reverse,
1659 "reverse": reverse,
1650 "roots": roots,
1660 "roots": roots,
1651 "sort": sort,
1661 "sort": sort,
1652 "secret": secret,
1662 "secret": secret,
1653 "matching": matching,
1663 "matching": matching,
1654 "tag": tag,
1664 "tag": tag,
1655 "tagged": tagged,
1665 "tagged": tagged,
1656 "user": user,
1666 "user": user,
1657 "unstable": unstable,
1667 "unstable": unstable,
1658 "_list": _list,
1668 "_list": _list,
1659 "_intlist": _intlist,
1669 "_intlist": _intlist,
1670 "_hexlist": _hexlist,
1660 }
1671 }
1661
1672
1662 # symbols which can't be used for a DoS attack for any given input
1673 # symbols which can't be used for a DoS attack for any given input
1663 # (e.g. those which accept regexes as plain strings shouldn't be included)
1674 # (e.g. those which accept regexes as plain strings shouldn't be included)
1664 # functions that just return a lot of changesets (like all) don't count here
1675 # functions that just return a lot of changesets (like all) don't count here
1665 safesymbols = set([
1676 safesymbols = set([
1666 "adds",
1677 "adds",
1667 "all",
1678 "all",
1668 "ancestor",
1679 "ancestor",
1669 "ancestors",
1680 "ancestors",
1670 "_firstancestors",
1681 "_firstancestors",
1671 "author",
1682 "author",
1672 "bisect",
1683 "bisect",
1673 "bisected",
1684 "bisected",
1674 "bookmark",
1685 "bookmark",
1675 "branch",
1686 "branch",
1676 "branchpoint",
1687 "branchpoint",
1677 "bumped",
1688 "bumped",
1678 "bundle",
1689 "bundle",
1679 "children",
1690 "children",
1680 "closed",
1691 "closed",
1681 "converted",
1692 "converted",
1682 "date",
1693 "date",
1683 "desc",
1694 "desc",
1684 "descendants",
1695 "descendants",
1685 "_firstdescendants",
1696 "_firstdescendants",
1686 "destination",
1697 "destination",
1687 "divergent",
1698 "divergent",
1688 "draft",
1699 "draft",
1689 "extinct",
1700 "extinct",
1690 "extra",
1701 "extra",
1691 "file",
1702 "file",
1692 "filelog",
1703 "filelog",
1693 "first",
1704 "first",
1694 "follow",
1705 "follow",
1695 "_followfirst",
1706 "_followfirst",
1696 "head",
1707 "head",
1697 "heads",
1708 "heads",
1698 "hidden",
1709 "hidden",
1699 "id",
1710 "id",
1700 "keyword",
1711 "keyword",
1701 "last",
1712 "last",
1702 "limit",
1713 "limit",
1703 "_matchfiles",
1714 "_matchfiles",
1704 "max",
1715 "max",
1705 "merge",
1716 "merge",
1706 "min",
1717 "min",
1707 "_missingancestors",
1718 "_missingancestors",
1708 "modifies",
1719 "modifies",
1709 "obsolete",
1720 "obsolete",
1710 "origin",
1721 "origin",
1711 "outgoing",
1722 "outgoing",
1712 "p1",
1723 "p1",
1713 "p2",
1724 "p2",
1714 "parents",
1725 "parents",
1715 "present",
1726 "present",
1716 "public",
1727 "public",
1717 "remote",
1728 "remote",
1718 "removes",
1729 "removes",
1719 "rev",
1730 "rev",
1720 "reverse",
1731 "reverse",
1721 "roots",
1732 "roots",
1722 "sort",
1733 "sort",
1723 "secret",
1734 "secret",
1724 "matching",
1735 "matching",
1725 "tag",
1736 "tag",
1726 "tagged",
1737 "tagged",
1727 "user",
1738 "user",
1728 "unstable",
1739 "unstable",
1729 "_list",
1740 "_list",
1730 "_intlist",
1741 "_intlist",
1742 "_hexlist",
1731 ])
1743 ])
1732
1744
1733 methods = {
1745 methods = {
1734 "range": rangeset,
1746 "range": rangeset,
1735 "dagrange": dagrange,
1747 "dagrange": dagrange,
1736 "string": stringset,
1748 "string": stringset,
1737 "symbol": symbolset,
1749 "symbol": symbolset,
1738 "and": andset,
1750 "and": andset,
1739 "or": orset,
1751 "or": orset,
1740 "not": notset,
1752 "not": notset,
1741 "list": listset,
1753 "list": listset,
1742 "func": func,
1754 "func": func,
1743 "ancestor": ancestorspec,
1755 "ancestor": ancestorspec,
1744 "parent": parentspec,
1756 "parent": parentspec,
1745 "parentpost": p1,
1757 "parentpost": p1,
1746 }
1758 }
1747
1759
1748 def optimize(x, small):
1760 def optimize(x, small):
1749 if x is None:
1761 if x is None:
1750 return 0, x
1762 return 0, x
1751
1763
1752 smallbonus = 1
1764 smallbonus = 1
1753 if small:
1765 if small:
1754 smallbonus = .5
1766 smallbonus = .5
1755
1767
1756 op = x[0]
1768 op = x[0]
1757 if op == 'minus':
1769 if op == 'minus':
1758 return optimize(('and', x[1], ('not', x[2])), small)
1770 return optimize(('and', x[1], ('not', x[2])), small)
1759 elif op == 'dagrangepre':
1771 elif op == 'dagrangepre':
1760 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
1772 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
1761 elif op == 'dagrangepost':
1773 elif op == 'dagrangepost':
1762 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
1774 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
1763 elif op == 'rangepre':
1775 elif op == 'rangepre':
1764 return optimize(('range', ('string', '0'), x[1]), small)
1776 return optimize(('range', ('string', '0'), x[1]), small)
1765 elif op == 'rangepost':
1777 elif op == 'rangepost':
1766 return optimize(('range', x[1], ('string', 'tip')), small)
1778 return optimize(('range', x[1], ('string', 'tip')), small)
1767 elif op == 'negate':
1779 elif op == 'negate':
1768 return optimize(('string',
1780 return optimize(('string',
1769 '-' + getstring(x[1], _("can't negate that"))), small)
1781 '-' + getstring(x[1], _("can't negate that"))), small)
1770 elif op in 'string symbol negate':
1782 elif op in 'string symbol negate':
1771 return smallbonus, x # single revisions are small
1783 return smallbonus, x # single revisions are small
1772 elif op == 'and':
1784 elif op == 'and':
1773 wa, ta = optimize(x[1], True)
1785 wa, ta = optimize(x[1], True)
1774 wb, tb = optimize(x[2], True)
1786 wb, tb = optimize(x[2], True)
1775
1787
1776 # (::x and not ::y)/(not ::y and ::x) have a fast path
1788 # (::x and not ::y)/(not ::y and ::x) have a fast path
1777 def ismissingancestors(revs, bases):
1789 def ismissingancestors(revs, bases):
1778 return (
1790 return (
1779 revs[0] == 'func'
1791 revs[0] == 'func'
1780 and getstring(revs[1], _('not a symbol')) == 'ancestors'
1792 and getstring(revs[1], _('not a symbol')) == 'ancestors'
1781 and bases[0] == 'not'
1793 and bases[0] == 'not'
1782 and bases[1][0] == 'func'
1794 and bases[1][0] == 'func'
1783 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
1795 and getstring(bases[1][1], _('not a symbol')) == 'ancestors')
1784
1796
1785 w = min(wa, wb)
1797 w = min(wa, wb)
1786 if ismissingancestors(ta, tb):
1798 if ismissingancestors(ta, tb):
1787 return w, ('func', ('symbol', '_missingancestors'),
1799 return w, ('func', ('symbol', '_missingancestors'),
1788 ('list', ta[2], tb[1][2]))
1800 ('list', ta[2], tb[1][2]))
1789 if ismissingancestors(tb, ta):
1801 if ismissingancestors(tb, ta):
1790 return w, ('func', ('symbol', '_missingancestors'),
1802 return w, ('func', ('symbol', '_missingancestors'),
1791 ('list', tb[2], ta[1][2]))
1803 ('list', tb[2], ta[1][2]))
1792
1804
1793 if wa > wb:
1805 if wa > wb:
1794 return w, (op, tb, ta)
1806 return w, (op, tb, ta)
1795 return w, (op, ta, tb)
1807 return w, (op, ta, tb)
1796 elif op == 'or':
1808 elif op == 'or':
1797 wa, ta = optimize(x[1], False)
1809 wa, ta = optimize(x[1], False)
1798 wb, tb = optimize(x[2], False)
1810 wb, tb = optimize(x[2], False)
1799 if wb < wa:
1811 if wb < wa:
1800 wb, wa = wa, wb
1812 wb, wa = wa, wb
1801 return max(wa, wb), (op, ta, tb)
1813 return max(wa, wb), (op, ta, tb)
1802 elif op == 'not':
1814 elif op == 'not':
1803 o = optimize(x[1], not small)
1815 o = optimize(x[1], not small)
1804 return o[0], (op, o[1])
1816 return o[0], (op, o[1])
1805 elif op == 'parentpost':
1817 elif op == 'parentpost':
1806 o = optimize(x[1], small)
1818 o = optimize(x[1], small)
1807 return o[0], (op, o[1])
1819 return o[0], (op, o[1])
1808 elif op == 'group':
1820 elif op == 'group':
1809 return optimize(x[1], small)
1821 return optimize(x[1], small)
1810 elif op in 'dagrange range list parent ancestorspec':
1822 elif op in 'dagrange range list parent ancestorspec':
1811 if op == 'parent':
1823 if op == 'parent':
1812 # x^:y means (x^) : y, not x ^ (:y)
1824 # x^:y means (x^) : y, not x ^ (:y)
1813 post = ('parentpost', x[1])
1825 post = ('parentpost', x[1])
1814 if x[2][0] == 'dagrangepre':
1826 if x[2][0] == 'dagrangepre':
1815 return optimize(('dagrange', post, x[2][1]), small)
1827 return optimize(('dagrange', post, x[2][1]), small)
1816 elif x[2][0] == 'rangepre':
1828 elif x[2][0] == 'rangepre':
1817 return optimize(('range', post, x[2][1]), small)
1829 return optimize(('range', post, x[2][1]), small)
1818
1830
1819 wa, ta = optimize(x[1], small)
1831 wa, ta = optimize(x[1], small)
1820 wb, tb = optimize(x[2], small)
1832 wb, tb = optimize(x[2], small)
1821 return wa + wb, (op, ta, tb)
1833 return wa + wb, (op, ta, tb)
1822 elif op == 'func':
1834 elif op == 'func':
1823 f = getstring(x[1], _("not a symbol"))
1835 f = getstring(x[1], _("not a symbol"))
1824 wa, ta = optimize(x[2], small)
1836 wa, ta = optimize(x[2], small)
1825 if f in ("author branch closed date desc file grep keyword "
1837 if f in ("author branch closed date desc file grep keyword "
1826 "outgoing user"):
1838 "outgoing user"):
1827 w = 10 # slow
1839 w = 10 # slow
1828 elif f in "modifies adds removes":
1840 elif f in "modifies adds removes":
1829 w = 30 # slower
1841 w = 30 # slower
1830 elif f == "contains":
1842 elif f == "contains":
1831 w = 100 # very slow
1843 w = 100 # very slow
1832 elif f == "ancestor":
1844 elif f == "ancestor":
1833 w = 1 * smallbonus
1845 w = 1 * smallbonus
1834 elif f in "reverse limit first":
1846 elif f in "reverse limit first":
1835 w = 0
1847 w = 0
1836 elif f in "sort":
1848 elif f in "sort":
1837 w = 10 # assume most sorts look at changelog
1849 w = 10 # assume most sorts look at changelog
1838 else:
1850 else:
1839 w = 1
1851 w = 1
1840 return w + wa, (op, x[1], ta)
1852 return w + wa, (op, x[1], ta)
1841 return 1, x
1853 return 1, x
1842
1854
1843 _aliasarg = ('func', ('symbol', '_aliasarg'))
1855 _aliasarg = ('func', ('symbol', '_aliasarg'))
1844 def _getaliasarg(tree):
1856 def _getaliasarg(tree):
1845 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
1857 """If tree matches ('func', ('symbol', '_aliasarg'), ('string', X))
1846 return X, None otherwise.
1858 return X, None otherwise.
1847 """
1859 """
1848 if (len(tree) == 3 and tree[:2] == _aliasarg
1860 if (len(tree) == 3 and tree[:2] == _aliasarg
1849 and tree[2][0] == 'string'):
1861 and tree[2][0] == 'string'):
1850 return tree[2][1]
1862 return tree[2][1]
1851 return None
1863 return None
1852
1864
1853 def _checkaliasarg(tree, known=None):
1865 def _checkaliasarg(tree, known=None):
1854 """Check tree contains no _aliasarg construct or only ones which
1866 """Check tree contains no _aliasarg construct or only ones which
1855 value is in known. Used to avoid alias placeholders injection.
1867 value is in known. Used to avoid alias placeholders injection.
1856 """
1868 """
1857 if isinstance(tree, tuple):
1869 if isinstance(tree, tuple):
1858 arg = _getaliasarg(tree)
1870 arg = _getaliasarg(tree)
1859 if arg is not None and (not known or arg not in known):
1871 if arg is not None and (not known or arg not in known):
1860 raise error.ParseError(_("not a function: %s") % '_aliasarg')
1872 raise error.ParseError(_("not a function: %s") % '_aliasarg')
1861 for t in tree:
1873 for t in tree:
1862 _checkaliasarg(t, known)
1874 _checkaliasarg(t, known)
1863
1875
1864 class revsetalias(object):
1876 class revsetalias(object):
1865 funcre = re.compile('^([^(]+)\(([^)]+)\)$')
1877 funcre = re.compile('^([^(]+)\(([^)]+)\)$')
1866 args = None
1878 args = None
1867
1879
1868 def __init__(self, name, value):
1880 def __init__(self, name, value):
1869 '''Aliases like:
1881 '''Aliases like:
1870
1882
1871 h = heads(default)
1883 h = heads(default)
1872 b($1) = ancestors($1) - ancestors(default)
1884 b($1) = ancestors($1) - ancestors(default)
1873 '''
1885 '''
1874 m = self.funcre.search(name)
1886 m = self.funcre.search(name)
1875 if m:
1887 if m:
1876 self.name = m.group(1)
1888 self.name = m.group(1)
1877 self.tree = ('func', ('symbol', m.group(1)))
1889 self.tree = ('func', ('symbol', m.group(1)))
1878 self.args = [x.strip() for x in m.group(2).split(',')]
1890 self.args = [x.strip() for x in m.group(2).split(',')]
1879 for arg in self.args:
1891 for arg in self.args:
1880 # _aliasarg() is an unknown symbol only used separate
1892 # _aliasarg() is an unknown symbol only used separate
1881 # alias argument placeholders from regular strings.
1893 # alias argument placeholders from regular strings.
1882 value = value.replace(arg, '_aliasarg(%r)' % (arg,))
1894 value = value.replace(arg, '_aliasarg(%r)' % (arg,))
1883 else:
1895 else:
1884 self.name = name
1896 self.name = name
1885 self.tree = ('symbol', name)
1897 self.tree = ('symbol', name)
1886
1898
1887 self.replacement, pos = parse(value)
1899 self.replacement, pos = parse(value)
1888 if pos != len(value):
1900 if pos != len(value):
1889 raise error.ParseError(_('invalid token'), pos)
1901 raise error.ParseError(_('invalid token'), pos)
1890 # Check for placeholder injection
1902 # Check for placeholder injection
1891 _checkaliasarg(self.replacement, self.args)
1903 _checkaliasarg(self.replacement, self.args)
1892
1904
1893 def _getalias(aliases, tree):
1905 def _getalias(aliases, tree):
1894 """If tree looks like an unexpanded alias, return it. Return None
1906 """If tree looks like an unexpanded alias, return it. Return None
1895 otherwise.
1907 otherwise.
1896 """
1908 """
1897 if isinstance(tree, tuple) and tree:
1909 if isinstance(tree, tuple) and tree:
1898 if tree[0] == 'symbol' and len(tree) == 2:
1910 if tree[0] == 'symbol' and len(tree) == 2:
1899 name = tree[1]
1911 name = tree[1]
1900 alias = aliases.get(name)
1912 alias = aliases.get(name)
1901 if alias and alias.args is None and alias.tree == tree:
1913 if alias and alias.args is None and alias.tree == tree:
1902 return alias
1914 return alias
1903 if tree[0] == 'func' and len(tree) > 1:
1915 if tree[0] == 'func' and len(tree) > 1:
1904 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
1916 if tree[1][0] == 'symbol' and len(tree[1]) == 2:
1905 name = tree[1][1]
1917 name = tree[1][1]
1906 alias = aliases.get(name)
1918 alias = aliases.get(name)
1907 if alias and alias.args is not None and alias.tree == tree[:2]:
1919 if alias and alias.args is not None and alias.tree == tree[:2]:
1908 return alias
1920 return alias
1909 return None
1921 return None
1910
1922
1911 def _expandargs(tree, args):
1923 def _expandargs(tree, args):
1912 """Replace _aliasarg instances with the substitution value of the
1924 """Replace _aliasarg instances with the substitution value of the
1913 same name in args, recursively.
1925 same name in args, recursively.
1914 """
1926 """
1915 if not tree or not isinstance(tree, tuple):
1927 if not tree or not isinstance(tree, tuple):
1916 return tree
1928 return tree
1917 arg = _getaliasarg(tree)
1929 arg = _getaliasarg(tree)
1918 if arg is not None:
1930 if arg is not None:
1919 return args[arg]
1931 return args[arg]
1920 return tuple(_expandargs(t, args) for t in tree)
1932 return tuple(_expandargs(t, args) for t in tree)
1921
1933
1922 def _expandaliases(aliases, tree, expanding, cache):
1934 def _expandaliases(aliases, tree, expanding, cache):
1923 """Expand aliases in tree, recursively.
1935 """Expand aliases in tree, recursively.
1924
1936
1925 'aliases' is a dictionary mapping user defined aliases to
1937 'aliases' is a dictionary mapping user defined aliases to
1926 revsetalias objects.
1938 revsetalias objects.
1927 """
1939 """
1928 if not isinstance(tree, tuple):
1940 if not isinstance(tree, tuple):
1929 # Do not expand raw strings
1941 # Do not expand raw strings
1930 return tree
1942 return tree
1931 alias = _getalias(aliases, tree)
1943 alias = _getalias(aliases, tree)
1932 if alias is not None:
1944 if alias is not None:
1933 if alias in expanding:
1945 if alias in expanding:
1934 raise error.ParseError(_('infinite expansion of revset alias "%s" '
1946 raise error.ParseError(_('infinite expansion of revset alias "%s" '
1935 'detected') % alias.name)
1947 'detected') % alias.name)
1936 expanding.append(alias)
1948 expanding.append(alias)
1937 if alias.name not in cache:
1949 if alias.name not in cache:
1938 cache[alias.name] = _expandaliases(aliases, alias.replacement,
1950 cache[alias.name] = _expandaliases(aliases, alias.replacement,
1939 expanding, cache)
1951 expanding, cache)
1940 result = cache[alias.name]
1952 result = cache[alias.name]
1941 expanding.pop()
1953 expanding.pop()
1942 if alias.args is not None:
1954 if alias.args is not None:
1943 l = getlist(tree[2])
1955 l = getlist(tree[2])
1944 if len(l) != len(alias.args):
1956 if len(l) != len(alias.args):
1945 raise error.ParseError(
1957 raise error.ParseError(
1946 _('invalid number of arguments: %s') % len(l))
1958 _('invalid number of arguments: %s') % len(l))
1947 l = [_expandaliases(aliases, a, [], cache) for a in l]
1959 l = [_expandaliases(aliases, a, [], cache) for a in l]
1948 result = _expandargs(result, dict(zip(alias.args, l)))
1960 result = _expandargs(result, dict(zip(alias.args, l)))
1949 else:
1961 else:
1950 result = tuple(_expandaliases(aliases, t, expanding, cache)
1962 result = tuple(_expandaliases(aliases, t, expanding, cache)
1951 for t in tree)
1963 for t in tree)
1952 return result
1964 return result
1953
1965
1954 def findaliases(ui, tree):
1966 def findaliases(ui, tree):
1955 _checkaliasarg(tree)
1967 _checkaliasarg(tree)
1956 aliases = {}
1968 aliases = {}
1957 for k, v in ui.configitems('revsetalias'):
1969 for k, v in ui.configitems('revsetalias'):
1958 alias = revsetalias(k, v)
1970 alias = revsetalias(k, v)
1959 aliases[alias.name] = alias
1971 aliases[alias.name] = alias
1960 return _expandaliases(aliases, tree, [], {})
1972 return _expandaliases(aliases, tree, [], {})
1961
1973
1962 def parse(spec):
1974 def parse(spec):
1963 p = parser.parser(tokenize, elements)
1975 p = parser.parser(tokenize, elements)
1964 return p.parse(spec)
1976 return p.parse(spec)
1965
1977
1966 def match(ui, spec):
1978 def match(ui, spec):
1967 if not spec:
1979 if not spec:
1968 raise error.ParseError(_("empty query"))
1980 raise error.ParseError(_("empty query"))
1969 tree, pos = parse(spec)
1981 tree, pos = parse(spec)
1970 if (pos != len(spec)):
1982 if (pos != len(spec)):
1971 raise error.ParseError(_("invalid token"), pos)
1983 raise error.ParseError(_("invalid token"), pos)
1972 if ui:
1984 if ui:
1973 tree = findaliases(ui, tree)
1985 tree = findaliases(ui, tree)
1974 weight, tree = optimize(tree, True)
1986 weight, tree = optimize(tree, True)
1975 def mfunc(repo, subset):
1987 def mfunc(repo, subset):
1976 if util.safehasattr(subset, 'set'):
1988 if util.safehasattr(subset, 'set'):
1977 return getset(repo, subset, tree)
1989 return getset(repo, subset, tree)
1978 return getset(repo, baseset(subset), tree)
1990 return getset(repo, baseset(subset), tree)
1979 return mfunc
1991 return mfunc
1980
1992
1981 def formatspec(expr, *args):
1993 def formatspec(expr, *args):
1982 '''
1994 '''
1983 This is a convenience function for using revsets internally, and
1995 This is a convenience function for using revsets internally, and
1984 escapes arguments appropriately. Aliases are intentionally ignored
1996 escapes arguments appropriately. Aliases are intentionally ignored
1985 so that intended expression behavior isn't accidentally subverted.
1997 so that intended expression behavior isn't accidentally subverted.
1986
1998
1987 Supported arguments:
1999 Supported arguments:
1988
2000
1989 %r = revset expression, parenthesized
2001 %r = revset expression, parenthesized
1990 %d = int(arg), no quoting
2002 %d = int(arg), no quoting
1991 %s = string(arg), escaped and single-quoted
2003 %s = string(arg), escaped and single-quoted
1992 %b = arg.branch(), escaped and single-quoted
2004 %b = arg.branch(), escaped and single-quoted
1993 %n = hex(arg), single-quoted
2005 %n = hex(arg), single-quoted
1994 %% = a literal '%'
2006 %% = a literal '%'
1995
2007
1996 Prefixing the type with 'l' specifies a parenthesized list of that type.
2008 Prefixing the type with 'l' specifies a parenthesized list of that type.
1997
2009
1998 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
2010 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
1999 '(10 or 11):: and ((this()) or (that()))'
2011 '(10 or 11):: and ((this()) or (that()))'
2000 >>> formatspec('%d:: and not %d::', 10, 20)
2012 >>> formatspec('%d:: and not %d::', 10, 20)
2001 '10:: and not 20::'
2013 '10:: and not 20::'
2002 >>> formatspec('%ld or %ld', [], [1])
2014 >>> formatspec('%ld or %ld', [], [1])
2003 "_list('') or 1"
2015 "_list('') or 1"
2004 >>> formatspec('keyword(%s)', 'foo\\xe9')
2016 >>> formatspec('keyword(%s)', 'foo\\xe9')
2005 "keyword('foo\\\\xe9')"
2017 "keyword('foo\\\\xe9')"
2006 >>> b = lambda: 'default'
2018 >>> b = lambda: 'default'
2007 >>> b.branch = b
2019 >>> b.branch = b
2008 >>> formatspec('branch(%b)', b)
2020 >>> formatspec('branch(%b)', b)
2009 "branch('default')"
2021 "branch('default')"
2010 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
2022 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
2011 "root(_list('a\\x00b\\x00c\\x00d'))"
2023 "root(_list('a\\x00b\\x00c\\x00d'))"
2012 '''
2024 '''
2013
2025
2014 def quote(s):
2026 def quote(s):
2015 return repr(str(s))
2027 return repr(str(s))
2016
2028
2017 def argtype(c, arg):
2029 def argtype(c, arg):
2018 if c == 'd':
2030 if c == 'd':
2019 return str(int(arg))
2031 return str(int(arg))
2020 elif c == 's':
2032 elif c == 's':
2021 return quote(arg)
2033 return quote(arg)
2022 elif c == 'r':
2034 elif c == 'r':
2023 parse(arg) # make sure syntax errors are confined
2035 parse(arg) # make sure syntax errors are confined
2024 return '(%s)' % arg
2036 return '(%s)' % arg
2025 elif c == 'n':
2037 elif c == 'n':
2026 return quote(node.hex(arg))
2038 return quote(node.hex(arg))
2027 elif c == 'b':
2039 elif c == 'b':
2028 return quote(arg.branch())
2040 return quote(arg.branch())
2029
2041
2030 def listexp(s, t):
2042 def listexp(s, t):
2031 l = len(s)
2043 l = len(s)
2032 if l == 0:
2044 if l == 0:
2033 return "_list('')"
2045 return "_list('')"
2034 elif l == 1:
2046 elif l == 1:
2035 return argtype(t, s[0])
2047 return argtype(t, s[0])
2036 elif t == 'd':
2048 elif t == 'd':
2037 return "_intlist('%s')" % "\0".join(str(int(a)) for a in s)
2049 return "_intlist('%s')" % "\0".join(str(int(a)) for a in s)
2038 elif t == 's':
2050 elif t == 's':
2039 return "_list('%s')" % "\0".join(s)
2051 return "_list('%s')" % "\0".join(s)
2040 elif t == 'n':
2052 elif t == 'n':
2041 return "_list('%s')" % "\0".join(node.hex(a) for a in s)
2053 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
2042 elif t == 'b':
2054 elif t == 'b':
2043 return "_list('%s')" % "\0".join(a.branch() for a in s)
2055 return "_list('%s')" % "\0".join(a.branch() for a in s)
2044
2056
2045 m = l // 2
2057 m = l // 2
2046 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2058 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
2047
2059
2048 ret = ''
2060 ret = ''
2049 pos = 0
2061 pos = 0
2050 arg = 0
2062 arg = 0
2051 while pos < len(expr):
2063 while pos < len(expr):
2052 c = expr[pos]
2064 c = expr[pos]
2053 if c == '%':
2065 if c == '%':
2054 pos += 1
2066 pos += 1
2055 d = expr[pos]
2067 d = expr[pos]
2056 if d == '%':
2068 if d == '%':
2057 ret += d
2069 ret += d
2058 elif d in 'dsnbr':
2070 elif d in 'dsnbr':
2059 ret += argtype(d, args[arg])
2071 ret += argtype(d, args[arg])
2060 arg += 1
2072 arg += 1
2061 elif d == 'l':
2073 elif d == 'l':
2062 # a list of some type
2074 # a list of some type
2063 pos += 1
2075 pos += 1
2064 d = expr[pos]
2076 d = expr[pos]
2065 ret += listexp(list(args[arg]), d)
2077 ret += listexp(list(args[arg]), d)
2066 arg += 1
2078 arg += 1
2067 else:
2079 else:
2068 raise util.Abort('unexpected revspec format character %s' % d)
2080 raise util.Abort('unexpected revspec format character %s' % d)
2069 else:
2081 else:
2070 ret += c
2082 ret += c
2071 pos += 1
2083 pos += 1
2072
2084
2073 return ret
2085 return ret
2074
2086
2075 def prettyformat(tree):
2087 def prettyformat(tree):
2076 def _prettyformat(tree, level, lines):
2088 def _prettyformat(tree, level, lines):
2077 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2089 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2078 lines.append((level, str(tree)))
2090 lines.append((level, str(tree)))
2079 else:
2091 else:
2080 lines.append((level, '(%s' % tree[0]))
2092 lines.append((level, '(%s' % tree[0]))
2081 for s in tree[1:]:
2093 for s in tree[1:]:
2082 _prettyformat(s, level + 1, lines)
2094 _prettyformat(s, level + 1, lines)
2083 lines[-1:] = [(lines[-1][0], lines[-1][1] + ')')]
2095 lines[-1:] = [(lines[-1][0], lines[-1][1] + ')')]
2084
2096
2085 lines = []
2097 lines = []
2086 _prettyformat(tree, 0, lines)
2098 _prettyformat(tree, 0, lines)
2087 output = '\n'.join((' '*l + s) for l, s in lines)
2099 output = '\n'.join((' '*l + s) for l, s in lines)
2088 return output
2100 return output
2089
2101
2090 def depth(tree):
2102 def depth(tree):
2091 if isinstance(tree, tuple):
2103 if isinstance(tree, tuple):
2092 return max(map(depth, tree)) + 1
2104 return max(map(depth, tree)) + 1
2093 else:
2105 else:
2094 return 0
2106 return 0
2095
2107
2096 def funcsused(tree):
2108 def funcsused(tree):
2097 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2109 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
2098 return set()
2110 return set()
2099 else:
2111 else:
2100 funcs = set()
2112 funcs = set()
2101 for s in tree[1:]:
2113 for s in tree[1:]:
2102 funcs |= funcsused(s)
2114 funcs |= funcsused(s)
2103 if tree[0] == 'func':
2115 if tree[0] == 'func':
2104 funcs.add(tree[1][1])
2116 funcs.add(tree[1][1])
2105 return funcs
2117 return funcs
2106
2118
2107 class baseset(list):
2119 class baseset(list):
2108 """Basic data structure that represents a revset and contains the basic
2120 """Basic data structure that represents a revset and contains the basic
2109 operation that it should be able to perform.
2121 operation that it should be able to perform.
2110 """
2122 """
2111 def __init__(self, data):
2123 def __init__(self, data):
2112 super(baseset, self).__init__(data)
2124 super(baseset, self).__init__(data)
2113 self._set = None
2125 self._set = None
2114
2126
2115 def set(self):
2127 def set(self):
2116 if not self._set:
2128 if not self._set:
2117 self._set = set(self)
2129 self._set = set(self)
2118 return self._set
2130 return self._set
2119
2131
2120 def __sub__(self, x):
2132 def __sub__(self, x):
2121 if isinstance(x, baseset):
2133 if isinstance(x, baseset):
2122 s = x.set()
2134 s = x.set()
2123 else:
2135 else:
2124 s = set(x)
2136 s = set(x)
2125 return baseset(self.set() - s)
2137 return baseset(self.set() - s)
2126
2138
2127 def __and__(self, x):
2139 def __and__(self, x):
2128 if isinstance(x, baseset):
2140 if isinstance(x, baseset):
2129 x = x.set()
2141 x = x.set()
2130 return baseset([y for y in self if y in x])
2142 return baseset([y for y in self if y in x])
2131
2143
2132 def __add__(self, x):
2144 def __add__(self, x):
2133 s = self.set()
2145 s = self.set()
2134 l = [r for r in x if r not in s]
2146 l = [r for r in x if r not in s]
2135 return baseset(list(self) + l)
2147 return baseset(list(self) + l)
2136
2148
2137 class lazyset(object):
2149 class lazyset(object):
2138 """Duck type for baseset class which iterates lazily over the revisions in
2150 """Duck type for baseset class which iterates lazily over the revisions in
2139 the subset and contains a function which tests for membership in the
2151 the subset and contains a function which tests for membership in the
2140 revset
2152 revset
2141 """
2153 """
2142 def __init__(self, subset, condition):
2154 def __init__(self, subset, condition):
2143 self._subset = subset
2155 self._subset = subset
2144 self._condition = condition
2156 self._condition = condition
2145 self._cache = {}
2157 self._cache = {}
2146
2158
2147 def __contains__(self, x):
2159 def __contains__(self, x):
2148 c = self._cache
2160 c = self._cache
2149 if x not in c:
2161 if x not in c:
2150 c[x] = x in self._subset and self._condition(x)
2162 c[x] = x in self._subset and self._condition(x)
2151 return c[x]
2163 return c[x]
2152
2164
2153 def __iter__(self):
2165 def __iter__(self):
2154 cond = self._condition
2166 cond = self._condition
2155 for x in self._subset:
2167 for x in self._subset:
2156 if cond(x):
2168 if cond(x):
2157 yield x
2169 yield x
2158
2170
2159 def __and__(self, x):
2171 def __and__(self, x):
2160 return lazyset(self, lambda r: r in x)
2172 return lazyset(self, lambda r: r in x)
2161
2173
2162 def __sub__(self, x):
2174 def __sub__(self, x):
2163 return lazyset(self, lambda r: r not in x)
2175 return lazyset(self, lambda r: r not in x)
2164
2176
2165 def __add__(self, x):
2177 def __add__(self, x):
2166 l = baseset([r for r in self])
2178 l = baseset([r for r in self])
2167 return l + baseset(x)
2179 return l + baseset(x)
2168
2180
2169 def __nonzero__(self):
2181 def __nonzero__(self):
2170 for r in self:
2182 for r in self:
2171 return True
2183 return True
2172 return False
2184 return False
2173
2185
2174 def __len__(self):
2186 def __len__(self):
2175 # Basic implementation to be changed in future patches.
2187 # Basic implementation to be changed in future patches.
2176 l = baseset([r for r in self])
2188 l = baseset([r for r in self])
2177 return len(l)
2189 return len(l)
2178
2190
2179 def __getitem__(self, x):
2191 def __getitem__(self, x):
2180 # Basic implementation to be changed in future patches.
2192 # Basic implementation to be changed in future patches.
2181 l = baseset([r for r in self])
2193 l = baseset([r for r in self])
2182 return l[x]
2194 return l[x]
2183
2195
2184 def sort(self, reverse=False):
2196 def sort(self, reverse=False):
2185 # Basic implementation to be changed in future patches.
2197 # Basic implementation to be changed in future patches.
2186 self._subset = baseset(self._subset)
2198 self._subset = baseset(self._subset)
2187 self._subset.sort(reverse=reverse)
2199 self._subset.sort(reverse=reverse)
2188
2200
2189 def reverse(self):
2201 def reverse(self):
2190 self._subset.reverse()
2202 self._subset.reverse()
2191
2203
2192 def set(self):
2204 def set(self):
2193 return set([r for r in self])
2205 return set([r for r in self])
2194
2206
2195 class generatorset(object):
2207 class generatorset(object):
2196 """Wrapper structure for generators that provides lazy membership and can
2208 """Wrapper structure for generators that provides lazy membership and can
2197 be iterated more than once.
2209 be iterated more than once.
2198 When asked for membership it generates values until either it finds the
2210 When asked for membership it generates values until either it finds the
2199 requested one or has gone through all the elements in the generator
2211 requested one or has gone through all the elements in the generator
2200 """
2212 """
2201 def __init__(self, gen):
2213 def __init__(self, gen):
2202 self._gen = gen
2214 self._gen = gen
2203 self._iter = iter(gen)
2215 self._iter = iter(gen)
2204 self._cache = {}
2216 self._cache = {}
2205 self._genlist = baseset([])
2217 self._genlist = baseset([])
2206 self._iterated = False
2218 self._iterated = False
2207
2219
2208 def _nextitem(self):
2220 def _nextitem(self):
2209 l = self._iter.next()
2221 l = self._iter.next()
2210 self._cache[l] = True
2222 self._cache[l] = True
2211 self._genlist.append(l)
2223 self._genlist.append(l)
2212 return l
2224 return l
2213
2225
2214 def __contains__(self, x):
2226 def __contains__(self, x):
2215 if x in self._cache:
2227 if x in self._cache:
2216 return self._cache[x]
2228 return self._cache[x]
2217
2229
2218 self._iterated = True
2230 self._iterated = True
2219 while True:
2231 while True:
2220 try:
2232 try:
2221 l = self._nextitem()
2233 l = self._nextitem()
2222 if l == x:
2234 if l == x:
2223 return True
2235 return True
2224 except (StopIteration):
2236 except (StopIteration):
2225 break
2237 break
2226
2238
2227 self._cache[x] = False
2239 self._cache[x] = False
2228 return False
2240 return False
2229
2241
2230 def __iter__(self):
2242 def __iter__(self):
2231 if self._iterated:
2243 if self._iterated:
2232 for l in self._genlist:
2244 for l in self._genlist:
2233 yield l
2245 yield l
2234 while True:
2246 while True:
2235 try:
2247 try:
2236 item = self._nextitem()
2248 item = self._nextitem()
2237 yield item
2249 yield item
2238 except (StopIteration):
2250 except (StopIteration):
2239 break
2251 break
2240 else:
2252 else:
2241 self._iterated = True
2253 self._iterated = True
2242 for item in self._gen:
2254 for item in self._gen:
2243 self._cache[item] = True
2255 self._cache[item] = True
2244 self._genlist.append(item)
2256 self._genlist.append(item)
2245 yield item
2257 yield item
2246
2258
2247 def set(self):
2259 def set(self):
2248 return self
2260 return self
2249
2261
2250 class spanset(object):
2262 class spanset(object):
2251 """Duck type for baseset class which represents a range of revisions and
2263 """Duck type for baseset class which represents a range of revisions and
2252 can work lazily and without having all the range in memory
2264 can work lazily and without having all the range in memory
2253 """
2265 """
2254 def __init__(self, repo, start=0, end=None):
2266 def __init__(self, repo, start=0, end=None):
2255 self._start = start
2267 self._start = start
2256 if end is not None:
2268 if end is not None:
2257 self._end = end
2269 self._end = end
2258 else:
2270 else:
2259 self._end = len(repo)
2271 self._end = len(repo)
2260 self._hiddenrevs = repo.changelog.filteredrevs
2272 self._hiddenrevs = repo.changelog.filteredrevs
2261
2273
2262 def _contained(self, rev):
2274 def _contained(self, rev):
2263 return (rev <= self._start and rev > self._end) or (rev >= self._start
2275 return (rev <= self._start and rev > self._end) or (rev >= self._start
2264 and rev < self._end)
2276 and rev < self._end)
2265
2277
2266 def __iter__(self):
2278 def __iter__(self):
2267 if self._start <= self._end:
2279 if self._start <= self._end:
2268 iterrange = xrange(self._start, self._end)
2280 iterrange = xrange(self._start, self._end)
2269 else:
2281 else:
2270 iterrange = xrange(self._start, self._end, -1)
2282 iterrange = xrange(self._start, self._end, -1)
2271
2283
2272 if self._hiddenrevs:
2284 if self._hiddenrevs:
2273 s = self._hiddenrevs
2285 s = self._hiddenrevs
2274 for r in iterrange:
2286 for r in iterrange:
2275 if r not in s:
2287 if r not in s:
2276 yield r
2288 yield r
2277 else:
2289 else:
2278 for r in iterrange:
2290 for r in iterrange:
2279 yield r
2291 yield r
2280
2292
2281 def __contains__(self, x):
2293 def __contains__(self, x):
2282 return self._contained(x) and not (self._hiddenrevs and rev in
2294 return self._contained(x) and not (self._hiddenrevs and rev in
2283 self._hiddenrevs)
2295 self._hiddenrevs)
2284
2296
2285 def __and__(self, x):
2297 def __and__(self, x):
2286 if isinstance(x, baseset):
2298 if isinstance(x, baseset):
2287 x = x.set()
2299 x = x.set()
2288 return lazyset(self, lambda r: r in x)
2300 return lazyset(self, lambda r: r in x)
2289
2301
2290 def __sub__(self, x):
2302 def __sub__(self, x):
2291 if isinstance(x, baseset):
2303 if isinstance(x, baseset):
2292 x = x.set()
2304 x = x.set()
2293 return lazyset(self, lambda r: r not in x)
2305 return lazyset(self, lambda r: r not in x)
2294
2306
2295 def __add__(self, x):
2307 def __add__(self, x):
2296 l = baseset(self)
2308 l = baseset(self)
2297 return l + baseset(x)
2309 return l + baseset(x)
2298
2310
2299 def __len__(self):
2311 def __len__(self):
2300 if not self._hiddenrevs:
2312 if not self._hiddenrevs:
2301 return abs(self._end - self._start)
2313 return abs(self._end - self._start)
2302 else:
2314 else:
2303 count = 0
2315 count = 0
2304 for rev in self._hiddenrevs:
2316 for rev in self._hiddenrevs:
2305 if self._contained(rev):
2317 if self._contained(rev):
2306 count += 1
2318 count += 1
2307 return abs(self._end - self._start) - count
2319 return abs(self._end - self._start) - count
2308
2320
2309 def __getitem__(self, x):
2321 def __getitem__(self, x):
2310 # Basic implementation to be changed in future patches.
2322 # Basic implementation to be changed in future patches.
2311 l = baseset([r for r in self])
2323 l = baseset([r for r in self])
2312 return l[x]
2324 return l[x]
2313
2325
2314 def sort(self, reverse=False):
2326 def sort(self, reverse=False):
2315 # Basic implementation to be changed in future patches.
2327 # Basic implementation to be changed in future patches.
2316 if reverse:
2328 if reverse:
2317 self.reverse()
2329 self.reverse()
2318
2330
2319 def reverse(self):
2331 def reverse(self):
2320 if self._start <= self._end:
2332 if self._start <= self._end:
2321 self._start, self._end = self._end - 1, self._start - 1
2333 self._start, self._end = self._end - 1, self._start - 1
2322 else:
2334 else:
2323 self._start, self._end = self._end + 1, self._start + 1
2335 self._start, self._end = self._end + 1, self._start + 1
2324
2336
2325 def set(self):
2337 def set(self):
2326 return self
2338 return self
2327
2339
2328 # tell hggettext to extract docstrings from these functions:
2340 # tell hggettext to extract docstrings from these functions:
2329 i18nfunctions = symbols.values()
2341 i18nfunctions = symbols.values()
General Comments 0
You need to be logged in to leave comments. Login now