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