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