##// END OF EJS Templates
revset: make repo.anyrevs accept customized alias override (API)...
Jun Wu -
r33336:4672db16 default
parent child Browse files
Show More
@@ -1,2248 +1,2250 b''
1 # debugcommands.py - command processing for debug* commands
1 # debugcommands.py - command processing for debug* commands
2 #
2 #
3 # Copyright 2005-2016 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2016 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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import difflib
10 import difflib
11 import errno
11 import errno
12 import operator
12 import operator
13 import os
13 import os
14 import random
14 import random
15 import socket
15 import socket
16 import string
16 import string
17 import sys
17 import sys
18 import tempfile
18 import tempfile
19 import time
19 import time
20
20
21 from .i18n import _
21 from .i18n import _
22 from .node import (
22 from .node import (
23 bin,
23 bin,
24 hex,
24 hex,
25 nullhex,
25 nullhex,
26 nullid,
26 nullid,
27 nullrev,
27 nullrev,
28 short,
28 short,
29 )
29 )
30 from . import (
30 from . import (
31 bundle2,
31 bundle2,
32 changegroup,
32 changegroup,
33 cmdutil,
33 cmdutil,
34 color,
34 color,
35 context,
35 context,
36 dagparser,
36 dagparser,
37 dagutil,
37 dagutil,
38 encoding,
38 encoding,
39 error,
39 error,
40 exchange,
40 exchange,
41 extensions,
41 extensions,
42 filemerge,
42 filemerge,
43 fileset,
43 fileset,
44 formatter,
44 formatter,
45 hg,
45 hg,
46 localrepo,
46 localrepo,
47 lock as lockmod,
47 lock as lockmod,
48 merge as mergemod,
48 merge as mergemod,
49 obsolete,
49 obsolete,
50 obsutil,
50 obsutil,
51 phases,
51 phases,
52 policy,
52 policy,
53 pvec,
53 pvec,
54 pycompat,
54 pycompat,
55 registrar,
55 registrar,
56 repair,
56 repair,
57 revlog,
57 revlog,
58 revset,
58 revset,
59 revsetlang,
59 revsetlang,
60 scmutil,
60 scmutil,
61 setdiscovery,
61 setdiscovery,
62 simplemerge,
62 simplemerge,
63 smartset,
63 smartset,
64 sslutil,
64 sslutil,
65 streamclone,
65 streamclone,
66 templater,
66 templater,
67 treediscovery,
67 treediscovery,
68 upgrade,
68 upgrade,
69 util,
69 util,
70 vfs as vfsmod,
70 vfs as vfsmod,
71 )
71 )
72
72
73 release = lockmod.release
73 release = lockmod.release
74
74
75 command = registrar.command()
75 command = registrar.command()
76
76
77 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
77 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
78 def debugancestor(ui, repo, *args):
78 def debugancestor(ui, repo, *args):
79 """find the ancestor revision of two revisions in a given index"""
79 """find the ancestor revision of two revisions in a given index"""
80 if len(args) == 3:
80 if len(args) == 3:
81 index, rev1, rev2 = args
81 index, rev1, rev2 = args
82 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False), index)
82 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False), index)
83 lookup = r.lookup
83 lookup = r.lookup
84 elif len(args) == 2:
84 elif len(args) == 2:
85 if not repo:
85 if not repo:
86 raise error.Abort(_('there is no Mercurial repository here '
86 raise error.Abort(_('there is no Mercurial repository here '
87 '(.hg not found)'))
87 '(.hg not found)'))
88 rev1, rev2 = args
88 rev1, rev2 = args
89 r = repo.changelog
89 r = repo.changelog
90 lookup = repo.lookup
90 lookup = repo.lookup
91 else:
91 else:
92 raise error.Abort(_('either two or three arguments required'))
92 raise error.Abort(_('either two or three arguments required'))
93 a = r.ancestor(lookup(rev1), lookup(rev2))
93 a = r.ancestor(lookup(rev1), lookup(rev2))
94 ui.write('%d:%s\n' % (r.rev(a), hex(a)))
94 ui.write('%d:%s\n' % (r.rev(a), hex(a)))
95
95
96 @command('debugapplystreamclonebundle', [], 'FILE')
96 @command('debugapplystreamclonebundle', [], 'FILE')
97 def debugapplystreamclonebundle(ui, repo, fname):
97 def debugapplystreamclonebundle(ui, repo, fname):
98 """apply a stream clone bundle file"""
98 """apply a stream clone bundle file"""
99 f = hg.openpath(ui, fname)
99 f = hg.openpath(ui, fname)
100 gen = exchange.readbundle(ui, f, fname)
100 gen = exchange.readbundle(ui, f, fname)
101 gen.apply(repo)
101 gen.apply(repo)
102
102
103 @command('debugbuilddag',
103 @command('debugbuilddag',
104 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
104 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
105 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
105 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
106 ('n', 'new-file', None, _('add new file at each rev'))],
106 ('n', 'new-file', None, _('add new file at each rev'))],
107 _('[OPTION]... [TEXT]'))
107 _('[OPTION]... [TEXT]'))
108 def debugbuilddag(ui, repo, text=None,
108 def debugbuilddag(ui, repo, text=None,
109 mergeable_file=False,
109 mergeable_file=False,
110 overwritten_file=False,
110 overwritten_file=False,
111 new_file=False):
111 new_file=False):
112 """builds a repo with a given DAG from scratch in the current empty repo
112 """builds a repo with a given DAG from scratch in the current empty repo
113
113
114 The description of the DAG is read from stdin if not given on the
114 The description of the DAG is read from stdin if not given on the
115 command line.
115 command line.
116
116
117 Elements:
117 Elements:
118
118
119 - "+n" is a linear run of n nodes based on the current default parent
119 - "+n" is a linear run of n nodes based on the current default parent
120 - "." is a single node based on the current default parent
120 - "." is a single node based on the current default parent
121 - "$" resets the default parent to null (implied at the start);
121 - "$" resets the default parent to null (implied at the start);
122 otherwise the default parent is always the last node created
122 otherwise the default parent is always the last node created
123 - "<p" sets the default parent to the backref p
123 - "<p" sets the default parent to the backref p
124 - "*p" is a fork at parent p, which is a backref
124 - "*p" is a fork at parent p, which is a backref
125 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
125 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
126 - "/p2" is a merge of the preceding node and p2
126 - "/p2" is a merge of the preceding node and p2
127 - ":tag" defines a local tag for the preceding node
127 - ":tag" defines a local tag for the preceding node
128 - "@branch" sets the named branch for subsequent nodes
128 - "@branch" sets the named branch for subsequent nodes
129 - "#...\\n" is a comment up to the end of the line
129 - "#...\\n" is a comment up to the end of the line
130
130
131 Whitespace between the above elements is ignored.
131 Whitespace between the above elements is ignored.
132
132
133 A backref is either
133 A backref is either
134
134
135 - a number n, which references the node curr-n, where curr is the current
135 - a number n, which references the node curr-n, where curr is the current
136 node, or
136 node, or
137 - the name of a local tag you placed earlier using ":tag", or
137 - the name of a local tag you placed earlier using ":tag", or
138 - empty to denote the default parent.
138 - empty to denote the default parent.
139
139
140 All string valued-elements are either strictly alphanumeric, or must
140 All string valued-elements are either strictly alphanumeric, or must
141 be enclosed in double quotes ("..."), with "\\" as escape character.
141 be enclosed in double quotes ("..."), with "\\" as escape character.
142 """
142 """
143
143
144 if text is None:
144 if text is None:
145 ui.status(_("reading DAG from stdin\n"))
145 ui.status(_("reading DAG from stdin\n"))
146 text = ui.fin.read()
146 text = ui.fin.read()
147
147
148 cl = repo.changelog
148 cl = repo.changelog
149 if len(cl) > 0:
149 if len(cl) > 0:
150 raise error.Abort(_('repository is not empty'))
150 raise error.Abort(_('repository is not empty'))
151
151
152 # determine number of revs in DAG
152 # determine number of revs in DAG
153 total = 0
153 total = 0
154 for type, data in dagparser.parsedag(text):
154 for type, data in dagparser.parsedag(text):
155 if type == 'n':
155 if type == 'n':
156 total += 1
156 total += 1
157
157
158 if mergeable_file:
158 if mergeable_file:
159 linesperrev = 2
159 linesperrev = 2
160 # make a file with k lines per rev
160 # make a file with k lines per rev
161 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
161 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
162 initialmergedlines.append("")
162 initialmergedlines.append("")
163
163
164 tags = []
164 tags = []
165
165
166 wlock = lock = tr = None
166 wlock = lock = tr = None
167 try:
167 try:
168 wlock = repo.wlock()
168 wlock = repo.wlock()
169 lock = repo.lock()
169 lock = repo.lock()
170 tr = repo.transaction("builddag")
170 tr = repo.transaction("builddag")
171
171
172 at = -1
172 at = -1
173 atbranch = 'default'
173 atbranch = 'default'
174 nodeids = []
174 nodeids = []
175 id = 0
175 id = 0
176 ui.progress(_('building'), id, unit=_('revisions'), total=total)
176 ui.progress(_('building'), id, unit=_('revisions'), total=total)
177 for type, data in dagparser.parsedag(text):
177 for type, data in dagparser.parsedag(text):
178 if type == 'n':
178 if type == 'n':
179 ui.note(('node %s\n' % str(data)))
179 ui.note(('node %s\n' % str(data)))
180 id, ps = data
180 id, ps = data
181
181
182 files = []
182 files = []
183 fctxs = {}
183 fctxs = {}
184
184
185 p2 = None
185 p2 = None
186 if mergeable_file:
186 if mergeable_file:
187 fn = "mf"
187 fn = "mf"
188 p1 = repo[ps[0]]
188 p1 = repo[ps[0]]
189 if len(ps) > 1:
189 if len(ps) > 1:
190 p2 = repo[ps[1]]
190 p2 = repo[ps[1]]
191 pa = p1.ancestor(p2)
191 pa = p1.ancestor(p2)
192 base, local, other = [x[fn].data() for x in (pa, p1,
192 base, local, other = [x[fn].data() for x in (pa, p1,
193 p2)]
193 p2)]
194 m3 = simplemerge.Merge3Text(base, local, other)
194 m3 = simplemerge.Merge3Text(base, local, other)
195 ml = [l.strip() for l in m3.merge_lines()]
195 ml = [l.strip() for l in m3.merge_lines()]
196 ml.append("")
196 ml.append("")
197 elif at > 0:
197 elif at > 0:
198 ml = p1[fn].data().split("\n")
198 ml = p1[fn].data().split("\n")
199 else:
199 else:
200 ml = initialmergedlines
200 ml = initialmergedlines
201 ml[id * linesperrev] += " r%i" % id
201 ml[id * linesperrev] += " r%i" % id
202 mergedtext = "\n".join(ml)
202 mergedtext = "\n".join(ml)
203 files.append(fn)
203 files.append(fn)
204 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
204 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
205
205
206 if overwritten_file:
206 if overwritten_file:
207 fn = "of"
207 fn = "of"
208 files.append(fn)
208 files.append(fn)
209 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
209 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
210
210
211 if new_file:
211 if new_file:
212 fn = "nf%i" % id
212 fn = "nf%i" % id
213 files.append(fn)
213 files.append(fn)
214 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
214 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
215 if len(ps) > 1:
215 if len(ps) > 1:
216 if not p2:
216 if not p2:
217 p2 = repo[ps[1]]
217 p2 = repo[ps[1]]
218 for fn in p2:
218 for fn in p2:
219 if fn.startswith("nf"):
219 if fn.startswith("nf"):
220 files.append(fn)
220 files.append(fn)
221 fctxs[fn] = p2[fn]
221 fctxs[fn] = p2[fn]
222
222
223 def fctxfn(repo, cx, path):
223 def fctxfn(repo, cx, path):
224 return fctxs.get(path)
224 return fctxs.get(path)
225
225
226 if len(ps) == 0 or ps[0] < 0:
226 if len(ps) == 0 or ps[0] < 0:
227 pars = [None, None]
227 pars = [None, None]
228 elif len(ps) == 1:
228 elif len(ps) == 1:
229 pars = [nodeids[ps[0]], None]
229 pars = [nodeids[ps[0]], None]
230 else:
230 else:
231 pars = [nodeids[p] for p in ps]
231 pars = [nodeids[p] for p in ps]
232 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
232 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
233 date=(id, 0),
233 date=(id, 0),
234 user="debugbuilddag",
234 user="debugbuilddag",
235 extra={'branch': atbranch})
235 extra={'branch': atbranch})
236 nodeid = repo.commitctx(cx)
236 nodeid = repo.commitctx(cx)
237 nodeids.append(nodeid)
237 nodeids.append(nodeid)
238 at = id
238 at = id
239 elif type == 'l':
239 elif type == 'l':
240 id, name = data
240 id, name = data
241 ui.note(('tag %s\n' % name))
241 ui.note(('tag %s\n' % name))
242 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
242 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
243 elif type == 'a':
243 elif type == 'a':
244 ui.note(('branch %s\n' % data))
244 ui.note(('branch %s\n' % data))
245 atbranch = data
245 atbranch = data
246 ui.progress(_('building'), id, unit=_('revisions'), total=total)
246 ui.progress(_('building'), id, unit=_('revisions'), total=total)
247 tr.close()
247 tr.close()
248
248
249 if tags:
249 if tags:
250 repo.vfs.write("localtags", "".join(tags))
250 repo.vfs.write("localtags", "".join(tags))
251 finally:
251 finally:
252 ui.progress(_('building'), None)
252 ui.progress(_('building'), None)
253 release(tr, lock, wlock)
253 release(tr, lock, wlock)
254
254
255 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
255 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
256 indent_string = ' ' * indent
256 indent_string = ' ' * indent
257 if all:
257 if all:
258 ui.write(("%sformat: id, p1, p2, cset, delta base, len(delta)\n")
258 ui.write(("%sformat: id, p1, p2, cset, delta base, len(delta)\n")
259 % indent_string)
259 % indent_string)
260
260
261 def showchunks(named):
261 def showchunks(named):
262 ui.write("\n%s%s\n" % (indent_string, named))
262 ui.write("\n%s%s\n" % (indent_string, named))
263 chain = None
263 chain = None
264 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
264 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
265 node = chunkdata['node']
265 node = chunkdata['node']
266 p1 = chunkdata['p1']
266 p1 = chunkdata['p1']
267 p2 = chunkdata['p2']
267 p2 = chunkdata['p2']
268 cs = chunkdata['cs']
268 cs = chunkdata['cs']
269 deltabase = chunkdata['deltabase']
269 deltabase = chunkdata['deltabase']
270 delta = chunkdata['delta']
270 delta = chunkdata['delta']
271 ui.write("%s%s %s %s %s %s %s\n" %
271 ui.write("%s%s %s %s %s %s %s\n" %
272 (indent_string, hex(node), hex(p1), hex(p2),
272 (indent_string, hex(node), hex(p1), hex(p2),
273 hex(cs), hex(deltabase), len(delta)))
273 hex(cs), hex(deltabase), len(delta)))
274 chain = node
274 chain = node
275
275
276 chunkdata = gen.changelogheader()
276 chunkdata = gen.changelogheader()
277 showchunks("changelog")
277 showchunks("changelog")
278 chunkdata = gen.manifestheader()
278 chunkdata = gen.manifestheader()
279 showchunks("manifest")
279 showchunks("manifest")
280 for chunkdata in iter(gen.filelogheader, {}):
280 for chunkdata in iter(gen.filelogheader, {}):
281 fname = chunkdata['filename']
281 fname = chunkdata['filename']
282 showchunks(fname)
282 showchunks(fname)
283 else:
283 else:
284 if isinstance(gen, bundle2.unbundle20):
284 if isinstance(gen, bundle2.unbundle20):
285 raise error.Abort(_('use debugbundle2 for this file'))
285 raise error.Abort(_('use debugbundle2 for this file'))
286 chunkdata = gen.changelogheader()
286 chunkdata = gen.changelogheader()
287 chain = None
287 chain = None
288 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
288 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
289 node = chunkdata['node']
289 node = chunkdata['node']
290 ui.write("%s%s\n" % (indent_string, hex(node)))
290 ui.write("%s%s\n" % (indent_string, hex(node)))
291 chain = node
291 chain = node
292
292
293 def _debugobsmarkers(ui, part, indent=0, **opts):
293 def _debugobsmarkers(ui, part, indent=0, **opts):
294 """display version and markers contained in 'data'"""
294 """display version and markers contained in 'data'"""
295 opts = pycompat.byteskwargs(opts)
295 opts = pycompat.byteskwargs(opts)
296 data = part.read()
296 data = part.read()
297 indent_string = ' ' * indent
297 indent_string = ' ' * indent
298 try:
298 try:
299 version, markers = obsolete._readmarkers(data)
299 version, markers = obsolete._readmarkers(data)
300 except error.UnknownVersion as exc:
300 except error.UnknownVersion as exc:
301 msg = "%sunsupported version: %s (%d bytes)\n"
301 msg = "%sunsupported version: %s (%d bytes)\n"
302 msg %= indent_string, exc.version, len(data)
302 msg %= indent_string, exc.version, len(data)
303 ui.write(msg)
303 ui.write(msg)
304 else:
304 else:
305 msg = "%sversion: %s (%d bytes)\n"
305 msg = "%sversion: %s (%d bytes)\n"
306 msg %= indent_string, version, len(data)
306 msg %= indent_string, version, len(data)
307 ui.write(msg)
307 ui.write(msg)
308 fm = ui.formatter('debugobsolete', opts)
308 fm = ui.formatter('debugobsolete', opts)
309 for rawmarker in sorted(markers):
309 for rawmarker in sorted(markers):
310 m = obsutil.marker(None, rawmarker)
310 m = obsutil.marker(None, rawmarker)
311 fm.startitem()
311 fm.startitem()
312 fm.plain(indent_string)
312 fm.plain(indent_string)
313 cmdutil.showmarker(fm, m)
313 cmdutil.showmarker(fm, m)
314 fm.end()
314 fm.end()
315
315
316 def _debugphaseheads(ui, data, indent=0):
316 def _debugphaseheads(ui, data, indent=0):
317 """display version and markers contained in 'data'"""
317 """display version and markers contained in 'data'"""
318 indent_string = ' ' * indent
318 indent_string = ' ' * indent
319 headsbyphase = bundle2._readphaseheads(data)
319 headsbyphase = bundle2._readphaseheads(data)
320 for phase in phases.allphases:
320 for phase in phases.allphases:
321 for head in headsbyphase[phase]:
321 for head in headsbyphase[phase]:
322 ui.write(indent_string)
322 ui.write(indent_string)
323 ui.write('%s %s\n' % (hex(head), phases.phasenames[phase]))
323 ui.write('%s %s\n' % (hex(head), phases.phasenames[phase]))
324
324
325 def _debugbundle2(ui, gen, all=None, **opts):
325 def _debugbundle2(ui, gen, all=None, **opts):
326 """lists the contents of a bundle2"""
326 """lists the contents of a bundle2"""
327 if not isinstance(gen, bundle2.unbundle20):
327 if not isinstance(gen, bundle2.unbundle20):
328 raise error.Abort(_('not a bundle2 file'))
328 raise error.Abort(_('not a bundle2 file'))
329 ui.write(('Stream params: %s\n' % repr(gen.params)))
329 ui.write(('Stream params: %s\n' % repr(gen.params)))
330 parttypes = opts.get(r'part_type', [])
330 parttypes = opts.get(r'part_type', [])
331 for part in gen.iterparts():
331 for part in gen.iterparts():
332 if parttypes and part.type not in parttypes:
332 if parttypes and part.type not in parttypes:
333 continue
333 continue
334 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
334 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
335 if part.type == 'changegroup':
335 if part.type == 'changegroup':
336 version = part.params.get('version', '01')
336 version = part.params.get('version', '01')
337 cg = changegroup.getunbundler(version, part, 'UN')
337 cg = changegroup.getunbundler(version, part, 'UN')
338 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
338 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
339 if part.type == 'obsmarkers':
339 if part.type == 'obsmarkers':
340 _debugobsmarkers(ui, part, indent=4, **opts)
340 _debugobsmarkers(ui, part, indent=4, **opts)
341 if part.type == 'phase-heads':
341 if part.type == 'phase-heads':
342 _debugphaseheads(ui, part, indent=4)
342 _debugphaseheads(ui, part, indent=4)
343
343
344 @command('debugbundle',
344 @command('debugbundle',
345 [('a', 'all', None, _('show all details')),
345 [('a', 'all', None, _('show all details')),
346 ('', 'part-type', [], _('show only the named part type')),
346 ('', 'part-type', [], _('show only the named part type')),
347 ('', 'spec', None, _('print the bundlespec of the bundle'))],
347 ('', 'spec', None, _('print the bundlespec of the bundle'))],
348 _('FILE'),
348 _('FILE'),
349 norepo=True)
349 norepo=True)
350 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
350 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
351 """lists the contents of a bundle"""
351 """lists the contents of a bundle"""
352 with hg.openpath(ui, bundlepath) as f:
352 with hg.openpath(ui, bundlepath) as f:
353 if spec:
353 if spec:
354 spec = exchange.getbundlespec(ui, f)
354 spec = exchange.getbundlespec(ui, f)
355 ui.write('%s\n' % spec)
355 ui.write('%s\n' % spec)
356 return
356 return
357
357
358 gen = exchange.readbundle(ui, f, bundlepath)
358 gen = exchange.readbundle(ui, f, bundlepath)
359 if isinstance(gen, bundle2.unbundle20):
359 if isinstance(gen, bundle2.unbundle20):
360 return _debugbundle2(ui, gen, all=all, **opts)
360 return _debugbundle2(ui, gen, all=all, **opts)
361 _debugchangegroup(ui, gen, all=all, **opts)
361 _debugchangegroup(ui, gen, all=all, **opts)
362
362
363 @command('debugcheckstate', [], '')
363 @command('debugcheckstate', [], '')
364 def debugcheckstate(ui, repo):
364 def debugcheckstate(ui, repo):
365 """validate the correctness of the current dirstate"""
365 """validate the correctness of the current dirstate"""
366 parent1, parent2 = repo.dirstate.parents()
366 parent1, parent2 = repo.dirstate.parents()
367 m1 = repo[parent1].manifest()
367 m1 = repo[parent1].manifest()
368 m2 = repo[parent2].manifest()
368 m2 = repo[parent2].manifest()
369 errors = 0
369 errors = 0
370 for f in repo.dirstate:
370 for f in repo.dirstate:
371 state = repo.dirstate[f]
371 state = repo.dirstate[f]
372 if state in "nr" and f not in m1:
372 if state in "nr" and f not in m1:
373 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
373 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
374 errors += 1
374 errors += 1
375 if state in "a" and f in m1:
375 if state in "a" and f in m1:
376 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
376 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
377 errors += 1
377 errors += 1
378 if state in "m" and f not in m1 and f not in m2:
378 if state in "m" and f not in m1 and f not in m2:
379 ui.warn(_("%s in state %s, but not in either manifest\n") %
379 ui.warn(_("%s in state %s, but not in either manifest\n") %
380 (f, state))
380 (f, state))
381 errors += 1
381 errors += 1
382 for f in m1:
382 for f in m1:
383 state = repo.dirstate[f]
383 state = repo.dirstate[f]
384 if state not in "nrm":
384 if state not in "nrm":
385 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
385 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
386 errors += 1
386 errors += 1
387 if errors:
387 if errors:
388 error = _(".hg/dirstate inconsistent with current parent's manifest")
388 error = _(".hg/dirstate inconsistent with current parent's manifest")
389 raise error.Abort(error)
389 raise error.Abort(error)
390
390
391 @command('debugcolor',
391 @command('debugcolor',
392 [('', 'style', None, _('show all configured styles'))],
392 [('', 'style', None, _('show all configured styles'))],
393 'hg debugcolor')
393 'hg debugcolor')
394 def debugcolor(ui, repo, **opts):
394 def debugcolor(ui, repo, **opts):
395 """show available color, effects or style"""
395 """show available color, effects or style"""
396 ui.write(('color mode: %s\n') % ui._colormode)
396 ui.write(('color mode: %s\n') % ui._colormode)
397 if opts.get(r'style'):
397 if opts.get(r'style'):
398 return _debugdisplaystyle(ui)
398 return _debugdisplaystyle(ui)
399 else:
399 else:
400 return _debugdisplaycolor(ui)
400 return _debugdisplaycolor(ui)
401
401
402 def _debugdisplaycolor(ui):
402 def _debugdisplaycolor(ui):
403 ui = ui.copy()
403 ui = ui.copy()
404 ui._styles.clear()
404 ui._styles.clear()
405 for effect in color._activeeffects(ui).keys():
405 for effect in color._activeeffects(ui).keys():
406 ui._styles[effect] = effect
406 ui._styles[effect] = effect
407 if ui._terminfoparams:
407 if ui._terminfoparams:
408 for k, v in ui.configitems('color'):
408 for k, v in ui.configitems('color'):
409 if k.startswith('color.'):
409 if k.startswith('color.'):
410 ui._styles[k] = k[6:]
410 ui._styles[k] = k[6:]
411 elif k.startswith('terminfo.'):
411 elif k.startswith('terminfo.'):
412 ui._styles[k] = k[9:]
412 ui._styles[k] = k[9:]
413 ui.write(_('available colors:\n'))
413 ui.write(_('available colors:\n'))
414 # sort label with a '_' after the other to group '_background' entry.
414 # sort label with a '_' after the other to group '_background' entry.
415 items = sorted(ui._styles.items(),
415 items = sorted(ui._styles.items(),
416 key=lambda i: ('_' in i[0], i[0], i[1]))
416 key=lambda i: ('_' in i[0], i[0], i[1]))
417 for colorname, label in items:
417 for colorname, label in items:
418 ui.write(('%s\n') % colorname, label=label)
418 ui.write(('%s\n') % colorname, label=label)
419
419
420 def _debugdisplaystyle(ui):
420 def _debugdisplaystyle(ui):
421 ui.write(_('available style:\n'))
421 ui.write(_('available style:\n'))
422 width = max(len(s) for s in ui._styles)
422 width = max(len(s) for s in ui._styles)
423 for label, effects in sorted(ui._styles.items()):
423 for label, effects in sorted(ui._styles.items()):
424 ui.write('%s' % label, label=label)
424 ui.write('%s' % label, label=label)
425 if effects:
425 if effects:
426 # 50
426 # 50
427 ui.write(': ')
427 ui.write(': ')
428 ui.write(' ' * (max(0, width - len(label))))
428 ui.write(' ' * (max(0, width - len(label))))
429 ui.write(', '.join(ui.label(e, e) for e in effects.split()))
429 ui.write(', '.join(ui.label(e, e) for e in effects.split()))
430 ui.write('\n')
430 ui.write('\n')
431
431
432 @command('debugcreatestreamclonebundle', [], 'FILE')
432 @command('debugcreatestreamclonebundle', [], 'FILE')
433 def debugcreatestreamclonebundle(ui, repo, fname):
433 def debugcreatestreamclonebundle(ui, repo, fname):
434 """create a stream clone bundle file
434 """create a stream clone bundle file
435
435
436 Stream bundles are special bundles that are essentially archives of
436 Stream bundles are special bundles that are essentially archives of
437 revlog files. They are commonly used for cloning very quickly.
437 revlog files. They are commonly used for cloning very quickly.
438 """
438 """
439 # TODO we may want to turn this into an abort when this functionality
439 # TODO we may want to turn this into an abort when this functionality
440 # is moved into `hg bundle`.
440 # is moved into `hg bundle`.
441 if phases.hassecret(repo):
441 if phases.hassecret(repo):
442 ui.warn(_('(warning: stream clone bundle will contain secret '
442 ui.warn(_('(warning: stream clone bundle will contain secret '
443 'revisions)\n'))
443 'revisions)\n'))
444
444
445 requirements, gen = streamclone.generatebundlev1(repo)
445 requirements, gen = streamclone.generatebundlev1(repo)
446 changegroup.writechunks(ui, gen, fname)
446 changegroup.writechunks(ui, gen, fname)
447
447
448 ui.write(_('bundle requirements: %s\n') % ', '.join(sorted(requirements)))
448 ui.write(_('bundle requirements: %s\n') % ', '.join(sorted(requirements)))
449
449
450 @command('debugdag',
450 @command('debugdag',
451 [('t', 'tags', None, _('use tags as labels')),
451 [('t', 'tags', None, _('use tags as labels')),
452 ('b', 'branches', None, _('annotate with branch names')),
452 ('b', 'branches', None, _('annotate with branch names')),
453 ('', 'dots', None, _('use dots for runs')),
453 ('', 'dots', None, _('use dots for runs')),
454 ('s', 'spaces', None, _('separate elements by spaces'))],
454 ('s', 'spaces', None, _('separate elements by spaces'))],
455 _('[OPTION]... [FILE [REV]...]'),
455 _('[OPTION]... [FILE [REV]...]'),
456 optionalrepo=True)
456 optionalrepo=True)
457 def debugdag(ui, repo, file_=None, *revs, **opts):
457 def debugdag(ui, repo, file_=None, *revs, **opts):
458 """format the changelog or an index DAG as a concise textual description
458 """format the changelog or an index DAG as a concise textual description
459
459
460 If you pass a revlog index, the revlog's DAG is emitted. If you list
460 If you pass a revlog index, the revlog's DAG is emitted. If you list
461 revision numbers, they get labeled in the output as rN.
461 revision numbers, they get labeled in the output as rN.
462
462
463 Otherwise, the changelog DAG of the current repo is emitted.
463 Otherwise, the changelog DAG of the current repo is emitted.
464 """
464 """
465 spaces = opts.get(r'spaces')
465 spaces = opts.get(r'spaces')
466 dots = opts.get(r'dots')
466 dots = opts.get(r'dots')
467 if file_:
467 if file_:
468 rlog = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
468 rlog = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
469 file_)
469 file_)
470 revs = set((int(r) for r in revs))
470 revs = set((int(r) for r in revs))
471 def events():
471 def events():
472 for r in rlog:
472 for r in rlog:
473 yield 'n', (r, list(p for p in rlog.parentrevs(r)
473 yield 'n', (r, list(p for p in rlog.parentrevs(r)
474 if p != -1))
474 if p != -1))
475 if r in revs:
475 if r in revs:
476 yield 'l', (r, "r%i" % r)
476 yield 'l', (r, "r%i" % r)
477 elif repo:
477 elif repo:
478 cl = repo.changelog
478 cl = repo.changelog
479 tags = opts.get(r'tags')
479 tags = opts.get(r'tags')
480 branches = opts.get(r'branches')
480 branches = opts.get(r'branches')
481 if tags:
481 if tags:
482 labels = {}
482 labels = {}
483 for l, n in repo.tags().items():
483 for l, n in repo.tags().items():
484 labels.setdefault(cl.rev(n), []).append(l)
484 labels.setdefault(cl.rev(n), []).append(l)
485 def events():
485 def events():
486 b = "default"
486 b = "default"
487 for r in cl:
487 for r in cl:
488 if branches:
488 if branches:
489 newb = cl.read(cl.node(r))[5]['branch']
489 newb = cl.read(cl.node(r))[5]['branch']
490 if newb != b:
490 if newb != b:
491 yield 'a', newb
491 yield 'a', newb
492 b = newb
492 b = newb
493 yield 'n', (r, list(p for p in cl.parentrevs(r)
493 yield 'n', (r, list(p for p in cl.parentrevs(r)
494 if p != -1))
494 if p != -1))
495 if tags:
495 if tags:
496 ls = labels.get(r)
496 ls = labels.get(r)
497 if ls:
497 if ls:
498 for l in ls:
498 for l in ls:
499 yield 'l', (r, l)
499 yield 'l', (r, l)
500 else:
500 else:
501 raise error.Abort(_('need repo for changelog dag'))
501 raise error.Abort(_('need repo for changelog dag'))
502
502
503 for line in dagparser.dagtextlines(events(),
503 for line in dagparser.dagtextlines(events(),
504 addspaces=spaces,
504 addspaces=spaces,
505 wraplabels=True,
505 wraplabels=True,
506 wrapannotations=True,
506 wrapannotations=True,
507 wrapnonlinear=dots,
507 wrapnonlinear=dots,
508 usedots=dots,
508 usedots=dots,
509 maxlinewidth=70):
509 maxlinewidth=70):
510 ui.write(line)
510 ui.write(line)
511 ui.write("\n")
511 ui.write("\n")
512
512
513 @command('debugdata', cmdutil.debugrevlogopts, _('-c|-m|FILE REV'))
513 @command('debugdata', cmdutil.debugrevlogopts, _('-c|-m|FILE REV'))
514 def debugdata(ui, repo, file_, rev=None, **opts):
514 def debugdata(ui, repo, file_, rev=None, **opts):
515 """dump the contents of a data file revision"""
515 """dump the contents of a data file revision"""
516 opts = pycompat.byteskwargs(opts)
516 opts = pycompat.byteskwargs(opts)
517 if opts.get('changelog') or opts.get('manifest') or opts.get('dir'):
517 if opts.get('changelog') or opts.get('manifest') or opts.get('dir'):
518 if rev is not None:
518 if rev is not None:
519 raise error.CommandError('debugdata', _('invalid arguments'))
519 raise error.CommandError('debugdata', _('invalid arguments'))
520 file_, rev = None, file_
520 file_, rev = None, file_
521 elif rev is None:
521 elif rev is None:
522 raise error.CommandError('debugdata', _('invalid arguments'))
522 raise error.CommandError('debugdata', _('invalid arguments'))
523 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
523 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
524 try:
524 try:
525 ui.write(r.revision(r.lookup(rev), raw=True))
525 ui.write(r.revision(r.lookup(rev), raw=True))
526 except KeyError:
526 except KeyError:
527 raise error.Abort(_('invalid revision identifier %s') % rev)
527 raise error.Abort(_('invalid revision identifier %s') % rev)
528
528
529 @command('debugdate',
529 @command('debugdate',
530 [('e', 'extended', None, _('try extended date formats'))],
530 [('e', 'extended', None, _('try extended date formats'))],
531 _('[-e] DATE [RANGE]'),
531 _('[-e] DATE [RANGE]'),
532 norepo=True, optionalrepo=True)
532 norepo=True, optionalrepo=True)
533 def debugdate(ui, date, range=None, **opts):
533 def debugdate(ui, date, range=None, **opts):
534 """parse and display a date"""
534 """parse and display a date"""
535 if opts[r"extended"]:
535 if opts[r"extended"]:
536 d = util.parsedate(date, util.extendeddateformats)
536 d = util.parsedate(date, util.extendeddateformats)
537 else:
537 else:
538 d = util.parsedate(date)
538 d = util.parsedate(date)
539 ui.write(("internal: %s %s\n") % d)
539 ui.write(("internal: %s %s\n") % d)
540 ui.write(("standard: %s\n") % util.datestr(d))
540 ui.write(("standard: %s\n") % util.datestr(d))
541 if range:
541 if range:
542 m = util.matchdate(range)
542 m = util.matchdate(range)
543 ui.write(("match: %s\n") % m(d[0]))
543 ui.write(("match: %s\n") % m(d[0]))
544
544
545 @command('debugdeltachain',
545 @command('debugdeltachain',
546 cmdutil.debugrevlogopts + cmdutil.formatteropts,
546 cmdutil.debugrevlogopts + cmdutil.formatteropts,
547 _('-c|-m|FILE'),
547 _('-c|-m|FILE'),
548 optionalrepo=True)
548 optionalrepo=True)
549 def debugdeltachain(ui, repo, file_=None, **opts):
549 def debugdeltachain(ui, repo, file_=None, **opts):
550 """dump information about delta chains in a revlog
550 """dump information about delta chains in a revlog
551
551
552 Output can be templatized. Available template keywords are:
552 Output can be templatized. Available template keywords are:
553
553
554 :``rev``: revision number
554 :``rev``: revision number
555 :``chainid``: delta chain identifier (numbered by unique base)
555 :``chainid``: delta chain identifier (numbered by unique base)
556 :``chainlen``: delta chain length to this revision
556 :``chainlen``: delta chain length to this revision
557 :``prevrev``: previous revision in delta chain
557 :``prevrev``: previous revision in delta chain
558 :``deltatype``: role of delta / how it was computed
558 :``deltatype``: role of delta / how it was computed
559 :``compsize``: compressed size of revision
559 :``compsize``: compressed size of revision
560 :``uncompsize``: uncompressed size of revision
560 :``uncompsize``: uncompressed size of revision
561 :``chainsize``: total size of compressed revisions in chain
561 :``chainsize``: total size of compressed revisions in chain
562 :``chainratio``: total chain size divided by uncompressed revision size
562 :``chainratio``: total chain size divided by uncompressed revision size
563 (new delta chains typically start at ratio 2.00)
563 (new delta chains typically start at ratio 2.00)
564 :``lindist``: linear distance from base revision in delta chain to end
564 :``lindist``: linear distance from base revision in delta chain to end
565 of this revision
565 of this revision
566 :``extradist``: total size of revisions not part of this delta chain from
566 :``extradist``: total size of revisions not part of this delta chain from
567 base of delta chain to end of this revision; a measurement
567 base of delta chain to end of this revision; a measurement
568 of how much extra data we need to read/seek across to read
568 of how much extra data we need to read/seek across to read
569 the delta chain for this revision
569 the delta chain for this revision
570 :``extraratio``: extradist divided by chainsize; another representation of
570 :``extraratio``: extradist divided by chainsize; another representation of
571 how much unrelated data is needed to load this delta chain
571 how much unrelated data is needed to load this delta chain
572 """
572 """
573 opts = pycompat.byteskwargs(opts)
573 opts = pycompat.byteskwargs(opts)
574 r = cmdutil.openrevlog(repo, 'debugdeltachain', file_, opts)
574 r = cmdutil.openrevlog(repo, 'debugdeltachain', file_, opts)
575 index = r.index
575 index = r.index
576 generaldelta = r.version & revlog.FLAG_GENERALDELTA
576 generaldelta = r.version & revlog.FLAG_GENERALDELTA
577
577
578 def revinfo(rev):
578 def revinfo(rev):
579 e = index[rev]
579 e = index[rev]
580 compsize = e[1]
580 compsize = e[1]
581 uncompsize = e[2]
581 uncompsize = e[2]
582 chainsize = 0
582 chainsize = 0
583
583
584 if generaldelta:
584 if generaldelta:
585 if e[3] == e[5]:
585 if e[3] == e[5]:
586 deltatype = 'p1'
586 deltatype = 'p1'
587 elif e[3] == e[6]:
587 elif e[3] == e[6]:
588 deltatype = 'p2'
588 deltatype = 'p2'
589 elif e[3] == rev - 1:
589 elif e[3] == rev - 1:
590 deltatype = 'prev'
590 deltatype = 'prev'
591 elif e[3] == rev:
591 elif e[3] == rev:
592 deltatype = 'base'
592 deltatype = 'base'
593 else:
593 else:
594 deltatype = 'other'
594 deltatype = 'other'
595 else:
595 else:
596 if e[3] == rev:
596 if e[3] == rev:
597 deltatype = 'base'
597 deltatype = 'base'
598 else:
598 else:
599 deltatype = 'prev'
599 deltatype = 'prev'
600
600
601 chain = r._deltachain(rev)[0]
601 chain = r._deltachain(rev)[0]
602 for iterrev in chain:
602 for iterrev in chain:
603 e = index[iterrev]
603 e = index[iterrev]
604 chainsize += e[1]
604 chainsize += e[1]
605
605
606 return compsize, uncompsize, deltatype, chain, chainsize
606 return compsize, uncompsize, deltatype, chain, chainsize
607
607
608 fm = ui.formatter('debugdeltachain', opts)
608 fm = ui.formatter('debugdeltachain', opts)
609
609
610 fm.plain(' rev chain# chainlen prev delta '
610 fm.plain(' rev chain# chainlen prev delta '
611 'size rawsize chainsize ratio lindist extradist '
611 'size rawsize chainsize ratio lindist extradist '
612 'extraratio\n')
612 'extraratio\n')
613
613
614 chainbases = {}
614 chainbases = {}
615 for rev in r:
615 for rev in r:
616 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
616 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
617 chainbase = chain[0]
617 chainbase = chain[0]
618 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
618 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
619 basestart = r.start(chainbase)
619 basestart = r.start(chainbase)
620 revstart = r.start(rev)
620 revstart = r.start(rev)
621 lineardist = revstart + comp - basestart
621 lineardist = revstart + comp - basestart
622 extradist = lineardist - chainsize
622 extradist = lineardist - chainsize
623 try:
623 try:
624 prevrev = chain[-2]
624 prevrev = chain[-2]
625 except IndexError:
625 except IndexError:
626 prevrev = -1
626 prevrev = -1
627
627
628 chainratio = float(chainsize) / float(uncomp)
628 chainratio = float(chainsize) / float(uncomp)
629 extraratio = float(extradist) / float(chainsize)
629 extraratio = float(extradist) / float(chainsize)
630
630
631 fm.startitem()
631 fm.startitem()
632 fm.write('rev chainid chainlen prevrev deltatype compsize '
632 fm.write('rev chainid chainlen prevrev deltatype compsize '
633 'uncompsize chainsize chainratio lindist extradist '
633 'uncompsize chainsize chainratio lindist extradist '
634 'extraratio',
634 'extraratio',
635 '%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f\n',
635 '%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f\n',
636 rev, chainid, len(chain), prevrev, deltatype, comp,
636 rev, chainid, len(chain), prevrev, deltatype, comp,
637 uncomp, chainsize, chainratio, lineardist, extradist,
637 uncomp, chainsize, chainratio, lineardist, extradist,
638 extraratio,
638 extraratio,
639 rev=rev, chainid=chainid, chainlen=len(chain),
639 rev=rev, chainid=chainid, chainlen=len(chain),
640 prevrev=prevrev, deltatype=deltatype, compsize=comp,
640 prevrev=prevrev, deltatype=deltatype, compsize=comp,
641 uncompsize=uncomp, chainsize=chainsize,
641 uncompsize=uncomp, chainsize=chainsize,
642 chainratio=chainratio, lindist=lineardist,
642 chainratio=chainratio, lindist=lineardist,
643 extradist=extradist, extraratio=extraratio)
643 extradist=extradist, extraratio=extraratio)
644
644
645 fm.end()
645 fm.end()
646
646
647 @command('debugdirstate|debugstate',
647 @command('debugdirstate|debugstate',
648 [('', 'nodates', None, _('do not display the saved mtime')),
648 [('', 'nodates', None, _('do not display the saved mtime')),
649 ('', 'datesort', None, _('sort by saved mtime'))],
649 ('', 'datesort', None, _('sort by saved mtime'))],
650 _('[OPTION]...'))
650 _('[OPTION]...'))
651 def debugstate(ui, repo, **opts):
651 def debugstate(ui, repo, **opts):
652 """show the contents of the current dirstate"""
652 """show the contents of the current dirstate"""
653
653
654 nodates = opts.get(r'nodates')
654 nodates = opts.get(r'nodates')
655 datesort = opts.get(r'datesort')
655 datesort = opts.get(r'datesort')
656
656
657 timestr = ""
657 timestr = ""
658 if datesort:
658 if datesort:
659 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
659 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
660 else:
660 else:
661 keyfunc = None # sort by filename
661 keyfunc = None # sort by filename
662 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
662 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
663 if ent[3] == -1:
663 if ent[3] == -1:
664 timestr = 'unset '
664 timestr = 'unset '
665 elif nodates:
665 elif nodates:
666 timestr = 'set '
666 timestr = 'set '
667 else:
667 else:
668 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
668 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
669 time.localtime(ent[3]))
669 time.localtime(ent[3]))
670 if ent[1] & 0o20000:
670 if ent[1] & 0o20000:
671 mode = 'lnk'
671 mode = 'lnk'
672 else:
672 else:
673 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
673 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
674 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
674 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
675 for f in repo.dirstate.copies():
675 for f in repo.dirstate.copies():
676 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
676 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
677
677
678 @command('debugdiscovery',
678 @command('debugdiscovery',
679 [('', 'old', None, _('use old-style discovery')),
679 [('', 'old', None, _('use old-style discovery')),
680 ('', 'nonheads', None,
680 ('', 'nonheads', None,
681 _('use old-style discovery with non-heads included')),
681 _('use old-style discovery with non-heads included')),
682 ] + cmdutil.remoteopts,
682 ] + cmdutil.remoteopts,
683 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
683 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
684 def debugdiscovery(ui, repo, remoteurl="default", **opts):
684 def debugdiscovery(ui, repo, remoteurl="default", **opts):
685 """runs the changeset discovery protocol in isolation"""
685 """runs the changeset discovery protocol in isolation"""
686 opts = pycompat.byteskwargs(opts)
686 opts = pycompat.byteskwargs(opts)
687 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
687 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
688 opts.get('branch'))
688 opts.get('branch'))
689 remote = hg.peer(repo, opts, remoteurl)
689 remote = hg.peer(repo, opts, remoteurl)
690 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
690 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
691
691
692 # make sure tests are repeatable
692 # make sure tests are repeatable
693 random.seed(12323)
693 random.seed(12323)
694
694
695 def doit(localheads, remoteheads, remote=remote):
695 def doit(localheads, remoteheads, remote=remote):
696 if opts.get('old'):
696 if opts.get('old'):
697 if localheads:
697 if localheads:
698 raise error.Abort('cannot use localheads with old style '
698 raise error.Abort('cannot use localheads with old style '
699 'discovery')
699 'discovery')
700 if not util.safehasattr(remote, 'branches'):
700 if not util.safehasattr(remote, 'branches'):
701 # enable in-client legacy support
701 # enable in-client legacy support
702 remote = localrepo.locallegacypeer(remote.local())
702 remote = localrepo.locallegacypeer(remote.local())
703 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
703 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
704 force=True)
704 force=True)
705 common = set(common)
705 common = set(common)
706 if not opts.get('nonheads'):
706 if not opts.get('nonheads'):
707 ui.write(("unpruned common: %s\n") %
707 ui.write(("unpruned common: %s\n") %
708 " ".join(sorted(short(n) for n in common)))
708 " ".join(sorted(short(n) for n in common)))
709 dag = dagutil.revlogdag(repo.changelog)
709 dag = dagutil.revlogdag(repo.changelog)
710 all = dag.ancestorset(dag.internalizeall(common))
710 all = dag.ancestorset(dag.internalizeall(common))
711 common = dag.externalizeall(dag.headsetofconnecteds(all))
711 common = dag.externalizeall(dag.headsetofconnecteds(all))
712 else:
712 else:
713 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
713 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
714 common = set(common)
714 common = set(common)
715 rheads = set(hds)
715 rheads = set(hds)
716 lheads = set(repo.heads())
716 lheads = set(repo.heads())
717 ui.write(("common heads: %s\n") %
717 ui.write(("common heads: %s\n") %
718 " ".join(sorted(short(n) for n in common)))
718 " ".join(sorted(short(n) for n in common)))
719 if lheads <= common:
719 if lheads <= common:
720 ui.write(("local is subset\n"))
720 ui.write(("local is subset\n"))
721 elif rheads <= common:
721 elif rheads <= common:
722 ui.write(("remote is subset\n"))
722 ui.write(("remote is subset\n"))
723
723
724 serverlogs = opts.get('serverlog')
724 serverlogs = opts.get('serverlog')
725 if serverlogs:
725 if serverlogs:
726 for filename in serverlogs:
726 for filename in serverlogs:
727 with open(filename, 'r') as logfile:
727 with open(filename, 'r') as logfile:
728 line = logfile.readline()
728 line = logfile.readline()
729 while line:
729 while line:
730 parts = line.strip().split(';')
730 parts = line.strip().split(';')
731 op = parts[1]
731 op = parts[1]
732 if op == 'cg':
732 if op == 'cg':
733 pass
733 pass
734 elif op == 'cgss':
734 elif op == 'cgss':
735 doit(parts[2].split(' '), parts[3].split(' '))
735 doit(parts[2].split(' '), parts[3].split(' '))
736 elif op == 'unb':
736 elif op == 'unb':
737 doit(parts[3].split(' '), parts[2].split(' '))
737 doit(parts[3].split(' '), parts[2].split(' '))
738 line = logfile.readline()
738 line = logfile.readline()
739 else:
739 else:
740 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
740 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
741 opts.get('remote_head'))
741 opts.get('remote_head'))
742 localrevs = opts.get('local_head')
742 localrevs = opts.get('local_head')
743 doit(localrevs, remoterevs)
743 doit(localrevs, remoterevs)
744
744
745 @command('debugextensions', cmdutil.formatteropts, [], norepo=True)
745 @command('debugextensions', cmdutil.formatteropts, [], norepo=True)
746 def debugextensions(ui, **opts):
746 def debugextensions(ui, **opts):
747 '''show information about active extensions'''
747 '''show information about active extensions'''
748 opts = pycompat.byteskwargs(opts)
748 opts = pycompat.byteskwargs(opts)
749 exts = extensions.extensions(ui)
749 exts = extensions.extensions(ui)
750 hgver = util.version()
750 hgver = util.version()
751 fm = ui.formatter('debugextensions', opts)
751 fm = ui.formatter('debugextensions', opts)
752 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
752 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
753 isinternal = extensions.ismoduleinternal(extmod)
753 isinternal = extensions.ismoduleinternal(extmod)
754 extsource = pycompat.fsencode(extmod.__file__)
754 extsource = pycompat.fsencode(extmod.__file__)
755 if isinternal:
755 if isinternal:
756 exttestedwith = [] # never expose magic string to users
756 exttestedwith = [] # never expose magic string to users
757 else:
757 else:
758 exttestedwith = getattr(extmod, 'testedwith', '').split()
758 exttestedwith = getattr(extmod, 'testedwith', '').split()
759 extbuglink = getattr(extmod, 'buglink', None)
759 extbuglink = getattr(extmod, 'buglink', None)
760
760
761 fm.startitem()
761 fm.startitem()
762
762
763 if ui.quiet or ui.verbose:
763 if ui.quiet or ui.verbose:
764 fm.write('name', '%s\n', extname)
764 fm.write('name', '%s\n', extname)
765 else:
765 else:
766 fm.write('name', '%s', extname)
766 fm.write('name', '%s', extname)
767 if isinternal or hgver in exttestedwith:
767 if isinternal or hgver in exttestedwith:
768 fm.plain('\n')
768 fm.plain('\n')
769 elif not exttestedwith:
769 elif not exttestedwith:
770 fm.plain(_(' (untested!)\n'))
770 fm.plain(_(' (untested!)\n'))
771 else:
771 else:
772 lasttestedversion = exttestedwith[-1]
772 lasttestedversion = exttestedwith[-1]
773 fm.plain(' (%s!)\n' % lasttestedversion)
773 fm.plain(' (%s!)\n' % lasttestedversion)
774
774
775 fm.condwrite(ui.verbose and extsource, 'source',
775 fm.condwrite(ui.verbose and extsource, 'source',
776 _(' location: %s\n'), extsource or "")
776 _(' location: %s\n'), extsource or "")
777
777
778 if ui.verbose:
778 if ui.verbose:
779 fm.plain(_(' bundled: %s\n') % ['no', 'yes'][isinternal])
779 fm.plain(_(' bundled: %s\n') % ['no', 'yes'][isinternal])
780 fm.data(bundled=isinternal)
780 fm.data(bundled=isinternal)
781
781
782 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
782 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
783 _(' tested with: %s\n'),
783 _(' tested with: %s\n'),
784 fm.formatlist(exttestedwith, name='ver'))
784 fm.formatlist(exttestedwith, name='ver'))
785
785
786 fm.condwrite(ui.verbose and extbuglink, 'buglink',
786 fm.condwrite(ui.verbose and extbuglink, 'buglink',
787 _(' bug reporting: %s\n'), extbuglink or "")
787 _(' bug reporting: %s\n'), extbuglink or "")
788
788
789 fm.end()
789 fm.end()
790
790
791 @command('debugfileset',
791 @command('debugfileset',
792 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
792 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
793 _('[-r REV] FILESPEC'))
793 _('[-r REV] FILESPEC'))
794 def debugfileset(ui, repo, expr, **opts):
794 def debugfileset(ui, repo, expr, **opts):
795 '''parse and apply a fileset specification'''
795 '''parse and apply a fileset specification'''
796 ctx = scmutil.revsingle(repo, opts.get(r'rev'), None)
796 ctx = scmutil.revsingle(repo, opts.get(r'rev'), None)
797 if ui.verbose:
797 if ui.verbose:
798 tree = fileset.parse(expr)
798 tree = fileset.parse(expr)
799 ui.note(fileset.prettyformat(tree), "\n")
799 ui.note(fileset.prettyformat(tree), "\n")
800
800
801 for f in ctx.getfileset(expr):
801 for f in ctx.getfileset(expr):
802 ui.write("%s\n" % f)
802 ui.write("%s\n" % f)
803
803
804 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
804 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
805 def debugfsinfo(ui, path="."):
805 def debugfsinfo(ui, path="."):
806 """show information detected about current filesystem"""
806 """show information detected about current filesystem"""
807 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
807 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
808 ui.write(('fstype: %s\n') % (util.getfstype(path) or '(unknown)'))
808 ui.write(('fstype: %s\n') % (util.getfstype(path) or '(unknown)'))
809 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
809 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
810 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
810 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
811 casesensitive = '(unknown)'
811 casesensitive = '(unknown)'
812 try:
812 try:
813 with tempfile.NamedTemporaryFile(prefix='.debugfsinfo', dir=path) as f:
813 with tempfile.NamedTemporaryFile(prefix='.debugfsinfo', dir=path) as f:
814 casesensitive = util.fscasesensitive(f.name) and 'yes' or 'no'
814 casesensitive = util.fscasesensitive(f.name) and 'yes' or 'no'
815 except OSError:
815 except OSError:
816 pass
816 pass
817 ui.write(('case-sensitive: %s\n') % casesensitive)
817 ui.write(('case-sensitive: %s\n') % casesensitive)
818
818
819 @command('debuggetbundle',
819 @command('debuggetbundle',
820 [('H', 'head', [], _('id of head node'), _('ID')),
820 [('H', 'head', [], _('id of head node'), _('ID')),
821 ('C', 'common', [], _('id of common node'), _('ID')),
821 ('C', 'common', [], _('id of common node'), _('ID')),
822 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
822 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
823 _('REPO FILE [-H|-C ID]...'),
823 _('REPO FILE [-H|-C ID]...'),
824 norepo=True)
824 norepo=True)
825 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
825 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
826 """retrieves a bundle from a repo
826 """retrieves a bundle from a repo
827
827
828 Every ID must be a full-length hex node id string. Saves the bundle to the
828 Every ID must be a full-length hex node id string. Saves the bundle to the
829 given file.
829 given file.
830 """
830 """
831 opts = pycompat.byteskwargs(opts)
831 opts = pycompat.byteskwargs(opts)
832 repo = hg.peer(ui, opts, repopath)
832 repo = hg.peer(ui, opts, repopath)
833 if not repo.capable('getbundle'):
833 if not repo.capable('getbundle'):
834 raise error.Abort("getbundle() not supported by target repository")
834 raise error.Abort("getbundle() not supported by target repository")
835 args = {}
835 args = {}
836 if common:
836 if common:
837 args[r'common'] = [bin(s) for s in common]
837 args[r'common'] = [bin(s) for s in common]
838 if head:
838 if head:
839 args[r'heads'] = [bin(s) for s in head]
839 args[r'heads'] = [bin(s) for s in head]
840 # TODO: get desired bundlecaps from command line.
840 # TODO: get desired bundlecaps from command line.
841 args[r'bundlecaps'] = None
841 args[r'bundlecaps'] = None
842 bundle = repo.getbundle('debug', **args)
842 bundle = repo.getbundle('debug', **args)
843
843
844 bundletype = opts.get('type', 'bzip2').lower()
844 bundletype = opts.get('type', 'bzip2').lower()
845 btypes = {'none': 'HG10UN',
845 btypes = {'none': 'HG10UN',
846 'bzip2': 'HG10BZ',
846 'bzip2': 'HG10BZ',
847 'gzip': 'HG10GZ',
847 'gzip': 'HG10GZ',
848 'bundle2': 'HG20'}
848 'bundle2': 'HG20'}
849 bundletype = btypes.get(bundletype)
849 bundletype = btypes.get(bundletype)
850 if bundletype not in bundle2.bundletypes:
850 if bundletype not in bundle2.bundletypes:
851 raise error.Abort(_('unknown bundle type specified with --type'))
851 raise error.Abort(_('unknown bundle type specified with --type'))
852 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
852 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
853
853
854 @command('debugignore', [], '[FILE]')
854 @command('debugignore', [], '[FILE]')
855 def debugignore(ui, repo, *files, **opts):
855 def debugignore(ui, repo, *files, **opts):
856 """display the combined ignore pattern and information about ignored files
856 """display the combined ignore pattern and information about ignored files
857
857
858 With no argument display the combined ignore pattern.
858 With no argument display the combined ignore pattern.
859
859
860 Given space separated file names, shows if the given file is ignored and
860 Given space separated file names, shows if the given file is ignored and
861 if so, show the ignore rule (file and line number) that matched it.
861 if so, show the ignore rule (file and line number) that matched it.
862 """
862 """
863 ignore = repo.dirstate._ignore
863 ignore = repo.dirstate._ignore
864 if not files:
864 if not files:
865 # Show all the patterns
865 # Show all the patterns
866 ui.write("%s\n" % repr(ignore))
866 ui.write("%s\n" % repr(ignore))
867 else:
867 else:
868 for f in files:
868 for f in files:
869 nf = util.normpath(f)
869 nf = util.normpath(f)
870 ignored = None
870 ignored = None
871 ignoredata = None
871 ignoredata = None
872 if nf != '.':
872 if nf != '.':
873 if ignore(nf):
873 if ignore(nf):
874 ignored = nf
874 ignored = nf
875 ignoredata = repo.dirstate._ignorefileandline(nf)
875 ignoredata = repo.dirstate._ignorefileandline(nf)
876 else:
876 else:
877 for p in util.finddirs(nf):
877 for p in util.finddirs(nf):
878 if ignore(p):
878 if ignore(p):
879 ignored = p
879 ignored = p
880 ignoredata = repo.dirstate._ignorefileandline(p)
880 ignoredata = repo.dirstate._ignorefileandline(p)
881 break
881 break
882 if ignored:
882 if ignored:
883 if ignored == nf:
883 if ignored == nf:
884 ui.write(_("%s is ignored\n") % f)
884 ui.write(_("%s is ignored\n") % f)
885 else:
885 else:
886 ui.write(_("%s is ignored because of "
886 ui.write(_("%s is ignored because of "
887 "containing folder %s\n")
887 "containing folder %s\n")
888 % (f, ignored))
888 % (f, ignored))
889 ignorefile, lineno, line = ignoredata
889 ignorefile, lineno, line = ignoredata
890 ui.write(_("(ignore rule in %s, line %d: '%s')\n")
890 ui.write(_("(ignore rule in %s, line %d: '%s')\n")
891 % (ignorefile, lineno, line))
891 % (ignorefile, lineno, line))
892 else:
892 else:
893 ui.write(_("%s is not ignored\n") % f)
893 ui.write(_("%s is not ignored\n") % f)
894
894
895 @command('debugindex', cmdutil.debugrevlogopts +
895 @command('debugindex', cmdutil.debugrevlogopts +
896 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
896 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
897 _('[-f FORMAT] -c|-m|FILE'),
897 _('[-f FORMAT] -c|-m|FILE'),
898 optionalrepo=True)
898 optionalrepo=True)
899 def debugindex(ui, repo, file_=None, **opts):
899 def debugindex(ui, repo, file_=None, **opts):
900 """dump the contents of an index file"""
900 """dump the contents of an index file"""
901 opts = pycompat.byteskwargs(opts)
901 opts = pycompat.byteskwargs(opts)
902 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
902 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
903 format = opts.get('format', 0)
903 format = opts.get('format', 0)
904 if format not in (0, 1):
904 if format not in (0, 1):
905 raise error.Abort(_("unknown format %d") % format)
905 raise error.Abort(_("unknown format %d") % format)
906
906
907 generaldelta = r.version & revlog.FLAG_GENERALDELTA
907 generaldelta = r.version & revlog.FLAG_GENERALDELTA
908 if generaldelta:
908 if generaldelta:
909 basehdr = ' delta'
909 basehdr = ' delta'
910 else:
910 else:
911 basehdr = ' base'
911 basehdr = ' base'
912
912
913 if ui.debugflag:
913 if ui.debugflag:
914 shortfn = hex
914 shortfn = hex
915 else:
915 else:
916 shortfn = short
916 shortfn = short
917
917
918 # There might not be anything in r, so have a sane default
918 # There might not be anything in r, so have a sane default
919 idlen = 12
919 idlen = 12
920 for i in r:
920 for i in r:
921 idlen = len(shortfn(r.node(i)))
921 idlen = len(shortfn(r.node(i)))
922 break
922 break
923
923
924 if format == 0:
924 if format == 0:
925 ui.write((" rev offset length " + basehdr + " linkrev"
925 ui.write((" rev offset length " + basehdr + " linkrev"
926 " %s %s p2\n") % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
926 " %s %s p2\n") % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
927 elif format == 1:
927 elif format == 1:
928 ui.write((" rev flag offset length"
928 ui.write((" rev flag offset length"
929 " size " + basehdr + " link p1 p2"
929 " size " + basehdr + " link p1 p2"
930 " %s\n") % "nodeid".rjust(idlen))
930 " %s\n") % "nodeid".rjust(idlen))
931
931
932 for i in r:
932 for i in r:
933 node = r.node(i)
933 node = r.node(i)
934 if generaldelta:
934 if generaldelta:
935 base = r.deltaparent(i)
935 base = r.deltaparent(i)
936 else:
936 else:
937 base = r.chainbase(i)
937 base = r.chainbase(i)
938 if format == 0:
938 if format == 0:
939 try:
939 try:
940 pp = r.parents(node)
940 pp = r.parents(node)
941 except Exception:
941 except Exception:
942 pp = [nullid, nullid]
942 pp = [nullid, nullid]
943 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
943 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
944 i, r.start(i), r.length(i), base, r.linkrev(i),
944 i, r.start(i), r.length(i), base, r.linkrev(i),
945 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
945 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
946 elif format == 1:
946 elif format == 1:
947 pr = r.parentrevs(i)
947 pr = r.parentrevs(i)
948 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
948 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
949 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
949 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
950 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
950 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
951
951
952 @command('debugindexdot', cmdutil.debugrevlogopts,
952 @command('debugindexdot', cmdutil.debugrevlogopts,
953 _('-c|-m|FILE'), optionalrepo=True)
953 _('-c|-m|FILE'), optionalrepo=True)
954 def debugindexdot(ui, repo, file_=None, **opts):
954 def debugindexdot(ui, repo, file_=None, **opts):
955 """dump an index DAG as a graphviz dot file"""
955 """dump an index DAG as a graphviz dot file"""
956 opts = pycompat.byteskwargs(opts)
956 opts = pycompat.byteskwargs(opts)
957 r = cmdutil.openrevlog(repo, 'debugindexdot', file_, opts)
957 r = cmdutil.openrevlog(repo, 'debugindexdot', file_, opts)
958 ui.write(("digraph G {\n"))
958 ui.write(("digraph G {\n"))
959 for i in r:
959 for i in r:
960 node = r.node(i)
960 node = r.node(i)
961 pp = r.parents(node)
961 pp = r.parents(node)
962 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
962 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
963 if pp[1] != nullid:
963 if pp[1] != nullid:
964 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
964 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
965 ui.write("}\n")
965 ui.write("}\n")
966
966
967 @command('debuginstall', [] + cmdutil.formatteropts, '', norepo=True)
967 @command('debuginstall', [] + cmdutil.formatteropts, '', norepo=True)
968 def debuginstall(ui, **opts):
968 def debuginstall(ui, **opts):
969 '''test Mercurial installation
969 '''test Mercurial installation
970
970
971 Returns 0 on success.
971 Returns 0 on success.
972 '''
972 '''
973 opts = pycompat.byteskwargs(opts)
973 opts = pycompat.byteskwargs(opts)
974
974
975 def writetemp(contents):
975 def writetemp(contents):
976 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
976 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
977 f = os.fdopen(fd, pycompat.sysstr("wb"))
977 f = os.fdopen(fd, pycompat.sysstr("wb"))
978 f.write(contents)
978 f.write(contents)
979 f.close()
979 f.close()
980 return name
980 return name
981
981
982 problems = 0
982 problems = 0
983
983
984 fm = ui.formatter('debuginstall', opts)
984 fm = ui.formatter('debuginstall', opts)
985 fm.startitem()
985 fm.startitem()
986
986
987 # encoding
987 # encoding
988 fm.write('encoding', _("checking encoding (%s)...\n"), encoding.encoding)
988 fm.write('encoding', _("checking encoding (%s)...\n"), encoding.encoding)
989 err = None
989 err = None
990 try:
990 try:
991 encoding.fromlocal("test")
991 encoding.fromlocal("test")
992 except error.Abort as inst:
992 except error.Abort as inst:
993 err = inst
993 err = inst
994 problems += 1
994 problems += 1
995 fm.condwrite(err, 'encodingerror', _(" %s\n"
995 fm.condwrite(err, 'encodingerror', _(" %s\n"
996 " (check that your locale is properly set)\n"), err)
996 " (check that your locale is properly set)\n"), err)
997
997
998 # Python
998 # Python
999 fm.write('pythonexe', _("checking Python executable (%s)\n"),
999 fm.write('pythonexe', _("checking Python executable (%s)\n"),
1000 pycompat.sysexecutable)
1000 pycompat.sysexecutable)
1001 fm.write('pythonver', _("checking Python version (%s)\n"),
1001 fm.write('pythonver', _("checking Python version (%s)\n"),
1002 ("%d.%d.%d" % sys.version_info[:3]))
1002 ("%d.%d.%d" % sys.version_info[:3]))
1003 fm.write('pythonlib', _("checking Python lib (%s)...\n"),
1003 fm.write('pythonlib', _("checking Python lib (%s)...\n"),
1004 os.path.dirname(pycompat.fsencode(os.__file__)))
1004 os.path.dirname(pycompat.fsencode(os.__file__)))
1005
1005
1006 security = set(sslutil.supportedprotocols)
1006 security = set(sslutil.supportedprotocols)
1007 if sslutil.hassni:
1007 if sslutil.hassni:
1008 security.add('sni')
1008 security.add('sni')
1009
1009
1010 fm.write('pythonsecurity', _("checking Python security support (%s)\n"),
1010 fm.write('pythonsecurity', _("checking Python security support (%s)\n"),
1011 fm.formatlist(sorted(security), name='protocol',
1011 fm.formatlist(sorted(security), name='protocol',
1012 fmt='%s', sep=','))
1012 fmt='%s', sep=','))
1013
1013
1014 # These are warnings, not errors. So don't increment problem count. This
1014 # These are warnings, not errors. So don't increment problem count. This
1015 # may change in the future.
1015 # may change in the future.
1016 if 'tls1.2' not in security:
1016 if 'tls1.2' not in security:
1017 fm.plain(_(' TLS 1.2 not supported by Python install; '
1017 fm.plain(_(' TLS 1.2 not supported by Python install; '
1018 'network connections lack modern security\n'))
1018 'network connections lack modern security\n'))
1019 if 'sni' not in security:
1019 if 'sni' not in security:
1020 fm.plain(_(' SNI not supported by Python install; may have '
1020 fm.plain(_(' SNI not supported by Python install; may have '
1021 'connectivity issues with some servers\n'))
1021 'connectivity issues with some servers\n'))
1022
1022
1023 # TODO print CA cert info
1023 # TODO print CA cert info
1024
1024
1025 # hg version
1025 # hg version
1026 hgver = util.version()
1026 hgver = util.version()
1027 fm.write('hgver', _("checking Mercurial version (%s)\n"),
1027 fm.write('hgver', _("checking Mercurial version (%s)\n"),
1028 hgver.split('+')[0])
1028 hgver.split('+')[0])
1029 fm.write('hgverextra', _("checking Mercurial custom build (%s)\n"),
1029 fm.write('hgverextra', _("checking Mercurial custom build (%s)\n"),
1030 '+'.join(hgver.split('+')[1:]))
1030 '+'.join(hgver.split('+')[1:]))
1031
1031
1032 # compiled modules
1032 # compiled modules
1033 fm.write('hgmodulepolicy', _("checking module policy (%s)\n"),
1033 fm.write('hgmodulepolicy', _("checking module policy (%s)\n"),
1034 policy.policy)
1034 policy.policy)
1035 fm.write('hgmodules', _("checking installed modules (%s)...\n"),
1035 fm.write('hgmodules', _("checking installed modules (%s)...\n"),
1036 os.path.dirname(pycompat.fsencode(__file__)))
1036 os.path.dirname(pycompat.fsencode(__file__)))
1037
1037
1038 if policy.policy in ('c', 'allow'):
1038 if policy.policy in ('c', 'allow'):
1039 err = None
1039 err = None
1040 try:
1040 try:
1041 from .cext import (
1041 from .cext import (
1042 base85,
1042 base85,
1043 bdiff,
1043 bdiff,
1044 mpatch,
1044 mpatch,
1045 osutil,
1045 osutil,
1046 )
1046 )
1047 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1047 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1048 except Exception as inst:
1048 except Exception as inst:
1049 err = inst
1049 err = inst
1050 problems += 1
1050 problems += 1
1051 fm.condwrite(err, 'extensionserror', " %s\n", err)
1051 fm.condwrite(err, 'extensionserror', " %s\n", err)
1052
1052
1053 compengines = util.compengines._engines.values()
1053 compengines = util.compengines._engines.values()
1054 fm.write('compengines', _('checking registered compression engines (%s)\n'),
1054 fm.write('compengines', _('checking registered compression engines (%s)\n'),
1055 fm.formatlist(sorted(e.name() for e in compengines),
1055 fm.formatlist(sorted(e.name() for e in compengines),
1056 name='compengine', fmt='%s', sep=', '))
1056 name='compengine', fmt='%s', sep=', '))
1057 fm.write('compenginesavail', _('checking available compression engines '
1057 fm.write('compenginesavail', _('checking available compression engines '
1058 '(%s)\n'),
1058 '(%s)\n'),
1059 fm.formatlist(sorted(e.name() for e in compengines
1059 fm.formatlist(sorted(e.name() for e in compengines
1060 if e.available()),
1060 if e.available()),
1061 name='compengine', fmt='%s', sep=', '))
1061 name='compengine', fmt='%s', sep=', '))
1062 wirecompengines = util.compengines.supportedwireengines(util.SERVERROLE)
1062 wirecompengines = util.compengines.supportedwireengines(util.SERVERROLE)
1063 fm.write('compenginesserver', _('checking available compression engines '
1063 fm.write('compenginesserver', _('checking available compression engines '
1064 'for wire protocol (%s)\n'),
1064 'for wire protocol (%s)\n'),
1065 fm.formatlist([e.name() for e in wirecompengines
1065 fm.formatlist([e.name() for e in wirecompengines
1066 if e.wireprotosupport()],
1066 if e.wireprotosupport()],
1067 name='compengine', fmt='%s', sep=', '))
1067 name='compengine', fmt='%s', sep=', '))
1068
1068
1069 # templates
1069 # templates
1070 p = templater.templatepaths()
1070 p = templater.templatepaths()
1071 fm.write('templatedirs', 'checking templates (%s)...\n', ' '.join(p))
1071 fm.write('templatedirs', 'checking templates (%s)...\n', ' '.join(p))
1072 fm.condwrite(not p, '', _(" no template directories found\n"))
1072 fm.condwrite(not p, '', _(" no template directories found\n"))
1073 if p:
1073 if p:
1074 m = templater.templatepath("map-cmdline.default")
1074 m = templater.templatepath("map-cmdline.default")
1075 if m:
1075 if m:
1076 # template found, check if it is working
1076 # template found, check if it is working
1077 err = None
1077 err = None
1078 try:
1078 try:
1079 templater.templater.frommapfile(m)
1079 templater.templater.frommapfile(m)
1080 except Exception as inst:
1080 except Exception as inst:
1081 err = inst
1081 err = inst
1082 p = None
1082 p = None
1083 fm.condwrite(err, 'defaulttemplateerror', " %s\n", err)
1083 fm.condwrite(err, 'defaulttemplateerror', " %s\n", err)
1084 else:
1084 else:
1085 p = None
1085 p = None
1086 fm.condwrite(p, 'defaulttemplate',
1086 fm.condwrite(p, 'defaulttemplate',
1087 _("checking default template (%s)\n"), m)
1087 _("checking default template (%s)\n"), m)
1088 fm.condwrite(not m, 'defaulttemplatenotfound',
1088 fm.condwrite(not m, 'defaulttemplatenotfound',
1089 _(" template '%s' not found\n"), "default")
1089 _(" template '%s' not found\n"), "default")
1090 if not p:
1090 if not p:
1091 problems += 1
1091 problems += 1
1092 fm.condwrite(not p, '',
1092 fm.condwrite(not p, '',
1093 _(" (templates seem to have been installed incorrectly)\n"))
1093 _(" (templates seem to have been installed incorrectly)\n"))
1094
1094
1095 # editor
1095 # editor
1096 editor = ui.geteditor()
1096 editor = ui.geteditor()
1097 editor = util.expandpath(editor)
1097 editor = util.expandpath(editor)
1098 fm.write('editor', _("checking commit editor... (%s)\n"), editor)
1098 fm.write('editor', _("checking commit editor... (%s)\n"), editor)
1099 cmdpath = util.findexe(pycompat.shlexsplit(editor)[0])
1099 cmdpath = util.findexe(pycompat.shlexsplit(editor)[0])
1100 fm.condwrite(not cmdpath and editor == 'vi', 'vinotfound',
1100 fm.condwrite(not cmdpath and editor == 'vi', 'vinotfound',
1101 _(" No commit editor set and can't find %s in PATH\n"
1101 _(" No commit editor set and can't find %s in PATH\n"
1102 " (specify a commit editor in your configuration"
1102 " (specify a commit editor in your configuration"
1103 " file)\n"), not cmdpath and editor == 'vi' and editor)
1103 " file)\n"), not cmdpath and editor == 'vi' and editor)
1104 fm.condwrite(not cmdpath and editor != 'vi', 'editornotfound',
1104 fm.condwrite(not cmdpath and editor != 'vi', 'editornotfound',
1105 _(" Can't find editor '%s' in PATH\n"
1105 _(" Can't find editor '%s' in PATH\n"
1106 " (specify a commit editor in your configuration"
1106 " (specify a commit editor in your configuration"
1107 " file)\n"), not cmdpath and editor)
1107 " file)\n"), not cmdpath and editor)
1108 if not cmdpath and editor != 'vi':
1108 if not cmdpath and editor != 'vi':
1109 problems += 1
1109 problems += 1
1110
1110
1111 # check username
1111 # check username
1112 username = None
1112 username = None
1113 err = None
1113 err = None
1114 try:
1114 try:
1115 username = ui.username()
1115 username = ui.username()
1116 except error.Abort as e:
1116 except error.Abort as e:
1117 err = e
1117 err = e
1118 problems += 1
1118 problems += 1
1119
1119
1120 fm.condwrite(username, 'username', _("checking username (%s)\n"), username)
1120 fm.condwrite(username, 'username', _("checking username (%s)\n"), username)
1121 fm.condwrite(err, 'usernameerror', _("checking username...\n %s\n"
1121 fm.condwrite(err, 'usernameerror', _("checking username...\n %s\n"
1122 " (specify a username in your configuration file)\n"), err)
1122 " (specify a username in your configuration file)\n"), err)
1123
1123
1124 fm.condwrite(not problems, '',
1124 fm.condwrite(not problems, '',
1125 _("no problems detected\n"))
1125 _("no problems detected\n"))
1126 if not problems:
1126 if not problems:
1127 fm.data(problems=problems)
1127 fm.data(problems=problems)
1128 fm.condwrite(problems, 'problems',
1128 fm.condwrite(problems, 'problems',
1129 _("%d problems detected,"
1129 _("%d problems detected,"
1130 " please check your install!\n"), problems)
1130 " please check your install!\n"), problems)
1131 fm.end()
1131 fm.end()
1132
1132
1133 return problems
1133 return problems
1134
1134
1135 @command('debugknown', [], _('REPO ID...'), norepo=True)
1135 @command('debugknown', [], _('REPO ID...'), norepo=True)
1136 def debugknown(ui, repopath, *ids, **opts):
1136 def debugknown(ui, repopath, *ids, **opts):
1137 """test whether node ids are known to a repo
1137 """test whether node ids are known to a repo
1138
1138
1139 Every ID must be a full-length hex node id string. Returns a list of 0s
1139 Every ID must be a full-length hex node id string. Returns a list of 0s
1140 and 1s indicating unknown/known.
1140 and 1s indicating unknown/known.
1141 """
1141 """
1142 opts = pycompat.byteskwargs(opts)
1142 opts = pycompat.byteskwargs(opts)
1143 repo = hg.peer(ui, opts, repopath)
1143 repo = hg.peer(ui, opts, repopath)
1144 if not repo.capable('known'):
1144 if not repo.capable('known'):
1145 raise error.Abort("known() not supported by target repository")
1145 raise error.Abort("known() not supported by target repository")
1146 flags = repo.known([bin(s) for s in ids])
1146 flags = repo.known([bin(s) for s in ids])
1147 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1147 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1148
1148
1149 @command('debuglabelcomplete', [], _('LABEL...'))
1149 @command('debuglabelcomplete', [], _('LABEL...'))
1150 def debuglabelcomplete(ui, repo, *args):
1150 def debuglabelcomplete(ui, repo, *args):
1151 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
1151 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
1152 debugnamecomplete(ui, repo, *args)
1152 debugnamecomplete(ui, repo, *args)
1153
1153
1154 @command('debuglocks',
1154 @command('debuglocks',
1155 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
1155 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
1156 ('W', 'force-wlock', None,
1156 ('W', 'force-wlock', None,
1157 _('free the working state lock (DANGEROUS)'))],
1157 _('free the working state lock (DANGEROUS)'))],
1158 _('[OPTION]...'))
1158 _('[OPTION]...'))
1159 def debuglocks(ui, repo, **opts):
1159 def debuglocks(ui, repo, **opts):
1160 """show or modify state of locks
1160 """show or modify state of locks
1161
1161
1162 By default, this command will show which locks are held. This
1162 By default, this command will show which locks are held. This
1163 includes the user and process holding the lock, the amount of time
1163 includes the user and process holding the lock, the amount of time
1164 the lock has been held, and the machine name where the process is
1164 the lock has been held, and the machine name where the process is
1165 running if it's not local.
1165 running if it's not local.
1166
1166
1167 Locks protect the integrity of Mercurial's data, so should be
1167 Locks protect the integrity of Mercurial's data, so should be
1168 treated with care. System crashes or other interruptions may cause
1168 treated with care. System crashes or other interruptions may cause
1169 locks to not be properly released, though Mercurial will usually
1169 locks to not be properly released, though Mercurial will usually
1170 detect and remove such stale locks automatically.
1170 detect and remove such stale locks automatically.
1171
1171
1172 However, detecting stale locks may not always be possible (for
1172 However, detecting stale locks may not always be possible (for
1173 instance, on a shared filesystem). Removing locks may also be
1173 instance, on a shared filesystem). Removing locks may also be
1174 blocked by filesystem permissions.
1174 blocked by filesystem permissions.
1175
1175
1176 Returns 0 if no locks are held.
1176 Returns 0 if no locks are held.
1177
1177
1178 """
1178 """
1179
1179
1180 if opts.get(r'force_lock'):
1180 if opts.get(r'force_lock'):
1181 repo.svfs.unlink('lock')
1181 repo.svfs.unlink('lock')
1182 if opts.get(r'force_wlock'):
1182 if opts.get(r'force_wlock'):
1183 repo.vfs.unlink('wlock')
1183 repo.vfs.unlink('wlock')
1184 if opts.get(r'force_lock') or opts.get(r'force_lock'):
1184 if opts.get(r'force_lock') or opts.get(r'force_lock'):
1185 return 0
1185 return 0
1186
1186
1187 now = time.time()
1187 now = time.time()
1188 held = 0
1188 held = 0
1189
1189
1190 def report(vfs, name, method):
1190 def report(vfs, name, method):
1191 # this causes stale locks to get reaped for more accurate reporting
1191 # this causes stale locks to get reaped for more accurate reporting
1192 try:
1192 try:
1193 l = method(False)
1193 l = method(False)
1194 except error.LockHeld:
1194 except error.LockHeld:
1195 l = None
1195 l = None
1196
1196
1197 if l:
1197 if l:
1198 l.release()
1198 l.release()
1199 else:
1199 else:
1200 try:
1200 try:
1201 stat = vfs.lstat(name)
1201 stat = vfs.lstat(name)
1202 age = now - stat.st_mtime
1202 age = now - stat.st_mtime
1203 user = util.username(stat.st_uid)
1203 user = util.username(stat.st_uid)
1204 locker = vfs.readlock(name)
1204 locker = vfs.readlock(name)
1205 if ":" in locker:
1205 if ":" in locker:
1206 host, pid = locker.split(':')
1206 host, pid = locker.split(':')
1207 if host == socket.gethostname():
1207 if host == socket.gethostname():
1208 locker = 'user %s, process %s' % (user, pid)
1208 locker = 'user %s, process %s' % (user, pid)
1209 else:
1209 else:
1210 locker = 'user %s, process %s, host %s' \
1210 locker = 'user %s, process %s, host %s' \
1211 % (user, pid, host)
1211 % (user, pid, host)
1212 ui.write(("%-6s %s (%ds)\n") % (name + ":", locker, age))
1212 ui.write(("%-6s %s (%ds)\n") % (name + ":", locker, age))
1213 return 1
1213 return 1
1214 except OSError as e:
1214 except OSError as e:
1215 if e.errno != errno.ENOENT:
1215 if e.errno != errno.ENOENT:
1216 raise
1216 raise
1217
1217
1218 ui.write(("%-6s free\n") % (name + ":"))
1218 ui.write(("%-6s free\n") % (name + ":"))
1219 return 0
1219 return 0
1220
1220
1221 held += report(repo.svfs, "lock", repo.lock)
1221 held += report(repo.svfs, "lock", repo.lock)
1222 held += report(repo.vfs, "wlock", repo.wlock)
1222 held += report(repo.vfs, "wlock", repo.wlock)
1223
1223
1224 return held
1224 return held
1225
1225
1226 @command('debugmergestate', [], '')
1226 @command('debugmergestate', [], '')
1227 def debugmergestate(ui, repo, *args):
1227 def debugmergestate(ui, repo, *args):
1228 """print merge state
1228 """print merge state
1229
1229
1230 Use --verbose to print out information about whether v1 or v2 merge state
1230 Use --verbose to print out information about whether v1 or v2 merge state
1231 was chosen."""
1231 was chosen."""
1232 def _hashornull(h):
1232 def _hashornull(h):
1233 if h == nullhex:
1233 if h == nullhex:
1234 return 'null'
1234 return 'null'
1235 else:
1235 else:
1236 return h
1236 return h
1237
1237
1238 def printrecords(version):
1238 def printrecords(version):
1239 ui.write(('* version %s records\n') % version)
1239 ui.write(('* version %s records\n') % version)
1240 if version == 1:
1240 if version == 1:
1241 records = v1records
1241 records = v1records
1242 else:
1242 else:
1243 records = v2records
1243 records = v2records
1244
1244
1245 for rtype, record in records:
1245 for rtype, record in records:
1246 # pretty print some record types
1246 # pretty print some record types
1247 if rtype == 'L':
1247 if rtype == 'L':
1248 ui.write(('local: %s\n') % record)
1248 ui.write(('local: %s\n') % record)
1249 elif rtype == 'O':
1249 elif rtype == 'O':
1250 ui.write(('other: %s\n') % record)
1250 ui.write(('other: %s\n') % record)
1251 elif rtype == 'm':
1251 elif rtype == 'm':
1252 driver, mdstate = record.split('\0', 1)
1252 driver, mdstate = record.split('\0', 1)
1253 ui.write(('merge driver: %s (state "%s")\n')
1253 ui.write(('merge driver: %s (state "%s")\n')
1254 % (driver, mdstate))
1254 % (driver, mdstate))
1255 elif rtype in 'FDC':
1255 elif rtype in 'FDC':
1256 r = record.split('\0')
1256 r = record.split('\0')
1257 f, state, hash, lfile, afile, anode, ofile = r[0:7]
1257 f, state, hash, lfile, afile, anode, ofile = r[0:7]
1258 if version == 1:
1258 if version == 1:
1259 onode = 'not stored in v1 format'
1259 onode = 'not stored in v1 format'
1260 flags = r[7]
1260 flags = r[7]
1261 else:
1261 else:
1262 onode, flags = r[7:9]
1262 onode, flags = r[7:9]
1263 ui.write(('file: %s (record type "%s", state "%s", hash %s)\n')
1263 ui.write(('file: %s (record type "%s", state "%s", hash %s)\n')
1264 % (f, rtype, state, _hashornull(hash)))
1264 % (f, rtype, state, _hashornull(hash)))
1265 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
1265 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
1266 ui.write((' ancestor path: %s (node %s)\n')
1266 ui.write((' ancestor path: %s (node %s)\n')
1267 % (afile, _hashornull(anode)))
1267 % (afile, _hashornull(anode)))
1268 ui.write((' other path: %s (node %s)\n')
1268 ui.write((' other path: %s (node %s)\n')
1269 % (ofile, _hashornull(onode)))
1269 % (ofile, _hashornull(onode)))
1270 elif rtype == 'f':
1270 elif rtype == 'f':
1271 filename, rawextras = record.split('\0', 1)
1271 filename, rawextras = record.split('\0', 1)
1272 extras = rawextras.split('\0')
1272 extras = rawextras.split('\0')
1273 i = 0
1273 i = 0
1274 extrastrings = []
1274 extrastrings = []
1275 while i < len(extras):
1275 while i < len(extras):
1276 extrastrings.append('%s = %s' % (extras[i], extras[i + 1]))
1276 extrastrings.append('%s = %s' % (extras[i], extras[i + 1]))
1277 i += 2
1277 i += 2
1278
1278
1279 ui.write(('file extras: %s (%s)\n')
1279 ui.write(('file extras: %s (%s)\n')
1280 % (filename, ', '.join(extrastrings)))
1280 % (filename, ', '.join(extrastrings)))
1281 elif rtype == 'l':
1281 elif rtype == 'l':
1282 labels = record.split('\0', 2)
1282 labels = record.split('\0', 2)
1283 labels = [l for l in labels if len(l) > 0]
1283 labels = [l for l in labels if len(l) > 0]
1284 ui.write(('labels:\n'))
1284 ui.write(('labels:\n'))
1285 ui.write((' local: %s\n' % labels[0]))
1285 ui.write((' local: %s\n' % labels[0]))
1286 ui.write((' other: %s\n' % labels[1]))
1286 ui.write((' other: %s\n' % labels[1]))
1287 if len(labels) > 2:
1287 if len(labels) > 2:
1288 ui.write((' base: %s\n' % labels[2]))
1288 ui.write((' base: %s\n' % labels[2]))
1289 else:
1289 else:
1290 ui.write(('unrecognized entry: %s\t%s\n')
1290 ui.write(('unrecognized entry: %s\t%s\n')
1291 % (rtype, record.replace('\0', '\t')))
1291 % (rtype, record.replace('\0', '\t')))
1292
1292
1293 # Avoid mergestate.read() since it may raise an exception for unsupported
1293 # Avoid mergestate.read() since it may raise an exception for unsupported
1294 # merge state records. We shouldn't be doing this, but this is OK since this
1294 # merge state records. We shouldn't be doing this, but this is OK since this
1295 # command is pretty low-level.
1295 # command is pretty low-level.
1296 ms = mergemod.mergestate(repo)
1296 ms = mergemod.mergestate(repo)
1297
1297
1298 # sort so that reasonable information is on top
1298 # sort so that reasonable information is on top
1299 v1records = ms._readrecordsv1()
1299 v1records = ms._readrecordsv1()
1300 v2records = ms._readrecordsv2()
1300 v2records = ms._readrecordsv2()
1301 order = 'LOml'
1301 order = 'LOml'
1302 def key(r):
1302 def key(r):
1303 idx = order.find(r[0])
1303 idx = order.find(r[0])
1304 if idx == -1:
1304 if idx == -1:
1305 return (1, r[1])
1305 return (1, r[1])
1306 else:
1306 else:
1307 return (0, idx)
1307 return (0, idx)
1308 v1records.sort(key=key)
1308 v1records.sort(key=key)
1309 v2records.sort(key=key)
1309 v2records.sort(key=key)
1310
1310
1311 if not v1records and not v2records:
1311 if not v1records and not v2records:
1312 ui.write(('no merge state found\n'))
1312 ui.write(('no merge state found\n'))
1313 elif not v2records:
1313 elif not v2records:
1314 ui.note(('no version 2 merge state\n'))
1314 ui.note(('no version 2 merge state\n'))
1315 printrecords(1)
1315 printrecords(1)
1316 elif ms._v1v2match(v1records, v2records):
1316 elif ms._v1v2match(v1records, v2records):
1317 ui.note(('v1 and v2 states match: using v2\n'))
1317 ui.note(('v1 and v2 states match: using v2\n'))
1318 printrecords(2)
1318 printrecords(2)
1319 else:
1319 else:
1320 ui.note(('v1 and v2 states mismatch: using v1\n'))
1320 ui.note(('v1 and v2 states mismatch: using v1\n'))
1321 printrecords(1)
1321 printrecords(1)
1322 if ui.verbose:
1322 if ui.verbose:
1323 printrecords(2)
1323 printrecords(2)
1324
1324
1325 @command('debugnamecomplete', [], _('NAME...'))
1325 @command('debugnamecomplete', [], _('NAME...'))
1326 def debugnamecomplete(ui, repo, *args):
1326 def debugnamecomplete(ui, repo, *args):
1327 '''complete "names" - tags, open branch names, bookmark names'''
1327 '''complete "names" - tags, open branch names, bookmark names'''
1328
1328
1329 names = set()
1329 names = set()
1330 # since we previously only listed open branches, we will handle that
1330 # since we previously only listed open branches, we will handle that
1331 # specially (after this for loop)
1331 # specially (after this for loop)
1332 for name, ns in repo.names.iteritems():
1332 for name, ns in repo.names.iteritems():
1333 if name != 'branches':
1333 if name != 'branches':
1334 names.update(ns.listnames(repo))
1334 names.update(ns.listnames(repo))
1335 names.update(tag for (tag, heads, tip, closed)
1335 names.update(tag for (tag, heads, tip, closed)
1336 in repo.branchmap().iterbranches() if not closed)
1336 in repo.branchmap().iterbranches() if not closed)
1337 completions = set()
1337 completions = set()
1338 if not args:
1338 if not args:
1339 args = ['']
1339 args = ['']
1340 for a in args:
1340 for a in args:
1341 completions.update(n for n in names if n.startswith(a))
1341 completions.update(n for n in names if n.startswith(a))
1342 ui.write('\n'.join(sorted(completions)))
1342 ui.write('\n'.join(sorted(completions)))
1343 ui.write('\n')
1343 ui.write('\n')
1344
1344
1345 @command('debugobsolete',
1345 @command('debugobsolete',
1346 [('', 'flags', 0, _('markers flag')),
1346 [('', 'flags', 0, _('markers flag')),
1347 ('', 'record-parents', False,
1347 ('', 'record-parents', False,
1348 _('record parent information for the precursor')),
1348 _('record parent information for the precursor')),
1349 ('r', 'rev', [], _('display markers relevant to REV')),
1349 ('r', 'rev', [], _('display markers relevant to REV')),
1350 ('', 'exclusive', False, _('restrict display to markers only '
1350 ('', 'exclusive', False, _('restrict display to markers only '
1351 'relevant to REV')),
1351 'relevant to REV')),
1352 ('', 'index', False, _('display index of the marker')),
1352 ('', 'index', False, _('display index of the marker')),
1353 ('', 'delete', [], _('delete markers specified by indices')),
1353 ('', 'delete', [], _('delete markers specified by indices')),
1354 ] + cmdutil.commitopts2 + cmdutil.formatteropts,
1354 ] + cmdutil.commitopts2 + cmdutil.formatteropts,
1355 _('[OBSOLETED [REPLACEMENT ...]]'))
1355 _('[OBSOLETED [REPLACEMENT ...]]'))
1356 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
1356 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
1357 """create arbitrary obsolete marker
1357 """create arbitrary obsolete marker
1358
1358
1359 With no arguments, displays the list of obsolescence markers."""
1359 With no arguments, displays the list of obsolescence markers."""
1360
1360
1361 opts = pycompat.byteskwargs(opts)
1361 opts = pycompat.byteskwargs(opts)
1362
1362
1363 def parsenodeid(s):
1363 def parsenodeid(s):
1364 try:
1364 try:
1365 # We do not use revsingle/revrange functions here to accept
1365 # We do not use revsingle/revrange functions here to accept
1366 # arbitrary node identifiers, possibly not present in the
1366 # arbitrary node identifiers, possibly not present in the
1367 # local repository.
1367 # local repository.
1368 n = bin(s)
1368 n = bin(s)
1369 if len(n) != len(nullid):
1369 if len(n) != len(nullid):
1370 raise TypeError()
1370 raise TypeError()
1371 return n
1371 return n
1372 except TypeError:
1372 except TypeError:
1373 raise error.Abort('changeset references must be full hexadecimal '
1373 raise error.Abort('changeset references must be full hexadecimal '
1374 'node identifiers')
1374 'node identifiers')
1375
1375
1376 if opts.get('delete'):
1376 if opts.get('delete'):
1377 indices = []
1377 indices = []
1378 for v in opts.get('delete'):
1378 for v in opts.get('delete'):
1379 try:
1379 try:
1380 indices.append(int(v))
1380 indices.append(int(v))
1381 except ValueError:
1381 except ValueError:
1382 raise error.Abort(_('invalid index value: %r') % v,
1382 raise error.Abort(_('invalid index value: %r') % v,
1383 hint=_('use integers for indices'))
1383 hint=_('use integers for indices'))
1384
1384
1385 if repo.currenttransaction():
1385 if repo.currenttransaction():
1386 raise error.Abort(_('cannot delete obsmarkers in the middle '
1386 raise error.Abort(_('cannot delete obsmarkers in the middle '
1387 'of transaction.'))
1387 'of transaction.'))
1388
1388
1389 with repo.lock():
1389 with repo.lock():
1390 n = repair.deleteobsmarkers(repo.obsstore, indices)
1390 n = repair.deleteobsmarkers(repo.obsstore, indices)
1391 ui.write(_('deleted %i obsolescence markers\n') % n)
1391 ui.write(_('deleted %i obsolescence markers\n') % n)
1392
1392
1393 return
1393 return
1394
1394
1395 if precursor is not None:
1395 if precursor is not None:
1396 if opts['rev']:
1396 if opts['rev']:
1397 raise error.Abort('cannot select revision when creating marker')
1397 raise error.Abort('cannot select revision when creating marker')
1398 metadata = {}
1398 metadata = {}
1399 metadata['user'] = opts['user'] or ui.username()
1399 metadata['user'] = opts['user'] or ui.username()
1400 succs = tuple(parsenodeid(succ) for succ in successors)
1400 succs = tuple(parsenodeid(succ) for succ in successors)
1401 l = repo.lock()
1401 l = repo.lock()
1402 try:
1402 try:
1403 tr = repo.transaction('debugobsolete')
1403 tr = repo.transaction('debugobsolete')
1404 try:
1404 try:
1405 date = opts.get('date')
1405 date = opts.get('date')
1406 if date:
1406 if date:
1407 date = util.parsedate(date)
1407 date = util.parsedate(date)
1408 else:
1408 else:
1409 date = None
1409 date = None
1410 prec = parsenodeid(precursor)
1410 prec = parsenodeid(precursor)
1411 parents = None
1411 parents = None
1412 if opts['record_parents']:
1412 if opts['record_parents']:
1413 if prec not in repo.unfiltered():
1413 if prec not in repo.unfiltered():
1414 raise error.Abort('cannot used --record-parents on '
1414 raise error.Abort('cannot used --record-parents on '
1415 'unknown changesets')
1415 'unknown changesets')
1416 parents = repo.unfiltered()[prec].parents()
1416 parents = repo.unfiltered()[prec].parents()
1417 parents = tuple(p.node() for p in parents)
1417 parents = tuple(p.node() for p in parents)
1418 repo.obsstore.create(tr, prec, succs, opts['flags'],
1418 repo.obsstore.create(tr, prec, succs, opts['flags'],
1419 parents=parents, date=date,
1419 parents=parents, date=date,
1420 metadata=metadata, ui=ui)
1420 metadata=metadata, ui=ui)
1421 tr.close()
1421 tr.close()
1422 except ValueError as exc:
1422 except ValueError as exc:
1423 raise error.Abort(_('bad obsmarker input: %s') % exc)
1423 raise error.Abort(_('bad obsmarker input: %s') % exc)
1424 finally:
1424 finally:
1425 tr.release()
1425 tr.release()
1426 finally:
1426 finally:
1427 l.release()
1427 l.release()
1428 else:
1428 else:
1429 if opts['rev']:
1429 if opts['rev']:
1430 revs = scmutil.revrange(repo, opts['rev'])
1430 revs = scmutil.revrange(repo, opts['rev'])
1431 nodes = [repo[r].node() for r in revs]
1431 nodes = [repo[r].node() for r in revs]
1432 markers = list(obsutil.getmarkers(repo, nodes=nodes,
1432 markers = list(obsutil.getmarkers(repo, nodes=nodes,
1433 exclusive=opts['exclusive']))
1433 exclusive=opts['exclusive']))
1434 markers.sort(key=lambda x: x._data)
1434 markers.sort(key=lambda x: x._data)
1435 else:
1435 else:
1436 markers = obsutil.getmarkers(repo)
1436 markers = obsutil.getmarkers(repo)
1437
1437
1438 markerstoiter = markers
1438 markerstoiter = markers
1439 isrelevant = lambda m: True
1439 isrelevant = lambda m: True
1440 if opts.get('rev') and opts.get('index'):
1440 if opts.get('rev') and opts.get('index'):
1441 markerstoiter = obsutil.getmarkers(repo)
1441 markerstoiter = obsutil.getmarkers(repo)
1442 markerset = set(markers)
1442 markerset = set(markers)
1443 isrelevant = lambda m: m in markerset
1443 isrelevant = lambda m: m in markerset
1444
1444
1445 fm = ui.formatter('debugobsolete', opts)
1445 fm = ui.formatter('debugobsolete', opts)
1446 for i, m in enumerate(markerstoiter):
1446 for i, m in enumerate(markerstoiter):
1447 if not isrelevant(m):
1447 if not isrelevant(m):
1448 # marker can be irrelevant when we're iterating over a set
1448 # marker can be irrelevant when we're iterating over a set
1449 # of markers (markerstoiter) which is bigger than the set
1449 # of markers (markerstoiter) which is bigger than the set
1450 # of markers we want to display (markers)
1450 # of markers we want to display (markers)
1451 # this can happen if both --index and --rev options are
1451 # this can happen if both --index and --rev options are
1452 # provided and thus we need to iterate over all of the markers
1452 # provided and thus we need to iterate over all of the markers
1453 # to get the correct indices, but only display the ones that
1453 # to get the correct indices, but only display the ones that
1454 # are relevant to --rev value
1454 # are relevant to --rev value
1455 continue
1455 continue
1456 fm.startitem()
1456 fm.startitem()
1457 ind = i if opts.get('index') else None
1457 ind = i if opts.get('index') else None
1458 cmdutil.showmarker(fm, m, index=ind)
1458 cmdutil.showmarker(fm, m, index=ind)
1459 fm.end()
1459 fm.end()
1460
1460
1461 @command('debugpathcomplete',
1461 @command('debugpathcomplete',
1462 [('f', 'full', None, _('complete an entire path')),
1462 [('f', 'full', None, _('complete an entire path')),
1463 ('n', 'normal', None, _('show only normal files')),
1463 ('n', 'normal', None, _('show only normal files')),
1464 ('a', 'added', None, _('show only added files')),
1464 ('a', 'added', None, _('show only added files')),
1465 ('r', 'removed', None, _('show only removed files'))],
1465 ('r', 'removed', None, _('show only removed files'))],
1466 _('FILESPEC...'))
1466 _('FILESPEC...'))
1467 def debugpathcomplete(ui, repo, *specs, **opts):
1467 def debugpathcomplete(ui, repo, *specs, **opts):
1468 '''complete part or all of a tracked path
1468 '''complete part or all of a tracked path
1469
1469
1470 This command supports shells that offer path name completion. It
1470 This command supports shells that offer path name completion. It
1471 currently completes only files already known to the dirstate.
1471 currently completes only files already known to the dirstate.
1472
1472
1473 Completion extends only to the next path segment unless
1473 Completion extends only to the next path segment unless
1474 --full is specified, in which case entire paths are used.'''
1474 --full is specified, in which case entire paths are used.'''
1475
1475
1476 def complete(path, acceptable):
1476 def complete(path, acceptable):
1477 dirstate = repo.dirstate
1477 dirstate = repo.dirstate
1478 spec = os.path.normpath(os.path.join(pycompat.getcwd(), path))
1478 spec = os.path.normpath(os.path.join(pycompat.getcwd(), path))
1479 rootdir = repo.root + pycompat.ossep
1479 rootdir = repo.root + pycompat.ossep
1480 if spec != repo.root and not spec.startswith(rootdir):
1480 if spec != repo.root and not spec.startswith(rootdir):
1481 return [], []
1481 return [], []
1482 if os.path.isdir(spec):
1482 if os.path.isdir(spec):
1483 spec += '/'
1483 spec += '/'
1484 spec = spec[len(rootdir):]
1484 spec = spec[len(rootdir):]
1485 fixpaths = pycompat.ossep != '/'
1485 fixpaths = pycompat.ossep != '/'
1486 if fixpaths:
1486 if fixpaths:
1487 spec = spec.replace(pycompat.ossep, '/')
1487 spec = spec.replace(pycompat.ossep, '/')
1488 speclen = len(spec)
1488 speclen = len(spec)
1489 fullpaths = opts[r'full']
1489 fullpaths = opts[r'full']
1490 files, dirs = set(), set()
1490 files, dirs = set(), set()
1491 adddir, addfile = dirs.add, files.add
1491 adddir, addfile = dirs.add, files.add
1492 for f, st in dirstate.iteritems():
1492 for f, st in dirstate.iteritems():
1493 if f.startswith(spec) and st[0] in acceptable:
1493 if f.startswith(spec) and st[0] in acceptable:
1494 if fixpaths:
1494 if fixpaths:
1495 f = f.replace('/', pycompat.ossep)
1495 f = f.replace('/', pycompat.ossep)
1496 if fullpaths:
1496 if fullpaths:
1497 addfile(f)
1497 addfile(f)
1498 continue
1498 continue
1499 s = f.find(pycompat.ossep, speclen)
1499 s = f.find(pycompat.ossep, speclen)
1500 if s >= 0:
1500 if s >= 0:
1501 adddir(f[:s])
1501 adddir(f[:s])
1502 else:
1502 else:
1503 addfile(f)
1503 addfile(f)
1504 return files, dirs
1504 return files, dirs
1505
1505
1506 acceptable = ''
1506 acceptable = ''
1507 if opts[r'normal']:
1507 if opts[r'normal']:
1508 acceptable += 'nm'
1508 acceptable += 'nm'
1509 if opts[r'added']:
1509 if opts[r'added']:
1510 acceptable += 'a'
1510 acceptable += 'a'
1511 if opts[r'removed']:
1511 if opts[r'removed']:
1512 acceptable += 'r'
1512 acceptable += 'r'
1513 cwd = repo.getcwd()
1513 cwd = repo.getcwd()
1514 if not specs:
1514 if not specs:
1515 specs = ['.']
1515 specs = ['.']
1516
1516
1517 files, dirs = set(), set()
1517 files, dirs = set(), set()
1518 for spec in specs:
1518 for spec in specs:
1519 f, d = complete(spec, acceptable or 'nmar')
1519 f, d = complete(spec, acceptable or 'nmar')
1520 files.update(f)
1520 files.update(f)
1521 dirs.update(d)
1521 dirs.update(d)
1522 files.update(dirs)
1522 files.update(dirs)
1523 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
1523 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
1524 ui.write('\n')
1524 ui.write('\n')
1525
1525
1526 @command('debugpickmergetool',
1526 @command('debugpickmergetool',
1527 [('r', 'rev', '', _('check for files in this revision'), _('REV')),
1527 [('r', 'rev', '', _('check for files in this revision'), _('REV')),
1528 ('', 'changedelete', None, _('emulate merging change and delete')),
1528 ('', 'changedelete', None, _('emulate merging change and delete')),
1529 ] + cmdutil.walkopts + cmdutil.mergetoolopts,
1529 ] + cmdutil.walkopts + cmdutil.mergetoolopts,
1530 _('[PATTERN]...'),
1530 _('[PATTERN]...'),
1531 inferrepo=True)
1531 inferrepo=True)
1532 def debugpickmergetool(ui, repo, *pats, **opts):
1532 def debugpickmergetool(ui, repo, *pats, **opts):
1533 """examine which merge tool is chosen for specified file
1533 """examine which merge tool is chosen for specified file
1534
1534
1535 As described in :hg:`help merge-tools`, Mercurial examines
1535 As described in :hg:`help merge-tools`, Mercurial examines
1536 configurations below in this order to decide which merge tool is
1536 configurations below in this order to decide which merge tool is
1537 chosen for specified file.
1537 chosen for specified file.
1538
1538
1539 1. ``--tool`` option
1539 1. ``--tool`` option
1540 2. ``HGMERGE`` environment variable
1540 2. ``HGMERGE`` environment variable
1541 3. configurations in ``merge-patterns`` section
1541 3. configurations in ``merge-patterns`` section
1542 4. configuration of ``ui.merge``
1542 4. configuration of ``ui.merge``
1543 5. configurations in ``merge-tools`` section
1543 5. configurations in ``merge-tools`` section
1544 6. ``hgmerge`` tool (for historical reason only)
1544 6. ``hgmerge`` tool (for historical reason only)
1545 7. default tool for fallback (``:merge`` or ``:prompt``)
1545 7. default tool for fallback (``:merge`` or ``:prompt``)
1546
1546
1547 This command writes out examination result in the style below::
1547 This command writes out examination result in the style below::
1548
1548
1549 FILE = MERGETOOL
1549 FILE = MERGETOOL
1550
1550
1551 By default, all files known in the first parent context of the
1551 By default, all files known in the first parent context of the
1552 working directory are examined. Use file patterns and/or -I/-X
1552 working directory are examined. Use file patterns and/or -I/-X
1553 options to limit target files. -r/--rev is also useful to examine
1553 options to limit target files. -r/--rev is also useful to examine
1554 files in another context without actual updating to it.
1554 files in another context without actual updating to it.
1555
1555
1556 With --debug, this command shows warning messages while matching
1556 With --debug, this command shows warning messages while matching
1557 against ``merge-patterns`` and so on, too. It is recommended to
1557 against ``merge-patterns`` and so on, too. It is recommended to
1558 use this option with explicit file patterns and/or -I/-X options,
1558 use this option with explicit file patterns and/or -I/-X options,
1559 because this option increases amount of output per file according
1559 because this option increases amount of output per file according
1560 to configurations in hgrc.
1560 to configurations in hgrc.
1561
1561
1562 With -v/--verbose, this command shows configurations below at
1562 With -v/--verbose, this command shows configurations below at
1563 first (only if specified).
1563 first (only if specified).
1564
1564
1565 - ``--tool`` option
1565 - ``--tool`` option
1566 - ``HGMERGE`` environment variable
1566 - ``HGMERGE`` environment variable
1567 - configuration of ``ui.merge``
1567 - configuration of ``ui.merge``
1568
1568
1569 If merge tool is chosen before matching against
1569 If merge tool is chosen before matching against
1570 ``merge-patterns``, this command can't show any helpful
1570 ``merge-patterns``, this command can't show any helpful
1571 information, even with --debug. In such case, information above is
1571 information, even with --debug. In such case, information above is
1572 useful to know why a merge tool is chosen.
1572 useful to know why a merge tool is chosen.
1573 """
1573 """
1574 opts = pycompat.byteskwargs(opts)
1574 opts = pycompat.byteskwargs(opts)
1575 overrides = {}
1575 overrides = {}
1576 if opts['tool']:
1576 if opts['tool']:
1577 overrides[('ui', 'forcemerge')] = opts['tool']
1577 overrides[('ui', 'forcemerge')] = opts['tool']
1578 ui.note(('with --tool %r\n') % (opts['tool']))
1578 ui.note(('with --tool %r\n') % (opts['tool']))
1579
1579
1580 with ui.configoverride(overrides, 'debugmergepatterns'):
1580 with ui.configoverride(overrides, 'debugmergepatterns'):
1581 hgmerge = encoding.environ.get("HGMERGE")
1581 hgmerge = encoding.environ.get("HGMERGE")
1582 if hgmerge is not None:
1582 if hgmerge is not None:
1583 ui.note(('with HGMERGE=%r\n') % (hgmerge))
1583 ui.note(('with HGMERGE=%r\n') % (hgmerge))
1584 uimerge = ui.config("ui", "merge")
1584 uimerge = ui.config("ui", "merge")
1585 if uimerge:
1585 if uimerge:
1586 ui.note(('with ui.merge=%r\n') % (uimerge))
1586 ui.note(('with ui.merge=%r\n') % (uimerge))
1587
1587
1588 ctx = scmutil.revsingle(repo, opts.get('rev'))
1588 ctx = scmutil.revsingle(repo, opts.get('rev'))
1589 m = scmutil.match(ctx, pats, opts)
1589 m = scmutil.match(ctx, pats, opts)
1590 changedelete = opts['changedelete']
1590 changedelete = opts['changedelete']
1591 for path in ctx.walk(m):
1591 for path in ctx.walk(m):
1592 fctx = ctx[path]
1592 fctx = ctx[path]
1593 try:
1593 try:
1594 if not ui.debugflag:
1594 if not ui.debugflag:
1595 ui.pushbuffer(error=True)
1595 ui.pushbuffer(error=True)
1596 tool, toolpath = filemerge._picktool(repo, ui, path,
1596 tool, toolpath = filemerge._picktool(repo, ui, path,
1597 fctx.isbinary(),
1597 fctx.isbinary(),
1598 'l' in fctx.flags(),
1598 'l' in fctx.flags(),
1599 changedelete)
1599 changedelete)
1600 finally:
1600 finally:
1601 if not ui.debugflag:
1601 if not ui.debugflag:
1602 ui.popbuffer()
1602 ui.popbuffer()
1603 ui.write(('%s = %s\n') % (path, tool))
1603 ui.write(('%s = %s\n') % (path, tool))
1604
1604
1605 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
1605 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
1606 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1606 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1607 '''access the pushkey key/value protocol
1607 '''access the pushkey key/value protocol
1608
1608
1609 With two args, list the keys in the given namespace.
1609 With two args, list the keys in the given namespace.
1610
1610
1611 With five args, set a key to new if it currently is set to old.
1611 With five args, set a key to new if it currently is set to old.
1612 Reports success or failure.
1612 Reports success or failure.
1613 '''
1613 '''
1614
1614
1615 target = hg.peer(ui, {}, repopath)
1615 target = hg.peer(ui, {}, repopath)
1616 if keyinfo:
1616 if keyinfo:
1617 key, old, new = keyinfo
1617 key, old, new = keyinfo
1618 r = target.pushkey(namespace, key, old, new)
1618 r = target.pushkey(namespace, key, old, new)
1619 ui.status(str(r) + '\n')
1619 ui.status(str(r) + '\n')
1620 return not r
1620 return not r
1621 else:
1621 else:
1622 for k, v in sorted(target.listkeys(namespace).iteritems()):
1622 for k, v in sorted(target.listkeys(namespace).iteritems()):
1623 ui.write("%s\t%s\n" % (util.escapestr(k),
1623 ui.write("%s\t%s\n" % (util.escapestr(k),
1624 util.escapestr(v)))
1624 util.escapestr(v)))
1625
1625
1626 @command('debugpvec', [], _('A B'))
1626 @command('debugpvec', [], _('A B'))
1627 def debugpvec(ui, repo, a, b=None):
1627 def debugpvec(ui, repo, a, b=None):
1628 ca = scmutil.revsingle(repo, a)
1628 ca = scmutil.revsingle(repo, a)
1629 cb = scmutil.revsingle(repo, b)
1629 cb = scmutil.revsingle(repo, b)
1630 pa = pvec.ctxpvec(ca)
1630 pa = pvec.ctxpvec(ca)
1631 pb = pvec.ctxpvec(cb)
1631 pb = pvec.ctxpvec(cb)
1632 if pa == pb:
1632 if pa == pb:
1633 rel = "="
1633 rel = "="
1634 elif pa > pb:
1634 elif pa > pb:
1635 rel = ">"
1635 rel = ">"
1636 elif pa < pb:
1636 elif pa < pb:
1637 rel = "<"
1637 rel = "<"
1638 elif pa | pb:
1638 elif pa | pb:
1639 rel = "|"
1639 rel = "|"
1640 ui.write(_("a: %s\n") % pa)
1640 ui.write(_("a: %s\n") % pa)
1641 ui.write(_("b: %s\n") % pb)
1641 ui.write(_("b: %s\n") % pb)
1642 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
1642 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
1643 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
1643 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
1644 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
1644 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
1645 pa.distance(pb), rel))
1645 pa.distance(pb), rel))
1646
1646
1647 @command('debugrebuilddirstate|debugrebuildstate',
1647 @command('debugrebuilddirstate|debugrebuildstate',
1648 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
1648 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
1649 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
1649 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
1650 'the working copy parent')),
1650 'the working copy parent')),
1651 ],
1651 ],
1652 _('[-r REV]'))
1652 _('[-r REV]'))
1653 def debugrebuilddirstate(ui, repo, rev, **opts):
1653 def debugrebuilddirstate(ui, repo, rev, **opts):
1654 """rebuild the dirstate as it would look like for the given revision
1654 """rebuild the dirstate as it would look like for the given revision
1655
1655
1656 If no revision is specified the first current parent will be used.
1656 If no revision is specified the first current parent will be used.
1657
1657
1658 The dirstate will be set to the files of the given revision.
1658 The dirstate will be set to the files of the given revision.
1659 The actual working directory content or existing dirstate
1659 The actual working directory content or existing dirstate
1660 information such as adds or removes is not considered.
1660 information such as adds or removes is not considered.
1661
1661
1662 ``minimal`` will only rebuild the dirstate status for files that claim to be
1662 ``minimal`` will only rebuild the dirstate status for files that claim to be
1663 tracked but are not in the parent manifest, or that exist in the parent
1663 tracked but are not in the parent manifest, or that exist in the parent
1664 manifest but are not in the dirstate. It will not change adds, removes, or
1664 manifest but are not in the dirstate. It will not change adds, removes, or
1665 modified files that are in the working copy parent.
1665 modified files that are in the working copy parent.
1666
1666
1667 One use of this command is to make the next :hg:`status` invocation
1667 One use of this command is to make the next :hg:`status` invocation
1668 check the actual file content.
1668 check the actual file content.
1669 """
1669 """
1670 ctx = scmutil.revsingle(repo, rev)
1670 ctx = scmutil.revsingle(repo, rev)
1671 with repo.wlock():
1671 with repo.wlock():
1672 dirstate = repo.dirstate
1672 dirstate = repo.dirstate
1673 changedfiles = None
1673 changedfiles = None
1674 # See command doc for what minimal does.
1674 # See command doc for what minimal does.
1675 if opts.get(r'minimal'):
1675 if opts.get(r'minimal'):
1676 manifestfiles = set(ctx.manifest().keys())
1676 manifestfiles = set(ctx.manifest().keys())
1677 dirstatefiles = set(dirstate)
1677 dirstatefiles = set(dirstate)
1678 manifestonly = manifestfiles - dirstatefiles
1678 manifestonly = manifestfiles - dirstatefiles
1679 dsonly = dirstatefiles - manifestfiles
1679 dsonly = dirstatefiles - manifestfiles
1680 dsnotadded = set(f for f in dsonly if dirstate[f] != 'a')
1680 dsnotadded = set(f for f in dsonly if dirstate[f] != 'a')
1681 changedfiles = manifestonly | dsnotadded
1681 changedfiles = manifestonly | dsnotadded
1682
1682
1683 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
1683 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
1684
1684
1685 @command('debugrebuildfncache', [], '')
1685 @command('debugrebuildfncache', [], '')
1686 def debugrebuildfncache(ui, repo):
1686 def debugrebuildfncache(ui, repo):
1687 """rebuild the fncache file"""
1687 """rebuild the fncache file"""
1688 repair.rebuildfncache(ui, repo)
1688 repair.rebuildfncache(ui, repo)
1689
1689
1690 @command('debugrename',
1690 @command('debugrename',
1691 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1691 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1692 _('[-r REV] FILE'))
1692 _('[-r REV] FILE'))
1693 def debugrename(ui, repo, file1, *pats, **opts):
1693 def debugrename(ui, repo, file1, *pats, **opts):
1694 """dump rename information"""
1694 """dump rename information"""
1695
1695
1696 opts = pycompat.byteskwargs(opts)
1696 opts = pycompat.byteskwargs(opts)
1697 ctx = scmutil.revsingle(repo, opts.get('rev'))
1697 ctx = scmutil.revsingle(repo, opts.get('rev'))
1698 m = scmutil.match(ctx, (file1,) + pats, opts)
1698 m = scmutil.match(ctx, (file1,) + pats, opts)
1699 for abs in ctx.walk(m):
1699 for abs in ctx.walk(m):
1700 fctx = ctx[abs]
1700 fctx = ctx[abs]
1701 o = fctx.filelog().renamed(fctx.filenode())
1701 o = fctx.filelog().renamed(fctx.filenode())
1702 rel = m.rel(abs)
1702 rel = m.rel(abs)
1703 if o:
1703 if o:
1704 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1704 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1705 else:
1705 else:
1706 ui.write(_("%s not renamed\n") % rel)
1706 ui.write(_("%s not renamed\n") % rel)
1707
1707
1708 @command('debugrevlog', cmdutil.debugrevlogopts +
1708 @command('debugrevlog', cmdutil.debugrevlogopts +
1709 [('d', 'dump', False, _('dump index data'))],
1709 [('d', 'dump', False, _('dump index data'))],
1710 _('-c|-m|FILE'),
1710 _('-c|-m|FILE'),
1711 optionalrepo=True)
1711 optionalrepo=True)
1712 def debugrevlog(ui, repo, file_=None, **opts):
1712 def debugrevlog(ui, repo, file_=None, **opts):
1713 """show data and statistics about a revlog"""
1713 """show data and statistics about a revlog"""
1714 opts = pycompat.byteskwargs(opts)
1714 opts = pycompat.byteskwargs(opts)
1715 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1715 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1716
1716
1717 if opts.get("dump"):
1717 if opts.get("dump"):
1718 numrevs = len(r)
1718 numrevs = len(r)
1719 ui.write(("# rev p1rev p2rev start end deltastart base p1 p2"
1719 ui.write(("# rev p1rev p2rev start end deltastart base p1 p2"
1720 " rawsize totalsize compression heads chainlen\n"))
1720 " rawsize totalsize compression heads chainlen\n"))
1721 ts = 0
1721 ts = 0
1722 heads = set()
1722 heads = set()
1723
1723
1724 for rev in xrange(numrevs):
1724 for rev in xrange(numrevs):
1725 dbase = r.deltaparent(rev)
1725 dbase = r.deltaparent(rev)
1726 if dbase == -1:
1726 if dbase == -1:
1727 dbase = rev
1727 dbase = rev
1728 cbase = r.chainbase(rev)
1728 cbase = r.chainbase(rev)
1729 clen = r.chainlen(rev)
1729 clen = r.chainlen(rev)
1730 p1, p2 = r.parentrevs(rev)
1730 p1, p2 = r.parentrevs(rev)
1731 rs = r.rawsize(rev)
1731 rs = r.rawsize(rev)
1732 ts = ts + rs
1732 ts = ts + rs
1733 heads -= set(r.parentrevs(rev))
1733 heads -= set(r.parentrevs(rev))
1734 heads.add(rev)
1734 heads.add(rev)
1735 try:
1735 try:
1736 compression = ts / r.end(rev)
1736 compression = ts / r.end(rev)
1737 except ZeroDivisionError:
1737 except ZeroDivisionError:
1738 compression = 0
1738 compression = 0
1739 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
1739 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
1740 "%11d %5d %8d\n" %
1740 "%11d %5d %8d\n" %
1741 (rev, p1, p2, r.start(rev), r.end(rev),
1741 (rev, p1, p2, r.start(rev), r.end(rev),
1742 r.start(dbase), r.start(cbase),
1742 r.start(dbase), r.start(cbase),
1743 r.start(p1), r.start(p2),
1743 r.start(p1), r.start(p2),
1744 rs, ts, compression, len(heads), clen))
1744 rs, ts, compression, len(heads), clen))
1745 return 0
1745 return 0
1746
1746
1747 v = r.version
1747 v = r.version
1748 format = v & 0xFFFF
1748 format = v & 0xFFFF
1749 flags = []
1749 flags = []
1750 gdelta = False
1750 gdelta = False
1751 if v & revlog.FLAG_INLINE_DATA:
1751 if v & revlog.FLAG_INLINE_DATA:
1752 flags.append('inline')
1752 flags.append('inline')
1753 if v & revlog.FLAG_GENERALDELTA:
1753 if v & revlog.FLAG_GENERALDELTA:
1754 gdelta = True
1754 gdelta = True
1755 flags.append('generaldelta')
1755 flags.append('generaldelta')
1756 if not flags:
1756 if not flags:
1757 flags = ['(none)']
1757 flags = ['(none)']
1758
1758
1759 nummerges = 0
1759 nummerges = 0
1760 numfull = 0
1760 numfull = 0
1761 numprev = 0
1761 numprev = 0
1762 nump1 = 0
1762 nump1 = 0
1763 nump2 = 0
1763 nump2 = 0
1764 numother = 0
1764 numother = 0
1765 nump1prev = 0
1765 nump1prev = 0
1766 nump2prev = 0
1766 nump2prev = 0
1767 chainlengths = []
1767 chainlengths = []
1768 chainbases = []
1768 chainbases = []
1769 chainspans = []
1769 chainspans = []
1770
1770
1771 datasize = [None, 0, 0]
1771 datasize = [None, 0, 0]
1772 fullsize = [None, 0, 0]
1772 fullsize = [None, 0, 0]
1773 deltasize = [None, 0, 0]
1773 deltasize = [None, 0, 0]
1774 chunktypecounts = {}
1774 chunktypecounts = {}
1775 chunktypesizes = {}
1775 chunktypesizes = {}
1776
1776
1777 def addsize(size, l):
1777 def addsize(size, l):
1778 if l[0] is None or size < l[0]:
1778 if l[0] is None or size < l[0]:
1779 l[0] = size
1779 l[0] = size
1780 if size > l[1]:
1780 if size > l[1]:
1781 l[1] = size
1781 l[1] = size
1782 l[2] += size
1782 l[2] += size
1783
1783
1784 numrevs = len(r)
1784 numrevs = len(r)
1785 for rev in xrange(numrevs):
1785 for rev in xrange(numrevs):
1786 p1, p2 = r.parentrevs(rev)
1786 p1, p2 = r.parentrevs(rev)
1787 delta = r.deltaparent(rev)
1787 delta = r.deltaparent(rev)
1788 if format > 0:
1788 if format > 0:
1789 addsize(r.rawsize(rev), datasize)
1789 addsize(r.rawsize(rev), datasize)
1790 if p2 != nullrev:
1790 if p2 != nullrev:
1791 nummerges += 1
1791 nummerges += 1
1792 size = r.length(rev)
1792 size = r.length(rev)
1793 if delta == nullrev:
1793 if delta == nullrev:
1794 chainlengths.append(0)
1794 chainlengths.append(0)
1795 chainbases.append(r.start(rev))
1795 chainbases.append(r.start(rev))
1796 chainspans.append(size)
1796 chainspans.append(size)
1797 numfull += 1
1797 numfull += 1
1798 addsize(size, fullsize)
1798 addsize(size, fullsize)
1799 else:
1799 else:
1800 chainlengths.append(chainlengths[delta] + 1)
1800 chainlengths.append(chainlengths[delta] + 1)
1801 baseaddr = chainbases[delta]
1801 baseaddr = chainbases[delta]
1802 revaddr = r.start(rev)
1802 revaddr = r.start(rev)
1803 chainbases.append(baseaddr)
1803 chainbases.append(baseaddr)
1804 chainspans.append((revaddr - baseaddr) + size)
1804 chainspans.append((revaddr - baseaddr) + size)
1805 addsize(size, deltasize)
1805 addsize(size, deltasize)
1806 if delta == rev - 1:
1806 if delta == rev - 1:
1807 numprev += 1
1807 numprev += 1
1808 if delta == p1:
1808 if delta == p1:
1809 nump1prev += 1
1809 nump1prev += 1
1810 elif delta == p2:
1810 elif delta == p2:
1811 nump2prev += 1
1811 nump2prev += 1
1812 elif delta == p1:
1812 elif delta == p1:
1813 nump1 += 1
1813 nump1 += 1
1814 elif delta == p2:
1814 elif delta == p2:
1815 nump2 += 1
1815 nump2 += 1
1816 elif delta != nullrev:
1816 elif delta != nullrev:
1817 numother += 1
1817 numother += 1
1818
1818
1819 # Obtain data on the raw chunks in the revlog.
1819 # Obtain data on the raw chunks in the revlog.
1820 segment = r._getsegmentforrevs(rev, rev)[1]
1820 segment = r._getsegmentforrevs(rev, rev)[1]
1821 if segment:
1821 if segment:
1822 chunktype = bytes(segment[0:1])
1822 chunktype = bytes(segment[0:1])
1823 else:
1823 else:
1824 chunktype = 'empty'
1824 chunktype = 'empty'
1825
1825
1826 if chunktype not in chunktypecounts:
1826 if chunktype not in chunktypecounts:
1827 chunktypecounts[chunktype] = 0
1827 chunktypecounts[chunktype] = 0
1828 chunktypesizes[chunktype] = 0
1828 chunktypesizes[chunktype] = 0
1829
1829
1830 chunktypecounts[chunktype] += 1
1830 chunktypecounts[chunktype] += 1
1831 chunktypesizes[chunktype] += size
1831 chunktypesizes[chunktype] += size
1832
1832
1833 # Adjust size min value for empty cases
1833 # Adjust size min value for empty cases
1834 for size in (datasize, fullsize, deltasize):
1834 for size in (datasize, fullsize, deltasize):
1835 if size[0] is None:
1835 if size[0] is None:
1836 size[0] = 0
1836 size[0] = 0
1837
1837
1838 numdeltas = numrevs - numfull
1838 numdeltas = numrevs - numfull
1839 numoprev = numprev - nump1prev - nump2prev
1839 numoprev = numprev - nump1prev - nump2prev
1840 totalrawsize = datasize[2]
1840 totalrawsize = datasize[2]
1841 datasize[2] /= numrevs
1841 datasize[2] /= numrevs
1842 fulltotal = fullsize[2]
1842 fulltotal = fullsize[2]
1843 fullsize[2] /= numfull
1843 fullsize[2] /= numfull
1844 deltatotal = deltasize[2]
1844 deltatotal = deltasize[2]
1845 if numrevs - numfull > 0:
1845 if numrevs - numfull > 0:
1846 deltasize[2] /= numrevs - numfull
1846 deltasize[2] /= numrevs - numfull
1847 totalsize = fulltotal + deltatotal
1847 totalsize = fulltotal + deltatotal
1848 avgchainlen = sum(chainlengths) / numrevs
1848 avgchainlen = sum(chainlengths) / numrevs
1849 maxchainlen = max(chainlengths)
1849 maxchainlen = max(chainlengths)
1850 maxchainspan = max(chainspans)
1850 maxchainspan = max(chainspans)
1851 compratio = 1
1851 compratio = 1
1852 if totalsize:
1852 if totalsize:
1853 compratio = totalrawsize / totalsize
1853 compratio = totalrawsize / totalsize
1854
1854
1855 basedfmtstr = '%%%dd\n'
1855 basedfmtstr = '%%%dd\n'
1856 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1856 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1857
1857
1858 def dfmtstr(max):
1858 def dfmtstr(max):
1859 return basedfmtstr % len(str(max))
1859 return basedfmtstr % len(str(max))
1860 def pcfmtstr(max, padding=0):
1860 def pcfmtstr(max, padding=0):
1861 return basepcfmtstr % (len(str(max)), ' ' * padding)
1861 return basepcfmtstr % (len(str(max)), ' ' * padding)
1862
1862
1863 def pcfmt(value, total):
1863 def pcfmt(value, total):
1864 if total:
1864 if total:
1865 return (value, 100 * float(value) / total)
1865 return (value, 100 * float(value) / total)
1866 else:
1866 else:
1867 return value, 100.0
1867 return value, 100.0
1868
1868
1869 ui.write(('format : %d\n') % format)
1869 ui.write(('format : %d\n') % format)
1870 ui.write(('flags : %s\n') % ', '.join(flags))
1870 ui.write(('flags : %s\n') % ', '.join(flags))
1871
1871
1872 ui.write('\n')
1872 ui.write('\n')
1873 fmt = pcfmtstr(totalsize)
1873 fmt = pcfmtstr(totalsize)
1874 fmt2 = dfmtstr(totalsize)
1874 fmt2 = dfmtstr(totalsize)
1875 ui.write(('revisions : ') + fmt2 % numrevs)
1875 ui.write(('revisions : ') + fmt2 % numrevs)
1876 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
1876 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
1877 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
1877 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
1878 ui.write(('revisions : ') + fmt2 % numrevs)
1878 ui.write(('revisions : ') + fmt2 % numrevs)
1879 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
1879 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
1880 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
1880 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
1881 ui.write(('revision size : ') + fmt2 % totalsize)
1881 ui.write(('revision size : ') + fmt2 % totalsize)
1882 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
1882 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
1883 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
1883 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
1884
1884
1885 def fmtchunktype(chunktype):
1885 def fmtchunktype(chunktype):
1886 if chunktype == 'empty':
1886 if chunktype == 'empty':
1887 return ' %s : ' % chunktype
1887 return ' %s : ' % chunktype
1888 elif chunktype in pycompat.bytestr(string.ascii_letters):
1888 elif chunktype in pycompat.bytestr(string.ascii_letters):
1889 return ' 0x%s (%s) : ' % (hex(chunktype), chunktype)
1889 return ' 0x%s (%s) : ' % (hex(chunktype), chunktype)
1890 else:
1890 else:
1891 return ' 0x%s : ' % hex(chunktype)
1891 return ' 0x%s : ' % hex(chunktype)
1892
1892
1893 ui.write('\n')
1893 ui.write('\n')
1894 ui.write(('chunks : ') + fmt2 % numrevs)
1894 ui.write(('chunks : ') + fmt2 % numrevs)
1895 for chunktype in sorted(chunktypecounts):
1895 for chunktype in sorted(chunktypecounts):
1896 ui.write(fmtchunktype(chunktype))
1896 ui.write(fmtchunktype(chunktype))
1897 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
1897 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
1898 ui.write(('chunks size : ') + fmt2 % totalsize)
1898 ui.write(('chunks size : ') + fmt2 % totalsize)
1899 for chunktype in sorted(chunktypecounts):
1899 for chunktype in sorted(chunktypecounts):
1900 ui.write(fmtchunktype(chunktype))
1900 ui.write(fmtchunktype(chunktype))
1901 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
1901 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
1902
1902
1903 ui.write('\n')
1903 ui.write('\n')
1904 fmt = dfmtstr(max(avgchainlen, maxchainlen, maxchainspan, compratio))
1904 fmt = dfmtstr(max(avgchainlen, maxchainlen, maxchainspan, compratio))
1905 ui.write(('avg chain length : ') + fmt % avgchainlen)
1905 ui.write(('avg chain length : ') + fmt % avgchainlen)
1906 ui.write(('max chain length : ') + fmt % maxchainlen)
1906 ui.write(('max chain length : ') + fmt % maxchainlen)
1907 ui.write(('max chain reach : ') + fmt % maxchainspan)
1907 ui.write(('max chain reach : ') + fmt % maxchainspan)
1908 ui.write(('compression ratio : ') + fmt % compratio)
1908 ui.write(('compression ratio : ') + fmt % compratio)
1909
1909
1910 if format > 0:
1910 if format > 0:
1911 ui.write('\n')
1911 ui.write('\n')
1912 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
1912 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
1913 % tuple(datasize))
1913 % tuple(datasize))
1914 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
1914 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
1915 % tuple(fullsize))
1915 % tuple(fullsize))
1916 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
1916 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
1917 % tuple(deltasize))
1917 % tuple(deltasize))
1918
1918
1919 if numdeltas > 0:
1919 if numdeltas > 0:
1920 ui.write('\n')
1920 ui.write('\n')
1921 fmt = pcfmtstr(numdeltas)
1921 fmt = pcfmtstr(numdeltas)
1922 fmt2 = pcfmtstr(numdeltas, 4)
1922 fmt2 = pcfmtstr(numdeltas, 4)
1923 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
1923 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
1924 if numprev > 0:
1924 if numprev > 0:
1925 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
1925 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
1926 numprev))
1926 numprev))
1927 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
1927 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
1928 numprev))
1928 numprev))
1929 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
1929 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
1930 numprev))
1930 numprev))
1931 if gdelta:
1931 if gdelta:
1932 ui.write(('deltas against p1 : ')
1932 ui.write(('deltas against p1 : ')
1933 + fmt % pcfmt(nump1, numdeltas))
1933 + fmt % pcfmt(nump1, numdeltas))
1934 ui.write(('deltas against p2 : ')
1934 ui.write(('deltas against p2 : ')
1935 + fmt % pcfmt(nump2, numdeltas))
1935 + fmt % pcfmt(nump2, numdeltas))
1936 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
1936 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
1937 numdeltas))
1937 numdeltas))
1938
1938
1939 @command('debugrevspec',
1939 @command('debugrevspec',
1940 [('', 'optimize', None,
1940 [('', 'optimize', None,
1941 _('print parsed tree after optimizing (DEPRECATED)')),
1941 _('print parsed tree after optimizing (DEPRECATED)')),
1942 ('', 'show-revs', True, _('print list of result revisions (default)')),
1942 ('', 'show-revs', True, _('print list of result revisions (default)')),
1943 ('s', 'show-set', None, _('print internal representation of result set')),
1943 ('s', 'show-set', None, _('print internal representation of result set')),
1944 ('p', 'show-stage', [],
1944 ('p', 'show-stage', [],
1945 _('print parsed tree at the given stage'), _('NAME')),
1945 _('print parsed tree at the given stage'), _('NAME')),
1946 ('', 'no-optimized', False, _('evaluate tree without optimization')),
1946 ('', 'no-optimized', False, _('evaluate tree without optimization')),
1947 ('', 'verify-optimized', False, _('verify optimized result')),
1947 ('', 'verify-optimized', False, _('verify optimized result')),
1948 ],
1948 ],
1949 ('REVSPEC'))
1949 ('REVSPEC'))
1950 def debugrevspec(ui, repo, expr, **opts):
1950 def debugrevspec(ui, repo, expr, **opts):
1951 """parse and apply a revision specification
1951 """parse and apply a revision specification
1952
1952
1953 Use -p/--show-stage option to print the parsed tree at the given stages.
1953 Use -p/--show-stage option to print the parsed tree at the given stages.
1954 Use -p all to print tree at every stage.
1954 Use -p all to print tree at every stage.
1955
1955
1956 Use --no-show-revs option with -s or -p to print only the set
1956 Use --no-show-revs option with -s or -p to print only the set
1957 representation or the parsed tree respectively.
1957 representation or the parsed tree respectively.
1958
1958
1959 Use --verify-optimized to compare the optimized result with the unoptimized
1959 Use --verify-optimized to compare the optimized result with the unoptimized
1960 one. Returns 1 if the optimized result differs.
1960 one. Returns 1 if the optimized result differs.
1961 """
1961 """
1962 opts = pycompat.byteskwargs(opts)
1962 opts = pycompat.byteskwargs(opts)
1963 aliases = ui.configitems('revsetalias')
1963 stages = [
1964 stages = [
1964 ('parsed', lambda tree: tree),
1965 ('parsed', lambda tree: tree),
1965 ('expanded', lambda tree: revsetlang.expandaliases(ui, tree)),
1966 ('expanded', lambda tree: revsetlang.expandaliases(tree, aliases,
1967 ui.warn)),
1966 ('concatenated', revsetlang.foldconcat),
1968 ('concatenated', revsetlang.foldconcat),
1967 ('analyzed', revsetlang.analyze),
1969 ('analyzed', revsetlang.analyze),
1968 ('optimized', revsetlang.optimize),
1970 ('optimized', revsetlang.optimize),
1969 ]
1971 ]
1970 if opts['no_optimized']:
1972 if opts['no_optimized']:
1971 stages = stages[:-1]
1973 stages = stages[:-1]
1972 if opts['verify_optimized'] and opts['no_optimized']:
1974 if opts['verify_optimized'] and opts['no_optimized']:
1973 raise error.Abort(_('cannot use --verify-optimized with '
1975 raise error.Abort(_('cannot use --verify-optimized with '
1974 '--no-optimized'))
1976 '--no-optimized'))
1975 stagenames = set(n for n, f in stages)
1977 stagenames = set(n for n, f in stages)
1976
1978
1977 showalways = set()
1979 showalways = set()
1978 showchanged = set()
1980 showchanged = set()
1979 if ui.verbose and not opts['show_stage']:
1981 if ui.verbose and not opts['show_stage']:
1980 # show parsed tree by --verbose (deprecated)
1982 # show parsed tree by --verbose (deprecated)
1981 showalways.add('parsed')
1983 showalways.add('parsed')
1982 showchanged.update(['expanded', 'concatenated'])
1984 showchanged.update(['expanded', 'concatenated'])
1983 if opts['optimize']:
1985 if opts['optimize']:
1984 showalways.add('optimized')
1986 showalways.add('optimized')
1985 if opts['show_stage'] and opts['optimize']:
1987 if opts['show_stage'] and opts['optimize']:
1986 raise error.Abort(_('cannot use --optimize with --show-stage'))
1988 raise error.Abort(_('cannot use --optimize with --show-stage'))
1987 if opts['show_stage'] == ['all']:
1989 if opts['show_stage'] == ['all']:
1988 showalways.update(stagenames)
1990 showalways.update(stagenames)
1989 else:
1991 else:
1990 for n in opts['show_stage']:
1992 for n in opts['show_stage']:
1991 if n not in stagenames:
1993 if n not in stagenames:
1992 raise error.Abort(_('invalid stage name: %s') % n)
1994 raise error.Abort(_('invalid stage name: %s') % n)
1993 showalways.update(opts['show_stage'])
1995 showalways.update(opts['show_stage'])
1994
1996
1995 treebystage = {}
1997 treebystage = {}
1996 printedtree = None
1998 printedtree = None
1997 tree = revsetlang.parse(expr, lookup=repo.__contains__)
1999 tree = revsetlang.parse(expr, lookup=repo.__contains__)
1998 for n, f in stages:
2000 for n, f in stages:
1999 treebystage[n] = tree = f(tree)
2001 treebystage[n] = tree = f(tree)
2000 if n in showalways or (n in showchanged and tree != printedtree):
2002 if n in showalways or (n in showchanged and tree != printedtree):
2001 if opts['show_stage'] or n != 'parsed':
2003 if opts['show_stage'] or n != 'parsed':
2002 ui.write(("* %s:\n") % n)
2004 ui.write(("* %s:\n") % n)
2003 ui.write(revsetlang.prettyformat(tree), "\n")
2005 ui.write(revsetlang.prettyformat(tree), "\n")
2004 printedtree = tree
2006 printedtree = tree
2005
2007
2006 if opts['verify_optimized']:
2008 if opts['verify_optimized']:
2007 arevs = revset.makematcher(treebystage['analyzed'])(repo)
2009 arevs = revset.makematcher(treebystage['analyzed'])(repo)
2008 brevs = revset.makematcher(treebystage['optimized'])(repo)
2010 brevs = revset.makematcher(treebystage['optimized'])(repo)
2009 if opts['show_set'] or (opts['show_set'] is None and ui.verbose):
2011 if opts['show_set'] or (opts['show_set'] is None and ui.verbose):
2010 ui.write(("* analyzed set:\n"), smartset.prettyformat(arevs), "\n")
2012 ui.write(("* analyzed set:\n"), smartset.prettyformat(arevs), "\n")
2011 ui.write(("* optimized set:\n"), smartset.prettyformat(brevs), "\n")
2013 ui.write(("* optimized set:\n"), smartset.prettyformat(brevs), "\n")
2012 arevs = list(arevs)
2014 arevs = list(arevs)
2013 brevs = list(brevs)
2015 brevs = list(brevs)
2014 if arevs == brevs:
2016 if arevs == brevs:
2015 return 0
2017 return 0
2016 ui.write(('--- analyzed\n'), label='diff.file_a')
2018 ui.write(('--- analyzed\n'), label='diff.file_a')
2017 ui.write(('+++ optimized\n'), label='diff.file_b')
2019 ui.write(('+++ optimized\n'), label='diff.file_b')
2018 sm = difflib.SequenceMatcher(None, arevs, brevs)
2020 sm = difflib.SequenceMatcher(None, arevs, brevs)
2019 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2021 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2020 if tag in ('delete', 'replace'):
2022 if tag in ('delete', 'replace'):
2021 for c in arevs[alo:ahi]:
2023 for c in arevs[alo:ahi]:
2022 ui.write('-%s\n' % c, label='diff.deleted')
2024 ui.write('-%s\n' % c, label='diff.deleted')
2023 if tag in ('insert', 'replace'):
2025 if tag in ('insert', 'replace'):
2024 for c in brevs[blo:bhi]:
2026 for c in brevs[blo:bhi]:
2025 ui.write('+%s\n' % c, label='diff.inserted')
2027 ui.write('+%s\n' % c, label='diff.inserted')
2026 if tag == 'equal':
2028 if tag == 'equal':
2027 for c in arevs[alo:ahi]:
2029 for c in arevs[alo:ahi]:
2028 ui.write(' %s\n' % c)
2030 ui.write(' %s\n' % c)
2029 return 1
2031 return 1
2030
2032
2031 func = revset.makematcher(tree)
2033 func = revset.makematcher(tree)
2032 revs = func(repo)
2034 revs = func(repo)
2033 if opts['show_set'] or (opts['show_set'] is None and ui.verbose):
2035 if opts['show_set'] or (opts['show_set'] is None and ui.verbose):
2034 ui.write(("* set:\n"), smartset.prettyformat(revs), "\n")
2036 ui.write(("* set:\n"), smartset.prettyformat(revs), "\n")
2035 if not opts['show_revs']:
2037 if not opts['show_revs']:
2036 return
2038 return
2037 for c in revs:
2039 for c in revs:
2038 ui.write("%s\n" % c)
2040 ui.write("%s\n" % c)
2039
2041
2040 @command('debugsetparents', [], _('REV1 [REV2]'))
2042 @command('debugsetparents', [], _('REV1 [REV2]'))
2041 def debugsetparents(ui, repo, rev1, rev2=None):
2043 def debugsetparents(ui, repo, rev1, rev2=None):
2042 """manually set the parents of the current working directory
2044 """manually set the parents of the current working directory
2043
2045
2044 This is useful for writing repository conversion tools, but should
2046 This is useful for writing repository conversion tools, but should
2045 be used with care. For example, neither the working directory nor the
2047 be used with care. For example, neither the working directory nor the
2046 dirstate is updated, so file status may be incorrect after running this
2048 dirstate is updated, so file status may be incorrect after running this
2047 command.
2049 command.
2048
2050
2049 Returns 0 on success.
2051 Returns 0 on success.
2050 """
2052 """
2051
2053
2052 r1 = scmutil.revsingle(repo, rev1).node()
2054 r1 = scmutil.revsingle(repo, rev1).node()
2053 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2055 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2054
2056
2055 with repo.wlock():
2057 with repo.wlock():
2056 repo.setparents(r1, r2)
2058 repo.setparents(r1, r2)
2057
2059
2058 @command('debugsub',
2060 @command('debugsub',
2059 [('r', 'rev', '',
2061 [('r', 'rev', '',
2060 _('revision to check'), _('REV'))],
2062 _('revision to check'), _('REV'))],
2061 _('[-r REV] [REV]'))
2063 _('[-r REV] [REV]'))
2062 def debugsub(ui, repo, rev=None):
2064 def debugsub(ui, repo, rev=None):
2063 ctx = scmutil.revsingle(repo, rev, None)
2065 ctx = scmutil.revsingle(repo, rev, None)
2064 for k, v in sorted(ctx.substate.items()):
2066 for k, v in sorted(ctx.substate.items()):
2065 ui.write(('path %s\n') % k)
2067 ui.write(('path %s\n') % k)
2066 ui.write((' source %s\n') % v[0])
2068 ui.write((' source %s\n') % v[0])
2067 ui.write((' revision %s\n') % v[1])
2069 ui.write((' revision %s\n') % v[1])
2068
2070
2069 @command('debugsuccessorssets',
2071 @command('debugsuccessorssets',
2070 [('', 'closest', False, _('return closest successors sets only'))],
2072 [('', 'closest', False, _('return closest successors sets only'))],
2071 _('[REV]'))
2073 _('[REV]'))
2072 def debugsuccessorssets(ui, repo, *revs, **opts):
2074 def debugsuccessorssets(ui, repo, *revs, **opts):
2073 """show set of successors for revision
2075 """show set of successors for revision
2074
2076
2075 A successors set of changeset A is a consistent group of revisions that
2077 A successors set of changeset A is a consistent group of revisions that
2076 succeed A. It contains non-obsolete changesets only unless closests
2078 succeed A. It contains non-obsolete changesets only unless closests
2077 successors set is set.
2079 successors set is set.
2078
2080
2079 In most cases a changeset A has a single successors set containing a single
2081 In most cases a changeset A has a single successors set containing a single
2080 successor (changeset A replaced by A').
2082 successor (changeset A replaced by A').
2081
2083
2082 A changeset that is made obsolete with no successors are called "pruned".
2084 A changeset that is made obsolete with no successors are called "pruned".
2083 Such changesets have no successors sets at all.
2085 Such changesets have no successors sets at all.
2084
2086
2085 A changeset that has been "split" will have a successors set containing
2087 A changeset that has been "split" will have a successors set containing
2086 more than one successor.
2088 more than one successor.
2087
2089
2088 A changeset that has been rewritten in multiple different ways is called
2090 A changeset that has been rewritten in multiple different ways is called
2089 "divergent". Such changesets have multiple successor sets (each of which
2091 "divergent". Such changesets have multiple successor sets (each of which
2090 may also be split, i.e. have multiple successors).
2092 may also be split, i.e. have multiple successors).
2091
2093
2092 Results are displayed as follows::
2094 Results are displayed as follows::
2093
2095
2094 <rev1>
2096 <rev1>
2095 <successors-1A>
2097 <successors-1A>
2096 <rev2>
2098 <rev2>
2097 <successors-2A>
2099 <successors-2A>
2098 <successors-2B1> <successors-2B2> <successors-2B3>
2100 <successors-2B1> <successors-2B2> <successors-2B3>
2099
2101
2100 Here rev2 has two possible (i.e. divergent) successors sets. The first
2102 Here rev2 has two possible (i.e. divergent) successors sets. The first
2101 holds one element, whereas the second holds three (i.e. the changeset has
2103 holds one element, whereas the second holds three (i.e. the changeset has
2102 been split).
2104 been split).
2103 """
2105 """
2104 # passed to successorssets caching computation from one call to another
2106 # passed to successorssets caching computation from one call to another
2105 cache = {}
2107 cache = {}
2106 ctx2str = str
2108 ctx2str = str
2107 node2str = short
2109 node2str = short
2108 if ui.debug():
2110 if ui.debug():
2109 def ctx2str(ctx):
2111 def ctx2str(ctx):
2110 return ctx.hex()
2112 return ctx.hex()
2111 node2str = hex
2113 node2str = hex
2112 for rev in scmutil.revrange(repo, revs):
2114 for rev in scmutil.revrange(repo, revs):
2113 ctx = repo[rev]
2115 ctx = repo[rev]
2114 ui.write('%s\n'% ctx2str(ctx))
2116 ui.write('%s\n'% ctx2str(ctx))
2115 for succsset in obsutil.successorssets(repo, ctx.node(),
2117 for succsset in obsutil.successorssets(repo, ctx.node(),
2116 closest=opts['closest'],
2118 closest=opts['closest'],
2117 cache=cache):
2119 cache=cache):
2118 if succsset:
2120 if succsset:
2119 ui.write(' ')
2121 ui.write(' ')
2120 ui.write(node2str(succsset[0]))
2122 ui.write(node2str(succsset[0]))
2121 for node in succsset[1:]:
2123 for node in succsset[1:]:
2122 ui.write(' ')
2124 ui.write(' ')
2123 ui.write(node2str(node))
2125 ui.write(node2str(node))
2124 ui.write('\n')
2126 ui.write('\n')
2125
2127
2126 @command('debugtemplate',
2128 @command('debugtemplate',
2127 [('r', 'rev', [], _('apply template on changesets'), _('REV')),
2129 [('r', 'rev', [], _('apply template on changesets'), _('REV')),
2128 ('D', 'define', [], _('define template keyword'), _('KEY=VALUE'))],
2130 ('D', 'define', [], _('define template keyword'), _('KEY=VALUE'))],
2129 _('[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
2131 _('[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
2130 optionalrepo=True)
2132 optionalrepo=True)
2131 def debugtemplate(ui, repo, tmpl, **opts):
2133 def debugtemplate(ui, repo, tmpl, **opts):
2132 """parse and apply a template
2134 """parse and apply a template
2133
2135
2134 If -r/--rev is given, the template is processed as a log template and
2136 If -r/--rev is given, the template is processed as a log template and
2135 applied to the given changesets. Otherwise, it is processed as a generic
2137 applied to the given changesets. Otherwise, it is processed as a generic
2136 template.
2138 template.
2137
2139
2138 Use --verbose to print the parsed tree.
2140 Use --verbose to print the parsed tree.
2139 """
2141 """
2140 revs = None
2142 revs = None
2141 if opts[r'rev']:
2143 if opts[r'rev']:
2142 if repo is None:
2144 if repo is None:
2143 raise error.RepoError(_('there is no Mercurial repository here '
2145 raise error.RepoError(_('there is no Mercurial repository here '
2144 '(.hg not found)'))
2146 '(.hg not found)'))
2145 revs = scmutil.revrange(repo, opts[r'rev'])
2147 revs = scmutil.revrange(repo, opts[r'rev'])
2146
2148
2147 props = {}
2149 props = {}
2148 for d in opts[r'define']:
2150 for d in opts[r'define']:
2149 try:
2151 try:
2150 k, v = (e.strip() for e in d.split('=', 1))
2152 k, v = (e.strip() for e in d.split('=', 1))
2151 if not k or k == 'ui':
2153 if not k or k == 'ui':
2152 raise ValueError
2154 raise ValueError
2153 props[k] = v
2155 props[k] = v
2154 except ValueError:
2156 except ValueError:
2155 raise error.Abort(_('malformed keyword definition: %s') % d)
2157 raise error.Abort(_('malformed keyword definition: %s') % d)
2156
2158
2157 if ui.verbose:
2159 if ui.verbose:
2158 aliases = ui.configitems('templatealias')
2160 aliases = ui.configitems('templatealias')
2159 tree = templater.parse(tmpl)
2161 tree = templater.parse(tmpl)
2160 ui.note(templater.prettyformat(tree), '\n')
2162 ui.note(templater.prettyformat(tree), '\n')
2161 newtree = templater.expandaliases(tree, aliases)
2163 newtree = templater.expandaliases(tree, aliases)
2162 if newtree != tree:
2164 if newtree != tree:
2163 ui.note(("* expanded:\n"), templater.prettyformat(newtree), '\n')
2165 ui.note(("* expanded:\n"), templater.prettyformat(newtree), '\n')
2164
2166
2165 if revs is None:
2167 if revs is None:
2166 t = formatter.maketemplater(ui, tmpl)
2168 t = formatter.maketemplater(ui, tmpl)
2167 props['ui'] = ui
2169 props['ui'] = ui
2168 ui.write(t.render(props))
2170 ui.write(t.render(props))
2169 else:
2171 else:
2170 displayer = cmdutil.makelogtemplater(ui, repo, tmpl)
2172 displayer = cmdutil.makelogtemplater(ui, repo, tmpl)
2171 for r in revs:
2173 for r in revs:
2172 displayer.show(repo[r], **pycompat.strkwargs(props))
2174 displayer.show(repo[r], **pycompat.strkwargs(props))
2173 displayer.close()
2175 displayer.close()
2174
2176
2175 @command('debugupdatecaches', [])
2177 @command('debugupdatecaches', [])
2176 def debugupdatecaches(ui, repo, *pats, **opts):
2178 def debugupdatecaches(ui, repo, *pats, **opts):
2177 """warm all known caches in the repository"""
2179 """warm all known caches in the repository"""
2178 with repo.wlock():
2180 with repo.wlock():
2179 with repo.lock():
2181 with repo.lock():
2180 repo.updatecaches()
2182 repo.updatecaches()
2181
2183
2182 @command('debugupgraderepo', [
2184 @command('debugupgraderepo', [
2183 ('o', 'optimize', [], _('extra optimization to perform'), _('NAME')),
2185 ('o', 'optimize', [], _('extra optimization to perform'), _('NAME')),
2184 ('', 'run', False, _('performs an upgrade')),
2186 ('', 'run', False, _('performs an upgrade')),
2185 ])
2187 ])
2186 def debugupgraderepo(ui, repo, run=False, optimize=None):
2188 def debugupgraderepo(ui, repo, run=False, optimize=None):
2187 """upgrade a repository to use different features
2189 """upgrade a repository to use different features
2188
2190
2189 If no arguments are specified, the repository is evaluated for upgrade
2191 If no arguments are specified, the repository is evaluated for upgrade
2190 and a list of problems and potential optimizations is printed.
2192 and a list of problems and potential optimizations is printed.
2191
2193
2192 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
2194 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
2193 can be influenced via additional arguments. More details will be provided
2195 can be influenced via additional arguments. More details will be provided
2194 by the command output when run without ``--run``.
2196 by the command output when run without ``--run``.
2195
2197
2196 During the upgrade, the repository will be locked and no writes will be
2198 During the upgrade, the repository will be locked and no writes will be
2197 allowed.
2199 allowed.
2198
2200
2199 At the end of the upgrade, the repository may not be readable while new
2201 At the end of the upgrade, the repository may not be readable while new
2200 repository data is swapped in. This window will be as long as it takes to
2202 repository data is swapped in. This window will be as long as it takes to
2201 rename some directories inside the ``.hg`` directory. On most machines, this
2203 rename some directories inside the ``.hg`` directory. On most machines, this
2202 should complete almost instantaneously and the chances of a consumer being
2204 should complete almost instantaneously and the chances of a consumer being
2203 unable to access the repository should be low.
2205 unable to access the repository should be low.
2204 """
2206 """
2205 return upgrade.upgraderepo(ui, repo, run=run, optimize=optimize)
2207 return upgrade.upgraderepo(ui, repo, run=run, optimize=optimize)
2206
2208
2207 @command('debugwalk', cmdutil.walkopts, _('[OPTION]... [FILE]...'),
2209 @command('debugwalk', cmdutil.walkopts, _('[OPTION]... [FILE]...'),
2208 inferrepo=True)
2210 inferrepo=True)
2209 def debugwalk(ui, repo, *pats, **opts):
2211 def debugwalk(ui, repo, *pats, **opts):
2210 """show how files match on given patterns"""
2212 """show how files match on given patterns"""
2211 opts = pycompat.byteskwargs(opts)
2213 opts = pycompat.byteskwargs(opts)
2212 m = scmutil.match(repo[None], pats, opts)
2214 m = scmutil.match(repo[None], pats, opts)
2213 ui.write(('matcher: %r\n' % m))
2215 ui.write(('matcher: %r\n' % m))
2214 items = list(repo[None].walk(m))
2216 items = list(repo[None].walk(m))
2215 if not items:
2217 if not items:
2216 return
2218 return
2217 f = lambda fn: fn
2219 f = lambda fn: fn
2218 if ui.configbool('ui', 'slash') and pycompat.ossep != '/':
2220 if ui.configbool('ui', 'slash') and pycompat.ossep != '/':
2219 f = lambda fn: util.normpath(fn)
2221 f = lambda fn: util.normpath(fn)
2220 fmt = 'f %%-%ds %%-%ds %%s' % (
2222 fmt = 'f %%-%ds %%-%ds %%s' % (
2221 max([len(abs) for abs in items]),
2223 max([len(abs) for abs in items]),
2222 max([len(m.rel(abs)) for abs in items]))
2224 max([len(m.rel(abs)) for abs in items]))
2223 for abs in items:
2225 for abs in items:
2224 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2226 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2225 ui.write("%s\n" % line.rstrip())
2227 ui.write("%s\n" % line.rstrip())
2226
2228
2227 @command('debugwireargs',
2229 @command('debugwireargs',
2228 [('', 'three', '', 'three'),
2230 [('', 'three', '', 'three'),
2229 ('', 'four', '', 'four'),
2231 ('', 'four', '', 'four'),
2230 ('', 'five', '', 'five'),
2232 ('', 'five', '', 'five'),
2231 ] + cmdutil.remoteopts,
2233 ] + cmdutil.remoteopts,
2232 _('REPO [OPTIONS]... [ONE [TWO]]'),
2234 _('REPO [OPTIONS]... [ONE [TWO]]'),
2233 norepo=True)
2235 norepo=True)
2234 def debugwireargs(ui, repopath, *vals, **opts):
2236 def debugwireargs(ui, repopath, *vals, **opts):
2235 opts = pycompat.byteskwargs(opts)
2237 opts = pycompat.byteskwargs(opts)
2236 repo = hg.peer(ui, opts, repopath)
2238 repo = hg.peer(ui, opts, repopath)
2237 for opt in cmdutil.remoteopts:
2239 for opt in cmdutil.remoteopts:
2238 del opts[opt[1]]
2240 del opts[opt[1]]
2239 args = {}
2241 args = {}
2240 for k, v in opts.iteritems():
2242 for k, v in opts.iteritems():
2241 if v:
2243 if v:
2242 args[k] = v
2244 args[k] = v
2243 # run twice to check that we don't mess up the stream for the next command
2245 # run twice to check that we don't mess up the stream for the next command
2244 res1 = repo.debugwireargs(*vals, **args)
2246 res1 = repo.debugwireargs(*vals, **args)
2245 res2 = repo.debugwireargs(*vals, **args)
2247 res2 = repo.debugwireargs(*vals, **args)
2246 ui.write("%s\n" % res1)
2248 ui.write("%s\n" % res1)
2247 if res1 != res2:
2249 if res1 != res2:
2248 ui.warn("%s\n" % res2)
2250 ui.warn("%s\n" % res2)
@@ -1,2137 +1,2140 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import inspect
12 import inspect
13 import os
13 import os
14 import random
14 import random
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 hex,
20 hex,
21 nullid,
21 nullid,
22 short,
22 short,
23 )
23 )
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 branchmap,
26 branchmap,
27 bundle2,
27 bundle2,
28 changegroup,
28 changegroup,
29 changelog,
29 changelog,
30 color,
30 color,
31 context,
31 context,
32 dirstate,
32 dirstate,
33 dirstateguard,
33 dirstateguard,
34 encoding,
34 encoding,
35 error,
35 error,
36 exchange,
36 exchange,
37 extensions,
37 extensions,
38 filelog,
38 filelog,
39 hook,
39 hook,
40 lock as lockmod,
40 lock as lockmod,
41 manifest,
41 manifest,
42 match as matchmod,
42 match as matchmod,
43 merge as mergemod,
43 merge as mergemod,
44 mergeutil,
44 mergeutil,
45 namespaces,
45 namespaces,
46 obsolete,
46 obsolete,
47 pathutil,
47 pathutil,
48 peer,
48 peer,
49 phases,
49 phases,
50 pushkey,
50 pushkey,
51 pycompat,
51 pycompat,
52 repoview,
52 repoview,
53 revset,
53 revset,
54 revsetlang,
54 revsetlang,
55 scmutil,
55 scmutil,
56 store,
56 store,
57 subrepo,
57 subrepo,
58 tags as tagsmod,
58 tags as tagsmod,
59 transaction,
59 transaction,
60 txnutil,
60 txnutil,
61 util,
61 util,
62 vfs as vfsmod,
62 vfs as vfsmod,
63 )
63 )
64
64
65 release = lockmod.release
65 release = lockmod.release
66 urlerr = util.urlerr
66 urlerr = util.urlerr
67 urlreq = util.urlreq
67 urlreq = util.urlreq
68
68
69 # set of (path, vfs-location) tuples. vfs-location is:
69 # set of (path, vfs-location) tuples. vfs-location is:
70 # - 'plain for vfs relative paths
70 # - 'plain for vfs relative paths
71 # - '' for svfs relative paths
71 # - '' for svfs relative paths
72 _cachedfiles = set()
72 _cachedfiles = set()
73
73
74 class _basefilecache(scmutil.filecache):
74 class _basefilecache(scmutil.filecache):
75 """All filecache usage on repo are done for logic that should be unfiltered
75 """All filecache usage on repo are done for logic that should be unfiltered
76 """
76 """
77 def __get__(self, repo, type=None):
77 def __get__(self, repo, type=None):
78 if repo is None:
78 if repo is None:
79 return self
79 return self
80 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
80 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
81 def __set__(self, repo, value):
81 def __set__(self, repo, value):
82 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
82 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
83 def __delete__(self, repo):
83 def __delete__(self, repo):
84 return super(_basefilecache, self).__delete__(repo.unfiltered())
84 return super(_basefilecache, self).__delete__(repo.unfiltered())
85
85
86 class repofilecache(_basefilecache):
86 class repofilecache(_basefilecache):
87 """filecache for files in .hg but outside of .hg/store"""
87 """filecache for files in .hg but outside of .hg/store"""
88 def __init__(self, *paths):
88 def __init__(self, *paths):
89 super(repofilecache, self).__init__(*paths)
89 super(repofilecache, self).__init__(*paths)
90 for path in paths:
90 for path in paths:
91 _cachedfiles.add((path, 'plain'))
91 _cachedfiles.add((path, 'plain'))
92
92
93 def join(self, obj, fname):
93 def join(self, obj, fname):
94 return obj.vfs.join(fname)
94 return obj.vfs.join(fname)
95
95
96 class storecache(_basefilecache):
96 class storecache(_basefilecache):
97 """filecache for files in the store"""
97 """filecache for files in the store"""
98 def __init__(self, *paths):
98 def __init__(self, *paths):
99 super(storecache, self).__init__(*paths)
99 super(storecache, self).__init__(*paths)
100 for path in paths:
100 for path in paths:
101 _cachedfiles.add((path, ''))
101 _cachedfiles.add((path, ''))
102
102
103 def join(self, obj, fname):
103 def join(self, obj, fname):
104 return obj.sjoin(fname)
104 return obj.sjoin(fname)
105
105
106 class unfilteredpropertycache(util.propertycache):
106 class unfilteredpropertycache(util.propertycache):
107 """propertycache that apply to unfiltered repo only"""
107 """propertycache that apply to unfiltered repo only"""
108
108
109 def __get__(self, repo, type=None):
109 def __get__(self, repo, type=None):
110 unfi = repo.unfiltered()
110 unfi = repo.unfiltered()
111 if unfi is repo:
111 if unfi is repo:
112 return super(unfilteredpropertycache, self).__get__(unfi)
112 return super(unfilteredpropertycache, self).__get__(unfi)
113 return getattr(unfi, self.name)
113 return getattr(unfi, self.name)
114
114
115 class filteredpropertycache(util.propertycache):
115 class filteredpropertycache(util.propertycache):
116 """propertycache that must take filtering in account"""
116 """propertycache that must take filtering in account"""
117
117
118 def cachevalue(self, obj, value):
118 def cachevalue(self, obj, value):
119 object.__setattr__(obj, self.name, value)
119 object.__setattr__(obj, self.name, value)
120
120
121
121
122 def hasunfilteredcache(repo, name):
122 def hasunfilteredcache(repo, name):
123 """check if a repo has an unfilteredpropertycache value for <name>"""
123 """check if a repo has an unfilteredpropertycache value for <name>"""
124 return name in vars(repo.unfiltered())
124 return name in vars(repo.unfiltered())
125
125
126 def unfilteredmethod(orig):
126 def unfilteredmethod(orig):
127 """decorate method that always need to be run on unfiltered version"""
127 """decorate method that always need to be run on unfiltered version"""
128 def wrapper(repo, *args, **kwargs):
128 def wrapper(repo, *args, **kwargs):
129 return orig(repo.unfiltered(), *args, **kwargs)
129 return orig(repo.unfiltered(), *args, **kwargs)
130 return wrapper
130 return wrapper
131
131
132 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
132 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
133 'unbundle'}
133 'unbundle'}
134 legacycaps = moderncaps.union({'changegroupsubset'})
134 legacycaps = moderncaps.union({'changegroupsubset'})
135
135
136 class localpeer(peer.peerrepository):
136 class localpeer(peer.peerrepository):
137 '''peer for a local repo; reflects only the most recent API'''
137 '''peer for a local repo; reflects only the most recent API'''
138
138
139 def __init__(self, repo, caps=None):
139 def __init__(self, repo, caps=None):
140 if caps is None:
140 if caps is None:
141 caps = moderncaps.copy()
141 caps = moderncaps.copy()
142 peer.peerrepository.__init__(self)
142 peer.peerrepository.__init__(self)
143 self._repo = repo.filtered('served')
143 self._repo = repo.filtered('served')
144 self.ui = repo.ui
144 self.ui = repo.ui
145 self._caps = repo._restrictcapabilities(caps)
145 self._caps = repo._restrictcapabilities(caps)
146 self.requirements = repo.requirements
146 self.requirements = repo.requirements
147 self.supportedformats = repo.supportedformats
147 self.supportedformats = repo.supportedformats
148
148
149 def close(self):
149 def close(self):
150 self._repo.close()
150 self._repo.close()
151
151
152 def _capabilities(self):
152 def _capabilities(self):
153 return self._caps
153 return self._caps
154
154
155 def local(self):
155 def local(self):
156 return self._repo
156 return self._repo
157
157
158 def canpush(self):
158 def canpush(self):
159 return True
159 return True
160
160
161 def url(self):
161 def url(self):
162 return self._repo.url()
162 return self._repo.url()
163
163
164 def lookup(self, key):
164 def lookup(self, key):
165 return self._repo.lookup(key)
165 return self._repo.lookup(key)
166
166
167 def branchmap(self):
167 def branchmap(self):
168 return self._repo.branchmap()
168 return self._repo.branchmap()
169
169
170 def heads(self):
170 def heads(self):
171 return self._repo.heads()
171 return self._repo.heads()
172
172
173 def known(self, nodes):
173 def known(self, nodes):
174 return self._repo.known(nodes)
174 return self._repo.known(nodes)
175
175
176 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
176 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
177 **kwargs):
177 **kwargs):
178 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
178 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
179 common=common, bundlecaps=bundlecaps,
179 common=common, bundlecaps=bundlecaps,
180 **kwargs)
180 **kwargs)
181 cb = util.chunkbuffer(chunks)
181 cb = util.chunkbuffer(chunks)
182
182
183 if exchange.bundle2requested(bundlecaps):
183 if exchange.bundle2requested(bundlecaps):
184 # When requesting a bundle2, getbundle returns a stream to make the
184 # When requesting a bundle2, getbundle returns a stream to make the
185 # wire level function happier. We need to build a proper object
185 # wire level function happier. We need to build a proper object
186 # from it in local peer.
186 # from it in local peer.
187 return bundle2.getunbundler(self.ui, cb)
187 return bundle2.getunbundler(self.ui, cb)
188 else:
188 else:
189 return changegroup.getunbundler('01', cb, None)
189 return changegroup.getunbundler('01', cb, None)
190
190
191 # TODO We might want to move the next two calls into legacypeer and add
191 # TODO We might want to move the next two calls into legacypeer and add
192 # unbundle instead.
192 # unbundle instead.
193
193
194 def unbundle(self, cg, heads, url):
194 def unbundle(self, cg, heads, url):
195 """apply a bundle on a repo
195 """apply a bundle on a repo
196
196
197 This function handles the repo locking itself."""
197 This function handles the repo locking itself."""
198 try:
198 try:
199 try:
199 try:
200 cg = exchange.readbundle(self.ui, cg, None)
200 cg = exchange.readbundle(self.ui, cg, None)
201 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
201 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
202 if util.safehasattr(ret, 'getchunks'):
202 if util.safehasattr(ret, 'getchunks'):
203 # This is a bundle20 object, turn it into an unbundler.
203 # This is a bundle20 object, turn it into an unbundler.
204 # This little dance should be dropped eventually when the
204 # This little dance should be dropped eventually when the
205 # API is finally improved.
205 # API is finally improved.
206 stream = util.chunkbuffer(ret.getchunks())
206 stream = util.chunkbuffer(ret.getchunks())
207 ret = bundle2.getunbundler(self.ui, stream)
207 ret = bundle2.getunbundler(self.ui, stream)
208 return ret
208 return ret
209 except Exception as exc:
209 except Exception as exc:
210 # If the exception contains output salvaged from a bundle2
210 # If the exception contains output salvaged from a bundle2
211 # reply, we need to make sure it is printed before continuing
211 # reply, we need to make sure it is printed before continuing
212 # to fail. So we build a bundle2 with such output and consume
212 # to fail. So we build a bundle2 with such output and consume
213 # it directly.
213 # it directly.
214 #
214 #
215 # This is not very elegant but allows a "simple" solution for
215 # This is not very elegant but allows a "simple" solution for
216 # issue4594
216 # issue4594
217 output = getattr(exc, '_bundle2salvagedoutput', ())
217 output = getattr(exc, '_bundle2salvagedoutput', ())
218 if output:
218 if output:
219 bundler = bundle2.bundle20(self._repo.ui)
219 bundler = bundle2.bundle20(self._repo.ui)
220 for out in output:
220 for out in output:
221 bundler.addpart(out)
221 bundler.addpart(out)
222 stream = util.chunkbuffer(bundler.getchunks())
222 stream = util.chunkbuffer(bundler.getchunks())
223 b = bundle2.getunbundler(self.ui, stream)
223 b = bundle2.getunbundler(self.ui, stream)
224 bundle2.processbundle(self._repo, b)
224 bundle2.processbundle(self._repo, b)
225 raise
225 raise
226 except error.PushRaced as exc:
226 except error.PushRaced as exc:
227 raise error.ResponseError(_('push failed:'), str(exc))
227 raise error.ResponseError(_('push failed:'), str(exc))
228
228
229 def lock(self):
229 def lock(self):
230 return self._repo.lock()
230 return self._repo.lock()
231
231
232 def pushkey(self, namespace, key, old, new):
232 def pushkey(self, namespace, key, old, new):
233 return self._repo.pushkey(namespace, key, old, new)
233 return self._repo.pushkey(namespace, key, old, new)
234
234
235 def listkeys(self, namespace):
235 def listkeys(self, namespace):
236 return self._repo.listkeys(namespace)
236 return self._repo.listkeys(namespace)
237
237
238 def debugwireargs(self, one, two, three=None, four=None, five=None):
238 def debugwireargs(self, one, two, three=None, four=None, five=None):
239 '''used to test argument passing over the wire'''
239 '''used to test argument passing over the wire'''
240 return "%s %s %s %s %s" % (one, two, three, four, five)
240 return "%s %s %s %s %s" % (one, two, three, four, five)
241
241
242 class locallegacypeer(localpeer):
242 class locallegacypeer(localpeer):
243 '''peer extension which implements legacy methods too; used for tests with
243 '''peer extension which implements legacy methods too; used for tests with
244 restricted capabilities'''
244 restricted capabilities'''
245
245
246 def __init__(self, repo):
246 def __init__(self, repo):
247 localpeer.__init__(self, repo, caps=legacycaps)
247 localpeer.__init__(self, repo, caps=legacycaps)
248
248
249 def branches(self, nodes):
249 def branches(self, nodes):
250 return self._repo.branches(nodes)
250 return self._repo.branches(nodes)
251
251
252 def between(self, pairs):
252 def between(self, pairs):
253 return self._repo.between(pairs)
253 return self._repo.between(pairs)
254
254
255 def changegroup(self, basenodes, source):
255 def changegroup(self, basenodes, source):
256 return changegroup.changegroup(self._repo, basenodes, source)
256 return changegroup.changegroup(self._repo, basenodes, source)
257
257
258 def changegroupsubset(self, bases, heads, source):
258 def changegroupsubset(self, bases, heads, source):
259 return changegroup.changegroupsubset(self._repo, bases, heads, source)
259 return changegroup.changegroupsubset(self._repo, bases, heads, source)
260
260
261 # Increment the sub-version when the revlog v2 format changes to lock out old
261 # Increment the sub-version when the revlog v2 format changes to lock out old
262 # clients.
262 # clients.
263 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
263 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
264
264
265 class localrepository(object):
265 class localrepository(object):
266
266
267 supportedformats = {
267 supportedformats = {
268 'revlogv1',
268 'revlogv1',
269 'generaldelta',
269 'generaldelta',
270 'treemanifest',
270 'treemanifest',
271 'manifestv2',
271 'manifestv2',
272 REVLOGV2_REQUIREMENT,
272 REVLOGV2_REQUIREMENT,
273 }
273 }
274 _basesupported = supportedformats | {
274 _basesupported = supportedformats | {
275 'store',
275 'store',
276 'fncache',
276 'fncache',
277 'shared',
277 'shared',
278 'relshared',
278 'relshared',
279 'dotencode',
279 'dotencode',
280 }
280 }
281 openerreqs = {
281 openerreqs = {
282 'revlogv1',
282 'revlogv1',
283 'generaldelta',
283 'generaldelta',
284 'treemanifest',
284 'treemanifest',
285 'manifestv2',
285 'manifestv2',
286 }
286 }
287
287
288 # a list of (ui, featureset) functions.
288 # a list of (ui, featureset) functions.
289 # only functions defined in module of enabled extensions are invoked
289 # only functions defined in module of enabled extensions are invoked
290 featuresetupfuncs = set()
290 featuresetupfuncs = set()
291
291
292 def __init__(self, baseui, path, create=False):
292 def __init__(self, baseui, path, create=False):
293 self.requirements = set()
293 self.requirements = set()
294 self.filtername = None
294 self.filtername = None
295 # wvfs: rooted at the repository root, used to access the working copy
295 # wvfs: rooted at the repository root, used to access the working copy
296 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
296 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
297 # vfs: rooted at .hg, used to access repo files outside of .hg/store
297 # vfs: rooted at .hg, used to access repo files outside of .hg/store
298 self.vfs = None
298 self.vfs = None
299 # svfs: usually rooted at .hg/store, used to access repository history
299 # svfs: usually rooted at .hg/store, used to access repository history
300 # If this is a shared repository, this vfs may point to another
300 # If this is a shared repository, this vfs may point to another
301 # repository's .hg/store directory.
301 # repository's .hg/store directory.
302 self.svfs = None
302 self.svfs = None
303 self.root = self.wvfs.base
303 self.root = self.wvfs.base
304 self.path = self.wvfs.join(".hg")
304 self.path = self.wvfs.join(".hg")
305 self.origroot = path
305 self.origroot = path
306 # These auditor are not used by the vfs,
306 # These auditor are not used by the vfs,
307 # only used when writing this comment: basectx.match
307 # only used when writing this comment: basectx.match
308 self.auditor = pathutil.pathauditor(self.root, self._checknested)
308 self.auditor = pathutil.pathauditor(self.root, self._checknested)
309 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
309 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
310 realfs=False)
310 realfs=False)
311 self.vfs = vfsmod.vfs(self.path)
311 self.vfs = vfsmod.vfs(self.path)
312 self.baseui = baseui
312 self.baseui = baseui
313 self.ui = baseui.copy()
313 self.ui = baseui.copy()
314 self.ui.copy = baseui.copy # prevent copying repo configuration
314 self.ui.copy = baseui.copy # prevent copying repo configuration
315 # A list of callback to shape the phase if no data were found.
315 # A list of callback to shape the phase if no data were found.
316 # Callback are in the form: func(repo, roots) --> processed root.
316 # Callback are in the form: func(repo, roots) --> processed root.
317 # This list it to be filled by extension during repo setup
317 # This list it to be filled by extension during repo setup
318 self._phasedefaults = []
318 self._phasedefaults = []
319 try:
319 try:
320 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
320 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
321 self._loadextensions()
321 self._loadextensions()
322 except IOError:
322 except IOError:
323 pass
323 pass
324
324
325 if self.featuresetupfuncs:
325 if self.featuresetupfuncs:
326 self.supported = set(self._basesupported) # use private copy
326 self.supported = set(self._basesupported) # use private copy
327 extmods = set(m.__name__ for n, m
327 extmods = set(m.__name__ for n, m
328 in extensions.extensions(self.ui))
328 in extensions.extensions(self.ui))
329 for setupfunc in self.featuresetupfuncs:
329 for setupfunc in self.featuresetupfuncs:
330 if setupfunc.__module__ in extmods:
330 if setupfunc.__module__ in extmods:
331 setupfunc(self.ui, self.supported)
331 setupfunc(self.ui, self.supported)
332 else:
332 else:
333 self.supported = self._basesupported
333 self.supported = self._basesupported
334 color.setup(self.ui)
334 color.setup(self.ui)
335
335
336 # Add compression engines.
336 # Add compression engines.
337 for name in util.compengines:
337 for name in util.compengines:
338 engine = util.compengines[name]
338 engine = util.compengines[name]
339 if engine.revlogheader():
339 if engine.revlogheader():
340 self.supported.add('exp-compression-%s' % name)
340 self.supported.add('exp-compression-%s' % name)
341
341
342 if not self.vfs.isdir():
342 if not self.vfs.isdir():
343 if create:
343 if create:
344 self.requirements = newreporequirements(self)
344 self.requirements = newreporequirements(self)
345
345
346 if not self.wvfs.exists():
346 if not self.wvfs.exists():
347 self.wvfs.makedirs()
347 self.wvfs.makedirs()
348 self.vfs.makedir(notindexed=True)
348 self.vfs.makedir(notindexed=True)
349
349
350 if 'store' in self.requirements:
350 if 'store' in self.requirements:
351 self.vfs.mkdir("store")
351 self.vfs.mkdir("store")
352
352
353 # create an invalid changelog
353 # create an invalid changelog
354 self.vfs.append(
354 self.vfs.append(
355 "00changelog.i",
355 "00changelog.i",
356 '\0\0\0\2' # represents revlogv2
356 '\0\0\0\2' # represents revlogv2
357 ' dummy changelog to prevent using the old repo layout'
357 ' dummy changelog to prevent using the old repo layout'
358 )
358 )
359 else:
359 else:
360 raise error.RepoError(_("repository %s not found") % path)
360 raise error.RepoError(_("repository %s not found") % path)
361 elif create:
361 elif create:
362 raise error.RepoError(_("repository %s already exists") % path)
362 raise error.RepoError(_("repository %s already exists") % path)
363 else:
363 else:
364 try:
364 try:
365 self.requirements = scmutil.readrequires(
365 self.requirements = scmutil.readrequires(
366 self.vfs, self.supported)
366 self.vfs, self.supported)
367 except IOError as inst:
367 except IOError as inst:
368 if inst.errno != errno.ENOENT:
368 if inst.errno != errno.ENOENT:
369 raise
369 raise
370
370
371 self.sharedpath = self.path
371 self.sharedpath = self.path
372 try:
372 try:
373 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
373 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
374 if 'relshared' in self.requirements:
374 if 'relshared' in self.requirements:
375 sharedpath = self.vfs.join(sharedpath)
375 sharedpath = self.vfs.join(sharedpath)
376 vfs = vfsmod.vfs(sharedpath, realpath=True)
376 vfs = vfsmod.vfs(sharedpath, realpath=True)
377 s = vfs.base
377 s = vfs.base
378 if not vfs.exists():
378 if not vfs.exists():
379 raise error.RepoError(
379 raise error.RepoError(
380 _('.hg/sharedpath points to nonexistent directory %s') % s)
380 _('.hg/sharedpath points to nonexistent directory %s') % s)
381 self.sharedpath = s
381 self.sharedpath = s
382 except IOError as inst:
382 except IOError as inst:
383 if inst.errno != errno.ENOENT:
383 if inst.errno != errno.ENOENT:
384 raise
384 raise
385
385
386 self.store = store.store(
386 self.store = store.store(
387 self.requirements, self.sharedpath, vfsmod.vfs)
387 self.requirements, self.sharedpath, vfsmod.vfs)
388 self.spath = self.store.path
388 self.spath = self.store.path
389 self.svfs = self.store.vfs
389 self.svfs = self.store.vfs
390 self.sjoin = self.store.join
390 self.sjoin = self.store.join
391 self.vfs.createmode = self.store.createmode
391 self.vfs.createmode = self.store.createmode
392 self._applyopenerreqs()
392 self._applyopenerreqs()
393 if create:
393 if create:
394 self._writerequirements()
394 self._writerequirements()
395
395
396 self._dirstatevalidatewarned = False
396 self._dirstatevalidatewarned = False
397
397
398 self._branchcaches = {}
398 self._branchcaches = {}
399 self._revbranchcache = None
399 self._revbranchcache = None
400 self.filterpats = {}
400 self.filterpats = {}
401 self._datafilters = {}
401 self._datafilters = {}
402 self._transref = self._lockref = self._wlockref = None
402 self._transref = self._lockref = self._wlockref = None
403
403
404 # A cache for various files under .hg/ that tracks file changes,
404 # A cache for various files under .hg/ that tracks file changes,
405 # (used by the filecache decorator)
405 # (used by the filecache decorator)
406 #
406 #
407 # Maps a property name to its util.filecacheentry
407 # Maps a property name to its util.filecacheentry
408 self._filecache = {}
408 self._filecache = {}
409
409
410 # hold sets of revision to be filtered
410 # hold sets of revision to be filtered
411 # should be cleared when something might have changed the filter value:
411 # should be cleared when something might have changed the filter value:
412 # - new changesets,
412 # - new changesets,
413 # - phase change,
413 # - phase change,
414 # - new obsolescence marker,
414 # - new obsolescence marker,
415 # - working directory parent change,
415 # - working directory parent change,
416 # - bookmark changes
416 # - bookmark changes
417 self.filteredrevcache = {}
417 self.filteredrevcache = {}
418
418
419 # post-dirstate-status hooks
419 # post-dirstate-status hooks
420 self._postdsstatus = []
420 self._postdsstatus = []
421
421
422 # generic mapping between names and nodes
422 # generic mapping between names and nodes
423 self.names = namespaces.namespaces()
423 self.names = namespaces.namespaces()
424
424
425 # Key to signature value.
425 # Key to signature value.
426 self._sparsesignaturecache = {}
426 self._sparsesignaturecache = {}
427 # Signature to cached matcher instance.
427 # Signature to cached matcher instance.
428 self._sparsematchercache = {}
428 self._sparsematchercache = {}
429
429
430 def close(self):
430 def close(self):
431 self._writecaches()
431 self._writecaches()
432
432
433 def _loadextensions(self):
433 def _loadextensions(self):
434 extensions.loadall(self.ui)
434 extensions.loadall(self.ui)
435
435
436 def _writecaches(self):
436 def _writecaches(self):
437 if self._revbranchcache:
437 if self._revbranchcache:
438 self._revbranchcache.write()
438 self._revbranchcache.write()
439
439
440 def _restrictcapabilities(self, caps):
440 def _restrictcapabilities(self, caps):
441 if self.ui.configbool('experimental', 'bundle2-advertise', True):
441 if self.ui.configbool('experimental', 'bundle2-advertise', True):
442 caps = set(caps)
442 caps = set(caps)
443 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
443 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
444 caps.add('bundle2=' + urlreq.quote(capsblob))
444 caps.add('bundle2=' + urlreq.quote(capsblob))
445 return caps
445 return caps
446
446
447 def _applyopenerreqs(self):
447 def _applyopenerreqs(self):
448 self.svfs.options = dict((r, 1) for r in self.requirements
448 self.svfs.options = dict((r, 1) for r in self.requirements
449 if r in self.openerreqs)
449 if r in self.openerreqs)
450 # experimental config: format.chunkcachesize
450 # experimental config: format.chunkcachesize
451 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
451 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
452 if chunkcachesize is not None:
452 if chunkcachesize is not None:
453 self.svfs.options['chunkcachesize'] = chunkcachesize
453 self.svfs.options['chunkcachesize'] = chunkcachesize
454 # experimental config: format.maxchainlen
454 # experimental config: format.maxchainlen
455 maxchainlen = self.ui.configint('format', 'maxchainlen')
455 maxchainlen = self.ui.configint('format', 'maxchainlen')
456 if maxchainlen is not None:
456 if maxchainlen is not None:
457 self.svfs.options['maxchainlen'] = maxchainlen
457 self.svfs.options['maxchainlen'] = maxchainlen
458 # experimental config: format.manifestcachesize
458 # experimental config: format.manifestcachesize
459 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
459 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
460 if manifestcachesize is not None:
460 if manifestcachesize is not None:
461 self.svfs.options['manifestcachesize'] = manifestcachesize
461 self.svfs.options['manifestcachesize'] = manifestcachesize
462 # experimental config: format.aggressivemergedeltas
462 # experimental config: format.aggressivemergedeltas
463 aggressivemergedeltas = self.ui.configbool('format',
463 aggressivemergedeltas = self.ui.configbool('format',
464 'aggressivemergedeltas')
464 'aggressivemergedeltas')
465 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
465 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
466 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
466 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
467 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
467 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
468 if 0 <= chainspan:
468 if 0 <= chainspan:
469 self.svfs.options['maxdeltachainspan'] = chainspan
469 self.svfs.options['maxdeltachainspan'] = chainspan
470
470
471 for r in self.requirements:
471 for r in self.requirements:
472 if r.startswith('exp-compression-'):
472 if r.startswith('exp-compression-'):
473 self.svfs.options['compengine'] = r[len('exp-compression-'):]
473 self.svfs.options['compengine'] = r[len('exp-compression-'):]
474
474
475 # TODO move "revlogv2" to openerreqs once finalized.
475 # TODO move "revlogv2" to openerreqs once finalized.
476 if REVLOGV2_REQUIREMENT in self.requirements:
476 if REVLOGV2_REQUIREMENT in self.requirements:
477 self.svfs.options['revlogv2'] = True
477 self.svfs.options['revlogv2'] = True
478
478
479 def _writerequirements(self):
479 def _writerequirements(self):
480 scmutil.writerequires(self.vfs, self.requirements)
480 scmutil.writerequires(self.vfs, self.requirements)
481
481
482 def _checknested(self, path):
482 def _checknested(self, path):
483 """Determine if path is a legal nested repository."""
483 """Determine if path is a legal nested repository."""
484 if not path.startswith(self.root):
484 if not path.startswith(self.root):
485 return False
485 return False
486 subpath = path[len(self.root) + 1:]
486 subpath = path[len(self.root) + 1:]
487 normsubpath = util.pconvert(subpath)
487 normsubpath = util.pconvert(subpath)
488
488
489 # XXX: Checking against the current working copy is wrong in
489 # XXX: Checking against the current working copy is wrong in
490 # the sense that it can reject things like
490 # the sense that it can reject things like
491 #
491 #
492 # $ hg cat -r 10 sub/x.txt
492 # $ hg cat -r 10 sub/x.txt
493 #
493 #
494 # if sub/ is no longer a subrepository in the working copy
494 # if sub/ is no longer a subrepository in the working copy
495 # parent revision.
495 # parent revision.
496 #
496 #
497 # However, it can of course also allow things that would have
497 # However, it can of course also allow things that would have
498 # been rejected before, such as the above cat command if sub/
498 # been rejected before, such as the above cat command if sub/
499 # is a subrepository now, but was a normal directory before.
499 # is a subrepository now, but was a normal directory before.
500 # The old path auditor would have rejected by mistake since it
500 # The old path auditor would have rejected by mistake since it
501 # panics when it sees sub/.hg/.
501 # panics when it sees sub/.hg/.
502 #
502 #
503 # All in all, checking against the working copy seems sensible
503 # All in all, checking against the working copy seems sensible
504 # since we want to prevent access to nested repositories on
504 # since we want to prevent access to nested repositories on
505 # the filesystem *now*.
505 # the filesystem *now*.
506 ctx = self[None]
506 ctx = self[None]
507 parts = util.splitpath(subpath)
507 parts = util.splitpath(subpath)
508 while parts:
508 while parts:
509 prefix = '/'.join(parts)
509 prefix = '/'.join(parts)
510 if prefix in ctx.substate:
510 if prefix in ctx.substate:
511 if prefix == normsubpath:
511 if prefix == normsubpath:
512 return True
512 return True
513 else:
513 else:
514 sub = ctx.sub(prefix)
514 sub = ctx.sub(prefix)
515 return sub.checknested(subpath[len(prefix) + 1:])
515 return sub.checknested(subpath[len(prefix) + 1:])
516 else:
516 else:
517 parts.pop()
517 parts.pop()
518 return False
518 return False
519
519
520 def peer(self):
520 def peer(self):
521 return localpeer(self) # not cached to avoid reference cycle
521 return localpeer(self) # not cached to avoid reference cycle
522
522
523 def unfiltered(self):
523 def unfiltered(self):
524 """Return unfiltered version of the repository
524 """Return unfiltered version of the repository
525
525
526 Intended to be overwritten by filtered repo."""
526 Intended to be overwritten by filtered repo."""
527 return self
527 return self
528
528
529 def filtered(self, name):
529 def filtered(self, name):
530 """Return a filtered version of a repository"""
530 """Return a filtered version of a repository"""
531 # build a new class with the mixin and the current class
531 # build a new class with the mixin and the current class
532 # (possibly subclass of the repo)
532 # (possibly subclass of the repo)
533 class filteredrepo(repoview.repoview, self.unfiltered().__class__):
533 class filteredrepo(repoview.repoview, self.unfiltered().__class__):
534 pass
534 pass
535 return filteredrepo(self, name)
535 return filteredrepo(self, name)
536
536
537 @repofilecache('bookmarks', 'bookmarks.current')
537 @repofilecache('bookmarks', 'bookmarks.current')
538 def _bookmarks(self):
538 def _bookmarks(self):
539 return bookmarks.bmstore(self)
539 return bookmarks.bmstore(self)
540
540
541 @property
541 @property
542 def _activebookmark(self):
542 def _activebookmark(self):
543 return self._bookmarks.active
543 return self._bookmarks.active
544
544
545 # _phaserevs and _phasesets depend on changelog. what we need is to
545 # _phaserevs and _phasesets depend on changelog. what we need is to
546 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
546 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
547 # can't be easily expressed in filecache mechanism.
547 # can't be easily expressed in filecache mechanism.
548 @storecache('phaseroots', '00changelog.i')
548 @storecache('phaseroots', '00changelog.i')
549 def _phasecache(self):
549 def _phasecache(self):
550 return phases.phasecache(self, self._phasedefaults)
550 return phases.phasecache(self, self._phasedefaults)
551
551
552 @storecache('obsstore')
552 @storecache('obsstore')
553 def obsstore(self):
553 def obsstore(self):
554 return obsolete.makestore(self.ui, self)
554 return obsolete.makestore(self.ui, self)
555
555
556 @storecache('00changelog.i')
556 @storecache('00changelog.i')
557 def changelog(self):
557 def changelog(self):
558 return changelog.changelog(self.svfs,
558 return changelog.changelog(self.svfs,
559 trypending=txnutil.mayhavepending(self.root))
559 trypending=txnutil.mayhavepending(self.root))
560
560
561 def _constructmanifest(self):
561 def _constructmanifest(self):
562 # This is a temporary function while we migrate from manifest to
562 # This is a temporary function while we migrate from manifest to
563 # manifestlog. It allows bundlerepo and unionrepo to intercept the
563 # manifestlog. It allows bundlerepo and unionrepo to intercept the
564 # manifest creation.
564 # manifest creation.
565 return manifest.manifestrevlog(self.svfs)
565 return manifest.manifestrevlog(self.svfs)
566
566
567 @storecache('00manifest.i')
567 @storecache('00manifest.i')
568 def manifestlog(self):
568 def manifestlog(self):
569 return manifest.manifestlog(self.svfs, self)
569 return manifest.manifestlog(self.svfs, self)
570
570
571 @repofilecache('dirstate')
571 @repofilecache('dirstate')
572 def dirstate(self):
572 def dirstate(self):
573 return dirstate.dirstate(self.vfs, self.ui, self.root,
573 return dirstate.dirstate(self.vfs, self.ui, self.root,
574 self._dirstatevalidate)
574 self._dirstatevalidate)
575
575
576 def _dirstatevalidate(self, node):
576 def _dirstatevalidate(self, node):
577 try:
577 try:
578 self.changelog.rev(node)
578 self.changelog.rev(node)
579 return node
579 return node
580 except error.LookupError:
580 except error.LookupError:
581 if not self._dirstatevalidatewarned:
581 if not self._dirstatevalidatewarned:
582 self._dirstatevalidatewarned = True
582 self._dirstatevalidatewarned = True
583 self.ui.warn(_("warning: ignoring unknown"
583 self.ui.warn(_("warning: ignoring unknown"
584 " working parent %s!\n") % short(node))
584 " working parent %s!\n") % short(node))
585 return nullid
585 return nullid
586
586
587 def __getitem__(self, changeid):
587 def __getitem__(self, changeid):
588 if changeid is None:
588 if changeid is None:
589 return context.workingctx(self)
589 return context.workingctx(self)
590 if isinstance(changeid, slice):
590 if isinstance(changeid, slice):
591 # wdirrev isn't contiguous so the slice shouldn't include it
591 # wdirrev isn't contiguous so the slice shouldn't include it
592 return [context.changectx(self, i)
592 return [context.changectx(self, i)
593 for i in xrange(*changeid.indices(len(self)))
593 for i in xrange(*changeid.indices(len(self)))
594 if i not in self.changelog.filteredrevs]
594 if i not in self.changelog.filteredrevs]
595 try:
595 try:
596 return context.changectx(self, changeid)
596 return context.changectx(self, changeid)
597 except error.WdirUnsupported:
597 except error.WdirUnsupported:
598 return context.workingctx(self)
598 return context.workingctx(self)
599
599
600 def __contains__(self, changeid):
600 def __contains__(self, changeid):
601 """True if the given changeid exists
601 """True if the given changeid exists
602
602
603 error.LookupError is raised if an ambiguous node specified.
603 error.LookupError is raised if an ambiguous node specified.
604 """
604 """
605 try:
605 try:
606 self[changeid]
606 self[changeid]
607 return True
607 return True
608 except error.RepoLookupError:
608 except error.RepoLookupError:
609 return False
609 return False
610
610
611 def __nonzero__(self):
611 def __nonzero__(self):
612 return True
612 return True
613
613
614 __bool__ = __nonzero__
614 __bool__ = __nonzero__
615
615
616 def __len__(self):
616 def __len__(self):
617 return len(self.changelog)
617 return len(self.changelog)
618
618
619 def __iter__(self):
619 def __iter__(self):
620 return iter(self.changelog)
620 return iter(self.changelog)
621
621
622 def revs(self, expr, *args):
622 def revs(self, expr, *args):
623 '''Find revisions matching a revset.
623 '''Find revisions matching a revset.
624
624
625 The revset is specified as a string ``expr`` that may contain
625 The revset is specified as a string ``expr`` that may contain
626 %-formatting to escape certain types. See ``revsetlang.formatspec``.
626 %-formatting to escape certain types. See ``revsetlang.formatspec``.
627
627
628 Revset aliases from the configuration are not expanded. To expand
628 Revset aliases from the configuration are not expanded. To expand
629 user aliases, consider calling ``scmutil.revrange()`` or
629 user aliases, consider calling ``scmutil.revrange()`` or
630 ``repo.anyrevs([expr], user=True)``.
630 ``repo.anyrevs([expr], user=True)``.
631
631
632 Returns a revset.abstractsmartset, which is a list-like interface
632 Returns a revset.abstractsmartset, which is a list-like interface
633 that contains integer revisions.
633 that contains integer revisions.
634 '''
634 '''
635 expr = revsetlang.formatspec(expr, *args)
635 expr = revsetlang.formatspec(expr, *args)
636 m = revset.match(None, expr)
636 m = revset.match(None, expr)
637 return m(self)
637 return m(self)
638
638
639 def set(self, expr, *args):
639 def set(self, expr, *args):
640 '''Find revisions matching a revset and emit changectx instances.
640 '''Find revisions matching a revset and emit changectx instances.
641
641
642 This is a convenience wrapper around ``revs()`` that iterates the
642 This is a convenience wrapper around ``revs()`` that iterates the
643 result and is a generator of changectx instances.
643 result and is a generator of changectx instances.
644
644
645 Revset aliases from the configuration are not expanded. To expand
645 Revset aliases from the configuration are not expanded. To expand
646 user aliases, consider calling ``scmutil.revrange()``.
646 user aliases, consider calling ``scmutil.revrange()``.
647 '''
647 '''
648 for r in self.revs(expr, *args):
648 for r in self.revs(expr, *args):
649 yield self[r]
649 yield self[r]
650
650
651 def anyrevs(self, specs, user=False):
651 def anyrevs(self, specs, user=False, localalias=None):
652 '''Find revisions matching one of the given revsets.
652 '''Find revisions matching one of the given revsets.
653
653
654 Revset aliases from the configuration are not expanded by default. To
654 Revset aliases from the configuration are not expanded by default. To
655 expand user aliases, specify ``user=True``.
655 expand user aliases, specify ``user=True``. To provide some local
656 definitions overriding user aliases, set ``localalias`` to
657 ``{name: definitionstring}``.
656 '''
658 '''
657 if user:
659 if user:
658 m = revset.matchany(self.ui, specs, repo=self)
660 m = revset.matchany(self.ui, specs, repo=self,
661 localalias=localalias)
659 else:
662 else:
660 m = revset.matchany(None, specs)
663 m = revset.matchany(None, specs, localalias=localalias)
661 return m(self)
664 return m(self)
662
665
663 def url(self):
666 def url(self):
664 return 'file:' + self.root
667 return 'file:' + self.root
665
668
666 def hook(self, name, throw=False, **args):
669 def hook(self, name, throw=False, **args):
667 """Call a hook, passing this repo instance.
670 """Call a hook, passing this repo instance.
668
671
669 This a convenience method to aid invoking hooks. Extensions likely
672 This a convenience method to aid invoking hooks. Extensions likely
670 won't call this unless they have registered a custom hook or are
673 won't call this unless they have registered a custom hook or are
671 replacing code that is expected to call a hook.
674 replacing code that is expected to call a hook.
672 """
675 """
673 return hook.hook(self.ui, self, name, throw, **args)
676 return hook.hook(self.ui, self, name, throw, **args)
674
677
675 @filteredpropertycache
678 @filteredpropertycache
676 def _tagscache(self):
679 def _tagscache(self):
677 '''Returns a tagscache object that contains various tags related
680 '''Returns a tagscache object that contains various tags related
678 caches.'''
681 caches.'''
679
682
680 # This simplifies its cache management by having one decorated
683 # This simplifies its cache management by having one decorated
681 # function (this one) and the rest simply fetch things from it.
684 # function (this one) and the rest simply fetch things from it.
682 class tagscache(object):
685 class tagscache(object):
683 def __init__(self):
686 def __init__(self):
684 # These two define the set of tags for this repository. tags
687 # These two define the set of tags for this repository. tags
685 # maps tag name to node; tagtypes maps tag name to 'global' or
688 # maps tag name to node; tagtypes maps tag name to 'global' or
686 # 'local'. (Global tags are defined by .hgtags across all
689 # 'local'. (Global tags are defined by .hgtags across all
687 # heads, and local tags are defined in .hg/localtags.)
690 # heads, and local tags are defined in .hg/localtags.)
688 # They constitute the in-memory cache of tags.
691 # They constitute the in-memory cache of tags.
689 self.tags = self.tagtypes = None
692 self.tags = self.tagtypes = None
690
693
691 self.nodetagscache = self.tagslist = None
694 self.nodetagscache = self.tagslist = None
692
695
693 cache = tagscache()
696 cache = tagscache()
694 cache.tags, cache.tagtypes = self._findtags()
697 cache.tags, cache.tagtypes = self._findtags()
695
698
696 return cache
699 return cache
697
700
698 def tags(self):
701 def tags(self):
699 '''return a mapping of tag to node'''
702 '''return a mapping of tag to node'''
700 t = {}
703 t = {}
701 if self.changelog.filteredrevs:
704 if self.changelog.filteredrevs:
702 tags, tt = self._findtags()
705 tags, tt = self._findtags()
703 else:
706 else:
704 tags = self._tagscache.tags
707 tags = self._tagscache.tags
705 for k, v in tags.iteritems():
708 for k, v in tags.iteritems():
706 try:
709 try:
707 # ignore tags to unknown nodes
710 # ignore tags to unknown nodes
708 self.changelog.rev(v)
711 self.changelog.rev(v)
709 t[k] = v
712 t[k] = v
710 except (error.LookupError, ValueError):
713 except (error.LookupError, ValueError):
711 pass
714 pass
712 return t
715 return t
713
716
714 def _findtags(self):
717 def _findtags(self):
715 '''Do the hard work of finding tags. Return a pair of dicts
718 '''Do the hard work of finding tags. Return a pair of dicts
716 (tags, tagtypes) where tags maps tag name to node, and tagtypes
719 (tags, tagtypes) where tags maps tag name to node, and tagtypes
717 maps tag name to a string like \'global\' or \'local\'.
720 maps tag name to a string like \'global\' or \'local\'.
718 Subclasses or extensions are free to add their own tags, but
721 Subclasses or extensions are free to add their own tags, but
719 should be aware that the returned dicts will be retained for the
722 should be aware that the returned dicts will be retained for the
720 duration of the localrepo object.'''
723 duration of the localrepo object.'''
721
724
722 # XXX what tagtype should subclasses/extensions use? Currently
725 # XXX what tagtype should subclasses/extensions use? Currently
723 # mq and bookmarks add tags, but do not set the tagtype at all.
726 # mq and bookmarks add tags, but do not set the tagtype at all.
724 # Should each extension invent its own tag type? Should there
727 # Should each extension invent its own tag type? Should there
725 # be one tagtype for all such "virtual" tags? Or is the status
728 # be one tagtype for all such "virtual" tags? Or is the status
726 # quo fine?
729 # quo fine?
727
730
728
731
729 # map tag name to (node, hist)
732 # map tag name to (node, hist)
730 alltags = tagsmod.findglobaltags(self.ui, self)
733 alltags = tagsmod.findglobaltags(self.ui, self)
731 # map tag name to tag type
734 # map tag name to tag type
732 tagtypes = dict((tag, 'global') for tag in alltags)
735 tagtypes = dict((tag, 'global') for tag in alltags)
733
736
734 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
737 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
735
738
736 # Build the return dicts. Have to re-encode tag names because
739 # Build the return dicts. Have to re-encode tag names because
737 # the tags module always uses UTF-8 (in order not to lose info
740 # the tags module always uses UTF-8 (in order not to lose info
738 # writing to the cache), but the rest of Mercurial wants them in
741 # writing to the cache), but the rest of Mercurial wants them in
739 # local encoding.
742 # local encoding.
740 tags = {}
743 tags = {}
741 for (name, (node, hist)) in alltags.iteritems():
744 for (name, (node, hist)) in alltags.iteritems():
742 if node != nullid:
745 if node != nullid:
743 tags[encoding.tolocal(name)] = node
746 tags[encoding.tolocal(name)] = node
744 tags['tip'] = self.changelog.tip()
747 tags['tip'] = self.changelog.tip()
745 tagtypes = dict([(encoding.tolocal(name), value)
748 tagtypes = dict([(encoding.tolocal(name), value)
746 for (name, value) in tagtypes.iteritems()])
749 for (name, value) in tagtypes.iteritems()])
747 return (tags, tagtypes)
750 return (tags, tagtypes)
748
751
749 def tagtype(self, tagname):
752 def tagtype(self, tagname):
750 '''
753 '''
751 return the type of the given tag. result can be:
754 return the type of the given tag. result can be:
752
755
753 'local' : a local tag
756 'local' : a local tag
754 'global' : a global tag
757 'global' : a global tag
755 None : tag does not exist
758 None : tag does not exist
756 '''
759 '''
757
760
758 return self._tagscache.tagtypes.get(tagname)
761 return self._tagscache.tagtypes.get(tagname)
759
762
760 def tagslist(self):
763 def tagslist(self):
761 '''return a list of tags ordered by revision'''
764 '''return a list of tags ordered by revision'''
762 if not self._tagscache.tagslist:
765 if not self._tagscache.tagslist:
763 l = []
766 l = []
764 for t, n in self.tags().iteritems():
767 for t, n in self.tags().iteritems():
765 l.append((self.changelog.rev(n), t, n))
768 l.append((self.changelog.rev(n), t, n))
766 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
769 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
767
770
768 return self._tagscache.tagslist
771 return self._tagscache.tagslist
769
772
770 def nodetags(self, node):
773 def nodetags(self, node):
771 '''return the tags associated with a node'''
774 '''return the tags associated with a node'''
772 if not self._tagscache.nodetagscache:
775 if not self._tagscache.nodetagscache:
773 nodetagscache = {}
776 nodetagscache = {}
774 for t, n in self._tagscache.tags.iteritems():
777 for t, n in self._tagscache.tags.iteritems():
775 nodetagscache.setdefault(n, []).append(t)
778 nodetagscache.setdefault(n, []).append(t)
776 for tags in nodetagscache.itervalues():
779 for tags in nodetagscache.itervalues():
777 tags.sort()
780 tags.sort()
778 self._tagscache.nodetagscache = nodetagscache
781 self._tagscache.nodetagscache = nodetagscache
779 return self._tagscache.nodetagscache.get(node, [])
782 return self._tagscache.nodetagscache.get(node, [])
780
783
781 def nodebookmarks(self, node):
784 def nodebookmarks(self, node):
782 """return the list of bookmarks pointing to the specified node"""
785 """return the list of bookmarks pointing to the specified node"""
783 marks = []
786 marks = []
784 for bookmark, n in self._bookmarks.iteritems():
787 for bookmark, n in self._bookmarks.iteritems():
785 if n == node:
788 if n == node:
786 marks.append(bookmark)
789 marks.append(bookmark)
787 return sorted(marks)
790 return sorted(marks)
788
791
789 def branchmap(self):
792 def branchmap(self):
790 '''returns a dictionary {branch: [branchheads]} with branchheads
793 '''returns a dictionary {branch: [branchheads]} with branchheads
791 ordered by increasing revision number'''
794 ordered by increasing revision number'''
792 branchmap.updatecache(self)
795 branchmap.updatecache(self)
793 return self._branchcaches[self.filtername]
796 return self._branchcaches[self.filtername]
794
797
795 @unfilteredmethod
798 @unfilteredmethod
796 def revbranchcache(self):
799 def revbranchcache(self):
797 if not self._revbranchcache:
800 if not self._revbranchcache:
798 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
801 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
799 return self._revbranchcache
802 return self._revbranchcache
800
803
801 def branchtip(self, branch, ignoremissing=False):
804 def branchtip(self, branch, ignoremissing=False):
802 '''return the tip node for a given branch
805 '''return the tip node for a given branch
803
806
804 If ignoremissing is True, then this method will not raise an error.
807 If ignoremissing is True, then this method will not raise an error.
805 This is helpful for callers that only expect None for a missing branch
808 This is helpful for callers that only expect None for a missing branch
806 (e.g. namespace).
809 (e.g. namespace).
807
810
808 '''
811 '''
809 try:
812 try:
810 return self.branchmap().branchtip(branch)
813 return self.branchmap().branchtip(branch)
811 except KeyError:
814 except KeyError:
812 if not ignoremissing:
815 if not ignoremissing:
813 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
816 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
814 else:
817 else:
815 pass
818 pass
816
819
817 def lookup(self, key):
820 def lookup(self, key):
818 return self[key].node()
821 return self[key].node()
819
822
820 def lookupbranch(self, key, remote=None):
823 def lookupbranch(self, key, remote=None):
821 repo = remote or self
824 repo = remote or self
822 if key in repo.branchmap():
825 if key in repo.branchmap():
823 return key
826 return key
824
827
825 repo = (remote and remote.local()) and remote or self
828 repo = (remote and remote.local()) and remote or self
826 return repo[key].branch()
829 return repo[key].branch()
827
830
828 def known(self, nodes):
831 def known(self, nodes):
829 cl = self.changelog
832 cl = self.changelog
830 nm = cl.nodemap
833 nm = cl.nodemap
831 filtered = cl.filteredrevs
834 filtered = cl.filteredrevs
832 result = []
835 result = []
833 for n in nodes:
836 for n in nodes:
834 r = nm.get(n)
837 r = nm.get(n)
835 resp = not (r is None or r in filtered)
838 resp = not (r is None or r in filtered)
836 result.append(resp)
839 result.append(resp)
837 return result
840 return result
838
841
839 def local(self):
842 def local(self):
840 return self
843 return self
841
844
842 def publishing(self):
845 def publishing(self):
843 # it's safe (and desirable) to trust the publish flag unconditionally
846 # it's safe (and desirable) to trust the publish flag unconditionally
844 # so that we don't finalize changes shared between users via ssh or nfs
847 # so that we don't finalize changes shared between users via ssh or nfs
845 return self.ui.configbool('phases', 'publish', True, untrusted=True)
848 return self.ui.configbool('phases', 'publish', True, untrusted=True)
846
849
847 def cancopy(self):
850 def cancopy(self):
848 # so statichttprepo's override of local() works
851 # so statichttprepo's override of local() works
849 if not self.local():
852 if not self.local():
850 return False
853 return False
851 if not self.publishing():
854 if not self.publishing():
852 return True
855 return True
853 # if publishing we can't copy if there is filtered content
856 # if publishing we can't copy if there is filtered content
854 return not self.filtered('visible').changelog.filteredrevs
857 return not self.filtered('visible').changelog.filteredrevs
855
858
856 def shared(self):
859 def shared(self):
857 '''the type of shared repository (None if not shared)'''
860 '''the type of shared repository (None if not shared)'''
858 if self.sharedpath != self.path:
861 if self.sharedpath != self.path:
859 return 'store'
862 return 'store'
860 return None
863 return None
861
864
862 def wjoin(self, f, *insidef):
865 def wjoin(self, f, *insidef):
863 return self.vfs.reljoin(self.root, f, *insidef)
866 return self.vfs.reljoin(self.root, f, *insidef)
864
867
865 def file(self, f):
868 def file(self, f):
866 if f[0] == '/':
869 if f[0] == '/':
867 f = f[1:]
870 f = f[1:]
868 return filelog.filelog(self.svfs, f)
871 return filelog.filelog(self.svfs, f)
869
872
870 def changectx(self, changeid):
873 def changectx(self, changeid):
871 return self[changeid]
874 return self[changeid]
872
875
873 def setparents(self, p1, p2=nullid):
876 def setparents(self, p1, p2=nullid):
874 with self.dirstate.parentchange():
877 with self.dirstate.parentchange():
875 copies = self.dirstate.setparents(p1, p2)
878 copies = self.dirstate.setparents(p1, p2)
876 pctx = self[p1]
879 pctx = self[p1]
877 if copies:
880 if copies:
878 # Adjust copy records, the dirstate cannot do it, it
881 # Adjust copy records, the dirstate cannot do it, it
879 # requires access to parents manifests. Preserve them
882 # requires access to parents manifests. Preserve them
880 # only for entries added to first parent.
883 # only for entries added to first parent.
881 for f in copies:
884 for f in copies:
882 if f not in pctx and copies[f] in pctx:
885 if f not in pctx and copies[f] in pctx:
883 self.dirstate.copy(copies[f], f)
886 self.dirstate.copy(copies[f], f)
884 if p2 == nullid:
887 if p2 == nullid:
885 for f, s in sorted(self.dirstate.copies().items()):
888 for f, s in sorted(self.dirstate.copies().items()):
886 if f not in pctx and s not in pctx:
889 if f not in pctx and s not in pctx:
887 self.dirstate.copy(None, f)
890 self.dirstate.copy(None, f)
888
891
889 def filectx(self, path, changeid=None, fileid=None):
892 def filectx(self, path, changeid=None, fileid=None):
890 """changeid can be a changeset revision, node, or tag.
893 """changeid can be a changeset revision, node, or tag.
891 fileid can be a file revision or node."""
894 fileid can be a file revision or node."""
892 return context.filectx(self, path, changeid, fileid)
895 return context.filectx(self, path, changeid, fileid)
893
896
894 def getcwd(self):
897 def getcwd(self):
895 return self.dirstate.getcwd()
898 return self.dirstate.getcwd()
896
899
897 def pathto(self, f, cwd=None):
900 def pathto(self, f, cwd=None):
898 return self.dirstate.pathto(f, cwd)
901 return self.dirstate.pathto(f, cwd)
899
902
900 def _loadfilter(self, filter):
903 def _loadfilter(self, filter):
901 if filter not in self.filterpats:
904 if filter not in self.filterpats:
902 l = []
905 l = []
903 for pat, cmd in self.ui.configitems(filter):
906 for pat, cmd in self.ui.configitems(filter):
904 if cmd == '!':
907 if cmd == '!':
905 continue
908 continue
906 mf = matchmod.match(self.root, '', [pat])
909 mf = matchmod.match(self.root, '', [pat])
907 fn = None
910 fn = None
908 params = cmd
911 params = cmd
909 for name, filterfn in self._datafilters.iteritems():
912 for name, filterfn in self._datafilters.iteritems():
910 if cmd.startswith(name):
913 if cmd.startswith(name):
911 fn = filterfn
914 fn = filterfn
912 params = cmd[len(name):].lstrip()
915 params = cmd[len(name):].lstrip()
913 break
916 break
914 if not fn:
917 if not fn:
915 fn = lambda s, c, **kwargs: util.filter(s, c)
918 fn = lambda s, c, **kwargs: util.filter(s, c)
916 # Wrap old filters not supporting keyword arguments
919 # Wrap old filters not supporting keyword arguments
917 if not inspect.getargspec(fn)[2]:
920 if not inspect.getargspec(fn)[2]:
918 oldfn = fn
921 oldfn = fn
919 fn = lambda s, c, **kwargs: oldfn(s, c)
922 fn = lambda s, c, **kwargs: oldfn(s, c)
920 l.append((mf, fn, params))
923 l.append((mf, fn, params))
921 self.filterpats[filter] = l
924 self.filterpats[filter] = l
922 return self.filterpats[filter]
925 return self.filterpats[filter]
923
926
924 def _filter(self, filterpats, filename, data):
927 def _filter(self, filterpats, filename, data):
925 for mf, fn, cmd in filterpats:
928 for mf, fn, cmd in filterpats:
926 if mf(filename):
929 if mf(filename):
927 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
930 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
928 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
931 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
929 break
932 break
930
933
931 return data
934 return data
932
935
933 @unfilteredpropertycache
936 @unfilteredpropertycache
934 def _encodefilterpats(self):
937 def _encodefilterpats(self):
935 return self._loadfilter('encode')
938 return self._loadfilter('encode')
936
939
937 @unfilteredpropertycache
940 @unfilteredpropertycache
938 def _decodefilterpats(self):
941 def _decodefilterpats(self):
939 return self._loadfilter('decode')
942 return self._loadfilter('decode')
940
943
941 def adddatafilter(self, name, filter):
944 def adddatafilter(self, name, filter):
942 self._datafilters[name] = filter
945 self._datafilters[name] = filter
943
946
944 def wread(self, filename):
947 def wread(self, filename):
945 if self.wvfs.islink(filename):
948 if self.wvfs.islink(filename):
946 data = self.wvfs.readlink(filename)
949 data = self.wvfs.readlink(filename)
947 else:
950 else:
948 data = self.wvfs.read(filename)
951 data = self.wvfs.read(filename)
949 return self._filter(self._encodefilterpats, filename, data)
952 return self._filter(self._encodefilterpats, filename, data)
950
953
951 def wwrite(self, filename, data, flags, backgroundclose=False):
954 def wwrite(self, filename, data, flags, backgroundclose=False):
952 """write ``data`` into ``filename`` in the working directory
955 """write ``data`` into ``filename`` in the working directory
953
956
954 This returns length of written (maybe decoded) data.
957 This returns length of written (maybe decoded) data.
955 """
958 """
956 data = self._filter(self._decodefilterpats, filename, data)
959 data = self._filter(self._decodefilterpats, filename, data)
957 if 'l' in flags:
960 if 'l' in flags:
958 self.wvfs.symlink(data, filename)
961 self.wvfs.symlink(data, filename)
959 else:
962 else:
960 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
963 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
961 if 'x' in flags:
964 if 'x' in flags:
962 self.wvfs.setflags(filename, False, True)
965 self.wvfs.setflags(filename, False, True)
963 return len(data)
966 return len(data)
964
967
965 def wwritedata(self, filename, data):
968 def wwritedata(self, filename, data):
966 return self._filter(self._decodefilterpats, filename, data)
969 return self._filter(self._decodefilterpats, filename, data)
967
970
968 def currenttransaction(self):
971 def currenttransaction(self):
969 """return the current transaction or None if non exists"""
972 """return the current transaction or None if non exists"""
970 if self._transref:
973 if self._transref:
971 tr = self._transref()
974 tr = self._transref()
972 else:
975 else:
973 tr = None
976 tr = None
974
977
975 if tr and tr.running():
978 if tr and tr.running():
976 return tr
979 return tr
977 return None
980 return None
978
981
979 def transaction(self, desc, report=None):
982 def transaction(self, desc, report=None):
980 if (self.ui.configbool('devel', 'all-warnings')
983 if (self.ui.configbool('devel', 'all-warnings')
981 or self.ui.configbool('devel', 'check-locks')):
984 or self.ui.configbool('devel', 'check-locks')):
982 if self._currentlock(self._lockref) is None:
985 if self._currentlock(self._lockref) is None:
983 raise error.ProgrammingError('transaction requires locking')
986 raise error.ProgrammingError('transaction requires locking')
984 tr = self.currenttransaction()
987 tr = self.currenttransaction()
985 if tr is not None:
988 if tr is not None:
986 return tr.nest()
989 return tr.nest()
987
990
988 # abort here if the journal already exists
991 # abort here if the journal already exists
989 if self.svfs.exists("journal"):
992 if self.svfs.exists("journal"):
990 raise error.RepoError(
993 raise error.RepoError(
991 _("abandoned transaction found"),
994 _("abandoned transaction found"),
992 hint=_("run 'hg recover' to clean up transaction"))
995 hint=_("run 'hg recover' to clean up transaction"))
993
996
994 idbase = "%.40f#%f" % (random.random(), time.time())
997 idbase = "%.40f#%f" % (random.random(), time.time())
995 ha = hex(hashlib.sha1(idbase).digest())
998 ha = hex(hashlib.sha1(idbase).digest())
996 txnid = 'TXN:' + ha
999 txnid = 'TXN:' + ha
997 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1000 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
998
1001
999 self._writejournal(desc)
1002 self._writejournal(desc)
1000 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1003 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1001 if report:
1004 if report:
1002 rp = report
1005 rp = report
1003 else:
1006 else:
1004 rp = self.ui.warn
1007 rp = self.ui.warn
1005 vfsmap = {'plain': self.vfs} # root of .hg/
1008 vfsmap = {'plain': self.vfs} # root of .hg/
1006 # we must avoid cyclic reference between repo and transaction.
1009 # we must avoid cyclic reference between repo and transaction.
1007 reporef = weakref.ref(self)
1010 reporef = weakref.ref(self)
1008 # Code to track tag movement
1011 # Code to track tag movement
1009 #
1012 #
1010 # Since tags are all handled as file content, it is actually quite hard
1013 # Since tags are all handled as file content, it is actually quite hard
1011 # to track these movement from a code perspective. So we fallback to a
1014 # to track these movement from a code perspective. So we fallback to a
1012 # tracking at the repository level. One could envision to track changes
1015 # tracking at the repository level. One could envision to track changes
1013 # to the '.hgtags' file through changegroup apply but that fails to
1016 # to the '.hgtags' file through changegroup apply but that fails to
1014 # cope with case where transaction expose new heads without changegroup
1017 # cope with case where transaction expose new heads without changegroup
1015 # being involved (eg: phase movement).
1018 # being involved (eg: phase movement).
1016 #
1019 #
1017 # For now, We gate the feature behind a flag since this likely comes
1020 # For now, We gate the feature behind a flag since this likely comes
1018 # with performance impacts. The current code run more often than needed
1021 # with performance impacts. The current code run more often than needed
1019 # and do not use caches as much as it could. The current focus is on
1022 # and do not use caches as much as it could. The current focus is on
1020 # the behavior of the feature so we disable it by default. The flag
1023 # the behavior of the feature so we disable it by default. The flag
1021 # will be removed when we are happy with the performance impact.
1024 # will be removed when we are happy with the performance impact.
1022 #
1025 #
1023 # Once this feature is no longer experimental move the following
1026 # Once this feature is no longer experimental move the following
1024 # documentation to the appropriate help section:
1027 # documentation to the appropriate help section:
1025 #
1028 #
1026 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1029 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1027 # tags (new or changed or deleted tags). In addition the details of
1030 # tags (new or changed or deleted tags). In addition the details of
1028 # these changes are made available in a file at:
1031 # these changes are made available in a file at:
1029 # ``REPOROOT/.hg/changes/tags.changes``.
1032 # ``REPOROOT/.hg/changes/tags.changes``.
1030 # Make sure you check for HG_TAG_MOVED before reading that file as it
1033 # Make sure you check for HG_TAG_MOVED before reading that file as it
1031 # might exist from a previous transaction even if no tag were touched
1034 # might exist from a previous transaction even if no tag were touched
1032 # in this one. Changes are recorded in a line base format::
1035 # in this one. Changes are recorded in a line base format::
1033 #
1036 #
1034 # <action> <hex-node> <tag-name>\n
1037 # <action> <hex-node> <tag-name>\n
1035 #
1038 #
1036 # Actions are defined as follow:
1039 # Actions are defined as follow:
1037 # "-R": tag is removed,
1040 # "-R": tag is removed,
1038 # "+A": tag is added,
1041 # "+A": tag is added,
1039 # "-M": tag is moved (old value),
1042 # "-M": tag is moved (old value),
1040 # "+M": tag is moved (new value),
1043 # "+M": tag is moved (new value),
1041 tracktags = lambda x: None
1044 tracktags = lambda x: None
1042 # experimental config: experimental.hook-track-tags
1045 # experimental config: experimental.hook-track-tags
1043 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags',
1046 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags',
1044 False)
1047 False)
1045 if desc != 'strip' and shouldtracktags:
1048 if desc != 'strip' and shouldtracktags:
1046 oldheads = self.changelog.headrevs()
1049 oldheads = self.changelog.headrevs()
1047 def tracktags(tr2):
1050 def tracktags(tr2):
1048 repo = reporef()
1051 repo = reporef()
1049 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1052 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1050 newheads = repo.changelog.headrevs()
1053 newheads = repo.changelog.headrevs()
1051 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1054 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1052 # notes: we compare lists here.
1055 # notes: we compare lists here.
1053 # As we do it only once buiding set would not be cheaper
1056 # As we do it only once buiding set would not be cheaper
1054 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1057 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1055 if changes:
1058 if changes:
1056 tr2.hookargs['tag_moved'] = '1'
1059 tr2.hookargs['tag_moved'] = '1'
1057 with repo.vfs('changes/tags.changes', 'w',
1060 with repo.vfs('changes/tags.changes', 'w',
1058 atomictemp=True) as changesfile:
1061 atomictemp=True) as changesfile:
1059 # note: we do not register the file to the transaction
1062 # note: we do not register the file to the transaction
1060 # because we needs it to still exist on the transaction
1063 # because we needs it to still exist on the transaction
1061 # is close (for txnclose hooks)
1064 # is close (for txnclose hooks)
1062 tagsmod.writediff(changesfile, changes)
1065 tagsmod.writediff(changesfile, changes)
1063 def validate(tr2):
1066 def validate(tr2):
1064 """will run pre-closing hooks"""
1067 """will run pre-closing hooks"""
1065 # XXX the transaction API is a bit lacking here so we take a hacky
1068 # XXX the transaction API is a bit lacking here so we take a hacky
1066 # path for now
1069 # path for now
1067 #
1070 #
1068 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1071 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1069 # dict is copied before these run. In addition we needs the data
1072 # dict is copied before these run. In addition we needs the data
1070 # available to in memory hooks too.
1073 # available to in memory hooks too.
1071 #
1074 #
1072 # Moreover, we also need to make sure this runs before txnclose
1075 # Moreover, we also need to make sure this runs before txnclose
1073 # hooks and there is no "pending" mechanism that would execute
1076 # hooks and there is no "pending" mechanism that would execute
1074 # logic only if hooks are about to run.
1077 # logic only if hooks are about to run.
1075 #
1078 #
1076 # Fixing this limitation of the transaction is also needed to track
1079 # Fixing this limitation of the transaction is also needed to track
1077 # other families of changes (bookmarks, phases, obsolescence).
1080 # other families of changes (bookmarks, phases, obsolescence).
1078 #
1081 #
1079 # This will have to be fixed before we remove the experimental
1082 # This will have to be fixed before we remove the experimental
1080 # gating.
1083 # gating.
1081 tracktags(tr2)
1084 tracktags(tr2)
1082 reporef().hook('pretxnclose', throw=True,
1085 reporef().hook('pretxnclose', throw=True,
1083 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1086 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1084 def releasefn(tr, success):
1087 def releasefn(tr, success):
1085 repo = reporef()
1088 repo = reporef()
1086 if success:
1089 if success:
1087 # this should be explicitly invoked here, because
1090 # this should be explicitly invoked here, because
1088 # in-memory changes aren't written out at closing
1091 # in-memory changes aren't written out at closing
1089 # transaction, if tr.addfilegenerator (via
1092 # transaction, if tr.addfilegenerator (via
1090 # dirstate.write or so) isn't invoked while
1093 # dirstate.write or so) isn't invoked while
1091 # transaction running
1094 # transaction running
1092 repo.dirstate.write(None)
1095 repo.dirstate.write(None)
1093 else:
1096 else:
1094 # discard all changes (including ones already written
1097 # discard all changes (including ones already written
1095 # out) in this transaction
1098 # out) in this transaction
1096 repo.dirstate.restorebackup(None, prefix='journal.')
1099 repo.dirstate.restorebackup(None, prefix='journal.')
1097
1100
1098 repo.invalidate(clearfilecache=True)
1101 repo.invalidate(clearfilecache=True)
1099
1102
1100 tr = transaction.transaction(rp, self.svfs, vfsmap,
1103 tr = transaction.transaction(rp, self.svfs, vfsmap,
1101 "journal",
1104 "journal",
1102 "undo",
1105 "undo",
1103 aftertrans(renames),
1106 aftertrans(renames),
1104 self.store.createmode,
1107 self.store.createmode,
1105 validator=validate,
1108 validator=validate,
1106 releasefn=releasefn,
1109 releasefn=releasefn,
1107 checkambigfiles=_cachedfiles)
1110 checkambigfiles=_cachedfiles)
1108 tr.changes['revs'] = set()
1111 tr.changes['revs'] = set()
1109 tr.changes['obsmarkers'] = set()
1112 tr.changes['obsmarkers'] = set()
1110
1113
1111 tr.hookargs['txnid'] = txnid
1114 tr.hookargs['txnid'] = txnid
1112 # note: writing the fncache only during finalize mean that the file is
1115 # note: writing the fncache only during finalize mean that the file is
1113 # outdated when running hooks. As fncache is used for streaming clone,
1116 # outdated when running hooks. As fncache is used for streaming clone,
1114 # this is not expected to break anything that happen during the hooks.
1117 # this is not expected to break anything that happen during the hooks.
1115 tr.addfinalize('flush-fncache', self.store.write)
1118 tr.addfinalize('flush-fncache', self.store.write)
1116 def txnclosehook(tr2):
1119 def txnclosehook(tr2):
1117 """To be run if transaction is successful, will schedule a hook run
1120 """To be run if transaction is successful, will schedule a hook run
1118 """
1121 """
1119 # Don't reference tr2 in hook() so we don't hold a reference.
1122 # Don't reference tr2 in hook() so we don't hold a reference.
1120 # This reduces memory consumption when there are multiple
1123 # This reduces memory consumption when there are multiple
1121 # transactions per lock. This can likely go away if issue5045
1124 # transactions per lock. This can likely go away if issue5045
1122 # fixes the function accumulation.
1125 # fixes the function accumulation.
1123 hookargs = tr2.hookargs
1126 hookargs = tr2.hookargs
1124
1127
1125 def hook():
1128 def hook():
1126 reporef().hook('txnclose', throw=False, txnname=desc,
1129 reporef().hook('txnclose', throw=False, txnname=desc,
1127 **pycompat.strkwargs(hookargs))
1130 **pycompat.strkwargs(hookargs))
1128 reporef()._afterlock(hook)
1131 reporef()._afterlock(hook)
1129 tr.addfinalize('txnclose-hook', txnclosehook)
1132 tr.addfinalize('txnclose-hook', txnclosehook)
1130 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1133 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1131 def txnaborthook(tr2):
1134 def txnaborthook(tr2):
1132 """To be run if transaction is aborted
1135 """To be run if transaction is aborted
1133 """
1136 """
1134 reporef().hook('txnabort', throw=False, txnname=desc,
1137 reporef().hook('txnabort', throw=False, txnname=desc,
1135 **tr2.hookargs)
1138 **tr2.hookargs)
1136 tr.addabort('txnabort-hook', txnaborthook)
1139 tr.addabort('txnabort-hook', txnaborthook)
1137 # avoid eager cache invalidation. in-memory data should be identical
1140 # avoid eager cache invalidation. in-memory data should be identical
1138 # to stored data if transaction has no error.
1141 # to stored data if transaction has no error.
1139 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1142 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1140 self._transref = weakref.ref(tr)
1143 self._transref = weakref.ref(tr)
1141 return tr
1144 return tr
1142
1145
1143 def _journalfiles(self):
1146 def _journalfiles(self):
1144 return ((self.svfs, 'journal'),
1147 return ((self.svfs, 'journal'),
1145 (self.vfs, 'journal.dirstate'),
1148 (self.vfs, 'journal.dirstate'),
1146 (self.vfs, 'journal.branch'),
1149 (self.vfs, 'journal.branch'),
1147 (self.vfs, 'journal.desc'),
1150 (self.vfs, 'journal.desc'),
1148 (self.vfs, 'journal.bookmarks'),
1151 (self.vfs, 'journal.bookmarks'),
1149 (self.svfs, 'journal.phaseroots'))
1152 (self.svfs, 'journal.phaseroots'))
1150
1153
1151 def undofiles(self):
1154 def undofiles(self):
1152 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1155 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1153
1156
1154 @unfilteredmethod
1157 @unfilteredmethod
1155 def _writejournal(self, desc):
1158 def _writejournal(self, desc):
1156 self.dirstate.savebackup(None, prefix='journal.')
1159 self.dirstate.savebackup(None, prefix='journal.')
1157 self.vfs.write("journal.branch",
1160 self.vfs.write("journal.branch",
1158 encoding.fromlocal(self.dirstate.branch()))
1161 encoding.fromlocal(self.dirstate.branch()))
1159 self.vfs.write("journal.desc",
1162 self.vfs.write("journal.desc",
1160 "%d\n%s\n" % (len(self), desc))
1163 "%d\n%s\n" % (len(self), desc))
1161 self.vfs.write("journal.bookmarks",
1164 self.vfs.write("journal.bookmarks",
1162 self.vfs.tryread("bookmarks"))
1165 self.vfs.tryread("bookmarks"))
1163 self.svfs.write("journal.phaseroots",
1166 self.svfs.write("journal.phaseroots",
1164 self.svfs.tryread("phaseroots"))
1167 self.svfs.tryread("phaseroots"))
1165
1168
1166 def recover(self):
1169 def recover(self):
1167 with self.lock():
1170 with self.lock():
1168 if self.svfs.exists("journal"):
1171 if self.svfs.exists("journal"):
1169 self.ui.status(_("rolling back interrupted transaction\n"))
1172 self.ui.status(_("rolling back interrupted transaction\n"))
1170 vfsmap = {'': self.svfs,
1173 vfsmap = {'': self.svfs,
1171 'plain': self.vfs,}
1174 'plain': self.vfs,}
1172 transaction.rollback(self.svfs, vfsmap, "journal",
1175 transaction.rollback(self.svfs, vfsmap, "journal",
1173 self.ui.warn,
1176 self.ui.warn,
1174 checkambigfiles=_cachedfiles)
1177 checkambigfiles=_cachedfiles)
1175 self.invalidate()
1178 self.invalidate()
1176 return True
1179 return True
1177 else:
1180 else:
1178 self.ui.warn(_("no interrupted transaction available\n"))
1181 self.ui.warn(_("no interrupted transaction available\n"))
1179 return False
1182 return False
1180
1183
1181 def rollback(self, dryrun=False, force=False):
1184 def rollback(self, dryrun=False, force=False):
1182 wlock = lock = dsguard = None
1185 wlock = lock = dsguard = None
1183 try:
1186 try:
1184 wlock = self.wlock()
1187 wlock = self.wlock()
1185 lock = self.lock()
1188 lock = self.lock()
1186 if self.svfs.exists("undo"):
1189 if self.svfs.exists("undo"):
1187 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1190 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1188
1191
1189 return self._rollback(dryrun, force, dsguard)
1192 return self._rollback(dryrun, force, dsguard)
1190 else:
1193 else:
1191 self.ui.warn(_("no rollback information available\n"))
1194 self.ui.warn(_("no rollback information available\n"))
1192 return 1
1195 return 1
1193 finally:
1196 finally:
1194 release(dsguard, lock, wlock)
1197 release(dsguard, lock, wlock)
1195
1198
1196 @unfilteredmethod # Until we get smarter cache management
1199 @unfilteredmethod # Until we get smarter cache management
1197 def _rollback(self, dryrun, force, dsguard):
1200 def _rollback(self, dryrun, force, dsguard):
1198 ui = self.ui
1201 ui = self.ui
1199 try:
1202 try:
1200 args = self.vfs.read('undo.desc').splitlines()
1203 args = self.vfs.read('undo.desc').splitlines()
1201 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1204 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1202 if len(args) >= 3:
1205 if len(args) >= 3:
1203 detail = args[2]
1206 detail = args[2]
1204 oldtip = oldlen - 1
1207 oldtip = oldlen - 1
1205
1208
1206 if detail and ui.verbose:
1209 if detail and ui.verbose:
1207 msg = (_('repository tip rolled back to revision %d'
1210 msg = (_('repository tip rolled back to revision %d'
1208 ' (undo %s: %s)\n')
1211 ' (undo %s: %s)\n')
1209 % (oldtip, desc, detail))
1212 % (oldtip, desc, detail))
1210 else:
1213 else:
1211 msg = (_('repository tip rolled back to revision %d'
1214 msg = (_('repository tip rolled back to revision %d'
1212 ' (undo %s)\n')
1215 ' (undo %s)\n')
1213 % (oldtip, desc))
1216 % (oldtip, desc))
1214 except IOError:
1217 except IOError:
1215 msg = _('rolling back unknown transaction\n')
1218 msg = _('rolling back unknown transaction\n')
1216 desc = None
1219 desc = None
1217
1220
1218 if not force and self['.'] != self['tip'] and desc == 'commit':
1221 if not force and self['.'] != self['tip'] and desc == 'commit':
1219 raise error.Abort(
1222 raise error.Abort(
1220 _('rollback of last commit while not checked out '
1223 _('rollback of last commit while not checked out '
1221 'may lose data'), hint=_('use -f to force'))
1224 'may lose data'), hint=_('use -f to force'))
1222
1225
1223 ui.status(msg)
1226 ui.status(msg)
1224 if dryrun:
1227 if dryrun:
1225 return 0
1228 return 0
1226
1229
1227 parents = self.dirstate.parents()
1230 parents = self.dirstate.parents()
1228 self.destroying()
1231 self.destroying()
1229 vfsmap = {'plain': self.vfs, '': self.svfs}
1232 vfsmap = {'plain': self.vfs, '': self.svfs}
1230 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1233 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1231 checkambigfiles=_cachedfiles)
1234 checkambigfiles=_cachedfiles)
1232 if self.vfs.exists('undo.bookmarks'):
1235 if self.vfs.exists('undo.bookmarks'):
1233 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1236 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1234 if self.svfs.exists('undo.phaseroots'):
1237 if self.svfs.exists('undo.phaseroots'):
1235 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1238 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1236 self.invalidate()
1239 self.invalidate()
1237
1240
1238 parentgone = (parents[0] not in self.changelog.nodemap or
1241 parentgone = (parents[0] not in self.changelog.nodemap or
1239 parents[1] not in self.changelog.nodemap)
1242 parents[1] not in self.changelog.nodemap)
1240 if parentgone:
1243 if parentgone:
1241 # prevent dirstateguard from overwriting already restored one
1244 # prevent dirstateguard from overwriting already restored one
1242 dsguard.close()
1245 dsguard.close()
1243
1246
1244 self.dirstate.restorebackup(None, prefix='undo.')
1247 self.dirstate.restorebackup(None, prefix='undo.')
1245 try:
1248 try:
1246 branch = self.vfs.read('undo.branch')
1249 branch = self.vfs.read('undo.branch')
1247 self.dirstate.setbranch(encoding.tolocal(branch))
1250 self.dirstate.setbranch(encoding.tolocal(branch))
1248 except IOError:
1251 except IOError:
1249 ui.warn(_('named branch could not be reset: '
1252 ui.warn(_('named branch could not be reset: '
1250 'current branch is still \'%s\'\n')
1253 'current branch is still \'%s\'\n')
1251 % self.dirstate.branch())
1254 % self.dirstate.branch())
1252
1255
1253 parents = tuple([p.rev() for p in self[None].parents()])
1256 parents = tuple([p.rev() for p in self[None].parents()])
1254 if len(parents) > 1:
1257 if len(parents) > 1:
1255 ui.status(_('working directory now based on '
1258 ui.status(_('working directory now based on '
1256 'revisions %d and %d\n') % parents)
1259 'revisions %d and %d\n') % parents)
1257 else:
1260 else:
1258 ui.status(_('working directory now based on '
1261 ui.status(_('working directory now based on '
1259 'revision %d\n') % parents)
1262 'revision %d\n') % parents)
1260 mergemod.mergestate.clean(self, self['.'].node())
1263 mergemod.mergestate.clean(self, self['.'].node())
1261
1264
1262 # TODO: if we know which new heads may result from this rollback, pass
1265 # TODO: if we know which new heads may result from this rollback, pass
1263 # them to destroy(), which will prevent the branchhead cache from being
1266 # them to destroy(), which will prevent the branchhead cache from being
1264 # invalidated.
1267 # invalidated.
1265 self.destroyed()
1268 self.destroyed()
1266 return 0
1269 return 0
1267
1270
1268 def _buildcacheupdater(self, newtransaction):
1271 def _buildcacheupdater(self, newtransaction):
1269 """called during transaction to build the callback updating cache
1272 """called during transaction to build the callback updating cache
1270
1273
1271 Lives on the repository to help extension who might want to augment
1274 Lives on the repository to help extension who might want to augment
1272 this logic. For this purpose, the created transaction is passed to the
1275 this logic. For this purpose, the created transaction is passed to the
1273 method.
1276 method.
1274 """
1277 """
1275 # we must avoid cyclic reference between repo and transaction.
1278 # we must avoid cyclic reference between repo and transaction.
1276 reporef = weakref.ref(self)
1279 reporef = weakref.ref(self)
1277 def updater(tr):
1280 def updater(tr):
1278 repo = reporef()
1281 repo = reporef()
1279 repo.updatecaches(tr)
1282 repo.updatecaches(tr)
1280 return updater
1283 return updater
1281
1284
1282 @unfilteredmethod
1285 @unfilteredmethod
1283 def updatecaches(self, tr=None):
1286 def updatecaches(self, tr=None):
1284 """warm appropriate caches
1287 """warm appropriate caches
1285
1288
1286 If this function is called after a transaction closed. The transaction
1289 If this function is called after a transaction closed. The transaction
1287 will be available in the 'tr' argument. This can be used to selectively
1290 will be available in the 'tr' argument. This can be used to selectively
1288 update caches relevant to the changes in that transaction.
1291 update caches relevant to the changes in that transaction.
1289 """
1292 """
1290 if tr is not None and tr.hookargs.get('source') == 'strip':
1293 if tr is not None and tr.hookargs.get('source') == 'strip':
1291 # During strip, many caches are invalid but
1294 # During strip, many caches are invalid but
1292 # later call to `destroyed` will refresh them.
1295 # later call to `destroyed` will refresh them.
1293 return
1296 return
1294
1297
1295 if tr is None or tr.changes['revs']:
1298 if tr is None or tr.changes['revs']:
1296 # updating the unfiltered branchmap should refresh all the others,
1299 # updating the unfiltered branchmap should refresh all the others,
1297 self.ui.debug('updating the branch cache\n')
1300 self.ui.debug('updating the branch cache\n')
1298 branchmap.updatecache(self.filtered('served'))
1301 branchmap.updatecache(self.filtered('served'))
1299
1302
1300 def invalidatecaches(self):
1303 def invalidatecaches(self):
1301
1304
1302 if '_tagscache' in vars(self):
1305 if '_tagscache' in vars(self):
1303 # can't use delattr on proxy
1306 # can't use delattr on proxy
1304 del self.__dict__['_tagscache']
1307 del self.__dict__['_tagscache']
1305
1308
1306 self.unfiltered()._branchcaches.clear()
1309 self.unfiltered()._branchcaches.clear()
1307 self.invalidatevolatilesets()
1310 self.invalidatevolatilesets()
1308 self._sparsesignaturecache.clear()
1311 self._sparsesignaturecache.clear()
1309
1312
1310 def invalidatevolatilesets(self):
1313 def invalidatevolatilesets(self):
1311 self.filteredrevcache.clear()
1314 self.filteredrevcache.clear()
1312 obsolete.clearobscaches(self)
1315 obsolete.clearobscaches(self)
1313
1316
1314 def invalidatedirstate(self):
1317 def invalidatedirstate(self):
1315 '''Invalidates the dirstate, causing the next call to dirstate
1318 '''Invalidates the dirstate, causing the next call to dirstate
1316 to check if it was modified since the last time it was read,
1319 to check if it was modified since the last time it was read,
1317 rereading it if it has.
1320 rereading it if it has.
1318
1321
1319 This is different to dirstate.invalidate() that it doesn't always
1322 This is different to dirstate.invalidate() that it doesn't always
1320 rereads the dirstate. Use dirstate.invalidate() if you want to
1323 rereads the dirstate. Use dirstate.invalidate() if you want to
1321 explicitly read the dirstate again (i.e. restoring it to a previous
1324 explicitly read the dirstate again (i.e. restoring it to a previous
1322 known good state).'''
1325 known good state).'''
1323 if hasunfilteredcache(self, 'dirstate'):
1326 if hasunfilteredcache(self, 'dirstate'):
1324 for k in self.dirstate._filecache:
1327 for k in self.dirstate._filecache:
1325 try:
1328 try:
1326 delattr(self.dirstate, k)
1329 delattr(self.dirstate, k)
1327 except AttributeError:
1330 except AttributeError:
1328 pass
1331 pass
1329 delattr(self.unfiltered(), 'dirstate')
1332 delattr(self.unfiltered(), 'dirstate')
1330
1333
1331 def invalidate(self, clearfilecache=False):
1334 def invalidate(self, clearfilecache=False):
1332 '''Invalidates both store and non-store parts other than dirstate
1335 '''Invalidates both store and non-store parts other than dirstate
1333
1336
1334 If a transaction is running, invalidation of store is omitted,
1337 If a transaction is running, invalidation of store is omitted,
1335 because discarding in-memory changes might cause inconsistency
1338 because discarding in-memory changes might cause inconsistency
1336 (e.g. incomplete fncache causes unintentional failure, but
1339 (e.g. incomplete fncache causes unintentional failure, but
1337 redundant one doesn't).
1340 redundant one doesn't).
1338 '''
1341 '''
1339 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1342 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1340 for k in list(self._filecache.keys()):
1343 for k in list(self._filecache.keys()):
1341 # dirstate is invalidated separately in invalidatedirstate()
1344 # dirstate is invalidated separately in invalidatedirstate()
1342 if k == 'dirstate':
1345 if k == 'dirstate':
1343 continue
1346 continue
1344
1347
1345 if clearfilecache:
1348 if clearfilecache:
1346 del self._filecache[k]
1349 del self._filecache[k]
1347 try:
1350 try:
1348 delattr(unfiltered, k)
1351 delattr(unfiltered, k)
1349 except AttributeError:
1352 except AttributeError:
1350 pass
1353 pass
1351 self.invalidatecaches()
1354 self.invalidatecaches()
1352 if not self.currenttransaction():
1355 if not self.currenttransaction():
1353 # TODO: Changing contents of store outside transaction
1356 # TODO: Changing contents of store outside transaction
1354 # causes inconsistency. We should make in-memory store
1357 # causes inconsistency. We should make in-memory store
1355 # changes detectable, and abort if changed.
1358 # changes detectable, and abort if changed.
1356 self.store.invalidatecaches()
1359 self.store.invalidatecaches()
1357
1360
1358 def invalidateall(self):
1361 def invalidateall(self):
1359 '''Fully invalidates both store and non-store parts, causing the
1362 '''Fully invalidates both store and non-store parts, causing the
1360 subsequent operation to reread any outside changes.'''
1363 subsequent operation to reread any outside changes.'''
1361 # extension should hook this to invalidate its caches
1364 # extension should hook this to invalidate its caches
1362 self.invalidate()
1365 self.invalidate()
1363 self.invalidatedirstate()
1366 self.invalidatedirstate()
1364
1367
1365 @unfilteredmethod
1368 @unfilteredmethod
1366 def _refreshfilecachestats(self, tr):
1369 def _refreshfilecachestats(self, tr):
1367 """Reload stats of cached files so that they are flagged as valid"""
1370 """Reload stats of cached files so that they are flagged as valid"""
1368 for k, ce in self._filecache.items():
1371 for k, ce in self._filecache.items():
1369 if k == 'dirstate' or k not in self.__dict__:
1372 if k == 'dirstate' or k not in self.__dict__:
1370 continue
1373 continue
1371 ce.refresh()
1374 ce.refresh()
1372
1375
1373 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1376 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1374 inheritchecker=None, parentenvvar=None):
1377 inheritchecker=None, parentenvvar=None):
1375 parentlock = None
1378 parentlock = None
1376 # the contents of parentenvvar are used by the underlying lock to
1379 # the contents of parentenvvar are used by the underlying lock to
1377 # determine whether it can be inherited
1380 # determine whether it can be inherited
1378 if parentenvvar is not None:
1381 if parentenvvar is not None:
1379 parentlock = encoding.environ.get(parentenvvar)
1382 parentlock = encoding.environ.get(parentenvvar)
1380 try:
1383 try:
1381 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1384 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1382 acquirefn=acquirefn, desc=desc,
1385 acquirefn=acquirefn, desc=desc,
1383 inheritchecker=inheritchecker,
1386 inheritchecker=inheritchecker,
1384 parentlock=parentlock)
1387 parentlock=parentlock)
1385 except error.LockHeld as inst:
1388 except error.LockHeld as inst:
1386 if not wait:
1389 if not wait:
1387 raise
1390 raise
1388 # show more details for new-style locks
1391 # show more details for new-style locks
1389 if ':' in inst.locker:
1392 if ':' in inst.locker:
1390 host, pid = inst.locker.split(":", 1)
1393 host, pid = inst.locker.split(":", 1)
1391 self.ui.warn(
1394 self.ui.warn(
1392 _("waiting for lock on %s held by process %r "
1395 _("waiting for lock on %s held by process %r "
1393 "on host %r\n") % (desc, pid, host))
1396 "on host %r\n") % (desc, pid, host))
1394 else:
1397 else:
1395 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1398 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1396 (desc, inst.locker))
1399 (desc, inst.locker))
1397 # default to 600 seconds timeout
1400 # default to 600 seconds timeout
1398 l = lockmod.lock(vfs, lockname,
1401 l = lockmod.lock(vfs, lockname,
1399 int(self.ui.config("ui", "timeout", "600")),
1402 int(self.ui.config("ui", "timeout", "600")),
1400 releasefn=releasefn, acquirefn=acquirefn,
1403 releasefn=releasefn, acquirefn=acquirefn,
1401 desc=desc)
1404 desc=desc)
1402 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1405 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1403 return l
1406 return l
1404
1407
1405 def _afterlock(self, callback):
1408 def _afterlock(self, callback):
1406 """add a callback to be run when the repository is fully unlocked
1409 """add a callback to be run when the repository is fully unlocked
1407
1410
1408 The callback will be executed when the outermost lock is released
1411 The callback will be executed when the outermost lock is released
1409 (with wlock being higher level than 'lock')."""
1412 (with wlock being higher level than 'lock')."""
1410 for ref in (self._wlockref, self._lockref):
1413 for ref in (self._wlockref, self._lockref):
1411 l = ref and ref()
1414 l = ref and ref()
1412 if l and l.held:
1415 if l and l.held:
1413 l.postrelease.append(callback)
1416 l.postrelease.append(callback)
1414 break
1417 break
1415 else: # no lock have been found.
1418 else: # no lock have been found.
1416 callback()
1419 callback()
1417
1420
1418 def lock(self, wait=True):
1421 def lock(self, wait=True):
1419 '''Lock the repository store (.hg/store) and return a weak reference
1422 '''Lock the repository store (.hg/store) and return a weak reference
1420 to the lock. Use this before modifying the store (e.g. committing or
1423 to the lock. Use this before modifying the store (e.g. committing or
1421 stripping). If you are opening a transaction, get a lock as well.)
1424 stripping). If you are opening a transaction, get a lock as well.)
1422
1425
1423 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1426 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1424 'wlock' first to avoid a dead-lock hazard.'''
1427 'wlock' first to avoid a dead-lock hazard.'''
1425 l = self._currentlock(self._lockref)
1428 l = self._currentlock(self._lockref)
1426 if l is not None:
1429 if l is not None:
1427 l.lock()
1430 l.lock()
1428 return l
1431 return l
1429
1432
1430 l = self._lock(self.svfs, "lock", wait, None,
1433 l = self._lock(self.svfs, "lock", wait, None,
1431 self.invalidate, _('repository %s') % self.origroot)
1434 self.invalidate, _('repository %s') % self.origroot)
1432 self._lockref = weakref.ref(l)
1435 self._lockref = weakref.ref(l)
1433 return l
1436 return l
1434
1437
1435 def _wlockchecktransaction(self):
1438 def _wlockchecktransaction(self):
1436 if self.currenttransaction() is not None:
1439 if self.currenttransaction() is not None:
1437 raise error.LockInheritanceContractViolation(
1440 raise error.LockInheritanceContractViolation(
1438 'wlock cannot be inherited in the middle of a transaction')
1441 'wlock cannot be inherited in the middle of a transaction')
1439
1442
1440 def wlock(self, wait=True):
1443 def wlock(self, wait=True):
1441 '''Lock the non-store parts of the repository (everything under
1444 '''Lock the non-store parts of the repository (everything under
1442 .hg except .hg/store) and return a weak reference to the lock.
1445 .hg except .hg/store) and return a weak reference to the lock.
1443
1446
1444 Use this before modifying files in .hg.
1447 Use this before modifying files in .hg.
1445
1448
1446 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1449 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1447 'wlock' first to avoid a dead-lock hazard.'''
1450 'wlock' first to avoid a dead-lock hazard.'''
1448 l = self._wlockref and self._wlockref()
1451 l = self._wlockref and self._wlockref()
1449 if l is not None and l.held:
1452 if l is not None and l.held:
1450 l.lock()
1453 l.lock()
1451 return l
1454 return l
1452
1455
1453 # We do not need to check for non-waiting lock acquisition. Such
1456 # We do not need to check for non-waiting lock acquisition. Such
1454 # acquisition would not cause dead-lock as they would just fail.
1457 # acquisition would not cause dead-lock as they would just fail.
1455 if wait and (self.ui.configbool('devel', 'all-warnings')
1458 if wait and (self.ui.configbool('devel', 'all-warnings')
1456 or self.ui.configbool('devel', 'check-locks')):
1459 or self.ui.configbool('devel', 'check-locks')):
1457 if self._currentlock(self._lockref) is not None:
1460 if self._currentlock(self._lockref) is not None:
1458 self.ui.develwarn('"wlock" acquired after "lock"')
1461 self.ui.develwarn('"wlock" acquired after "lock"')
1459
1462
1460 def unlock():
1463 def unlock():
1461 if self.dirstate.pendingparentchange():
1464 if self.dirstate.pendingparentchange():
1462 self.dirstate.invalidate()
1465 self.dirstate.invalidate()
1463 else:
1466 else:
1464 self.dirstate.write(None)
1467 self.dirstate.write(None)
1465
1468
1466 self._filecache['dirstate'].refresh()
1469 self._filecache['dirstate'].refresh()
1467
1470
1468 l = self._lock(self.vfs, "wlock", wait, unlock,
1471 l = self._lock(self.vfs, "wlock", wait, unlock,
1469 self.invalidatedirstate, _('working directory of %s') %
1472 self.invalidatedirstate, _('working directory of %s') %
1470 self.origroot,
1473 self.origroot,
1471 inheritchecker=self._wlockchecktransaction,
1474 inheritchecker=self._wlockchecktransaction,
1472 parentenvvar='HG_WLOCK_LOCKER')
1475 parentenvvar='HG_WLOCK_LOCKER')
1473 self._wlockref = weakref.ref(l)
1476 self._wlockref = weakref.ref(l)
1474 return l
1477 return l
1475
1478
1476 def _currentlock(self, lockref):
1479 def _currentlock(self, lockref):
1477 """Returns the lock if it's held, or None if it's not."""
1480 """Returns the lock if it's held, or None if it's not."""
1478 if lockref is None:
1481 if lockref is None:
1479 return None
1482 return None
1480 l = lockref()
1483 l = lockref()
1481 if l is None or not l.held:
1484 if l is None or not l.held:
1482 return None
1485 return None
1483 return l
1486 return l
1484
1487
1485 def currentwlock(self):
1488 def currentwlock(self):
1486 """Returns the wlock if it's held, or None if it's not."""
1489 """Returns the wlock if it's held, or None if it's not."""
1487 return self._currentlock(self._wlockref)
1490 return self._currentlock(self._wlockref)
1488
1491
1489 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1492 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1490 """
1493 """
1491 commit an individual file as part of a larger transaction
1494 commit an individual file as part of a larger transaction
1492 """
1495 """
1493
1496
1494 fname = fctx.path()
1497 fname = fctx.path()
1495 fparent1 = manifest1.get(fname, nullid)
1498 fparent1 = manifest1.get(fname, nullid)
1496 fparent2 = manifest2.get(fname, nullid)
1499 fparent2 = manifest2.get(fname, nullid)
1497 if isinstance(fctx, context.filectx):
1500 if isinstance(fctx, context.filectx):
1498 node = fctx.filenode()
1501 node = fctx.filenode()
1499 if node in [fparent1, fparent2]:
1502 if node in [fparent1, fparent2]:
1500 self.ui.debug('reusing %s filelog entry\n' % fname)
1503 self.ui.debug('reusing %s filelog entry\n' % fname)
1501 if manifest1.flags(fname) != fctx.flags():
1504 if manifest1.flags(fname) != fctx.flags():
1502 changelist.append(fname)
1505 changelist.append(fname)
1503 return node
1506 return node
1504
1507
1505 flog = self.file(fname)
1508 flog = self.file(fname)
1506 meta = {}
1509 meta = {}
1507 copy = fctx.renamed()
1510 copy = fctx.renamed()
1508 if copy and copy[0] != fname:
1511 if copy and copy[0] != fname:
1509 # Mark the new revision of this file as a copy of another
1512 # Mark the new revision of this file as a copy of another
1510 # file. This copy data will effectively act as a parent
1513 # file. This copy data will effectively act as a parent
1511 # of this new revision. If this is a merge, the first
1514 # of this new revision. If this is a merge, the first
1512 # parent will be the nullid (meaning "look up the copy data")
1515 # parent will be the nullid (meaning "look up the copy data")
1513 # and the second one will be the other parent. For example:
1516 # and the second one will be the other parent. For example:
1514 #
1517 #
1515 # 0 --- 1 --- 3 rev1 changes file foo
1518 # 0 --- 1 --- 3 rev1 changes file foo
1516 # \ / rev2 renames foo to bar and changes it
1519 # \ / rev2 renames foo to bar and changes it
1517 # \- 2 -/ rev3 should have bar with all changes and
1520 # \- 2 -/ rev3 should have bar with all changes and
1518 # should record that bar descends from
1521 # should record that bar descends from
1519 # bar in rev2 and foo in rev1
1522 # bar in rev2 and foo in rev1
1520 #
1523 #
1521 # this allows this merge to succeed:
1524 # this allows this merge to succeed:
1522 #
1525 #
1523 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1526 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1524 # \ / merging rev3 and rev4 should use bar@rev2
1527 # \ / merging rev3 and rev4 should use bar@rev2
1525 # \- 2 --- 4 as the merge base
1528 # \- 2 --- 4 as the merge base
1526 #
1529 #
1527
1530
1528 cfname = copy[0]
1531 cfname = copy[0]
1529 crev = manifest1.get(cfname)
1532 crev = manifest1.get(cfname)
1530 newfparent = fparent2
1533 newfparent = fparent2
1531
1534
1532 if manifest2: # branch merge
1535 if manifest2: # branch merge
1533 if fparent2 == nullid or crev is None: # copied on remote side
1536 if fparent2 == nullid or crev is None: # copied on remote side
1534 if cfname in manifest2:
1537 if cfname in manifest2:
1535 crev = manifest2[cfname]
1538 crev = manifest2[cfname]
1536 newfparent = fparent1
1539 newfparent = fparent1
1537
1540
1538 # Here, we used to search backwards through history to try to find
1541 # Here, we used to search backwards through history to try to find
1539 # where the file copy came from if the source of a copy was not in
1542 # where the file copy came from if the source of a copy was not in
1540 # the parent directory. However, this doesn't actually make sense to
1543 # the parent directory. However, this doesn't actually make sense to
1541 # do (what does a copy from something not in your working copy even
1544 # do (what does a copy from something not in your working copy even
1542 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1545 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1543 # the user that copy information was dropped, so if they didn't
1546 # the user that copy information was dropped, so if they didn't
1544 # expect this outcome it can be fixed, but this is the correct
1547 # expect this outcome it can be fixed, but this is the correct
1545 # behavior in this circumstance.
1548 # behavior in this circumstance.
1546
1549
1547 if crev:
1550 if crev:
1548 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1551 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1549 meta["copy"] = cfname
1552 meta["copy"] = cfname
1550 meta["copyrev"] = hex(crev)
1553 meta["copyrev"] = hex(crev)
1551 fparent1, fparent2 = nullid, newfparent
1554 fparent1, fparent2 = nullid, newfparent
1552 else:
1555 else:
1553 self.ui.warn(_("warning: can't find ancestor for '%s' "
1556 self.ui.warn(_("warning: can't find ancestor for '%s' "
1554 "copied from '%s'!\n") % (fname, cfname))
1557 "copied from '%s'!\n") % (fname, cfname))
1555
1558
1556 elif fparent1 == nullid:
1559 elif fparent1 == nullid:
1557 fparent1, fparent2 = fparent2, nullid
1560 fparent1, fparent2 = fparent2, nullid
1558 elif fparent2 != nullid:
1561 elif fparent2 != nullid:
1559 # is one parent an ancestor of the other?
1562 # is one parent an ancestor of the other?
1560 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1563 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1561 if fparent1 in fparentancestors:
1564 if fparent1 in fparentancestors:
1562 fparent1, fparent2 = fparent2, nullid
1565 fparent1, fparent2 = fparent2, nullid
1563 elif fparent2 in fparentancestors:
1566 elif fparent2 in fparentancestors:
1564 fparent2 = nullid
1567 fparent2 = nullid
1565
1568
1566 # is the file changed?
1569 # is the file changed?
1567 text = fctx.data()
1570 text = fctx.data()
1568 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1571 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1569 changelist.append(fname)
1572 changelist.append(fname)
1570 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1573 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1571 # are just the flags changed during merge?
1574 # are just the flags changed during merge?
1572 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1575 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1573 changelist.append(fname)
1576 changelist.append(fname)
1574
1577
1575 return fparent1
1578 return fparent1
1576
1579
1577 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1580 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1578 """check for commit arguments that aren't committable"""
1581 """check for commit arguments that aren't committable"""
1579 if match.isexact() or match.prefix():
1582 if match.isexact() or match.prefix():
1580 matched = set(status.modified + status.added + status.removed)
1583 matched = set(status.modified + status.added + status.removed)
1581
1584
1582 for f in match.files():
1585 for f in match.files():
1583 f = self.dirstate.normalize(f)
1586 f = self.dirstate.normalize(f)
1584 if f == '.' or f in matched or f in wctx.substate:
1587 if f == '.' or f in matched or f in wctx.substate:
1585 continue
1588 continue
1586 if f in status.deleted:
1589 if f in status.deleted:
1587 fail(f, _('file not found!'))
1590 fail(f, _('file not found!'))
1588 if f in vdirs: # visited directory
1591 if f in vdirs: # visited directory
1589 d = f + '/'
1592 d = f + '/'
1590 for mf in matched:
1593 for mf in matched:
1591 if mf.startswith(d):
1594 if mf.startswith(d):
1592 break
1595 break
1593 else:
1596 else:
1594 fail(f, _("no match under directory!"))
1597 fail(f, _("no match under directory!"))
1595 elif f not in self.dirstate:
1598 elif f not in self.dirstate:
1596 fail(f, _("file not tracked!"))
1599 fail(f, _("file not tracked!"))
1597
1600
1598 @unfilteredmethod
1601 @unfilteredmethod
1599 def commit(self, text="", user=None, date=None, match=None, force=False,
1602 def commit(self, text="", user=None, date=None, match=None, force=False,
1600 editor=False, extra=None):
1603 editor=False, extra=None):
1601 """Add a new revision to current repository.
1604 """Add a new revision to current repository.
1602
1605
1603 Revision information is gathered from the working directory,
1606 Revision information is gathered from the working directory,
1604 match can be used to filter the committed files. If editor is
1607 match can be used to filter the committed files. If editor is
1605 supplied, it is called to get a commit message.
1608 supplied, it is called to get a commit message.
1606 """
1609 """
1607 if extra is None:
1610 if extra is None:
1608 extra = {}
1611 extra = {}
1609
1612
1610 def fail(f, msg):
1613 def fail(f, msg):
1611 raise error.Abort('%s: %s' % (f, msg))
1614 raise error.Abort('%s: %s' % (f, msg))
1612
1615
1613 if not match:
1616 if not match:
1614 match = matchmod.always(self.root, '')
1617 match = matchmod.always(self.root, '')
1615
1618
1616 if not force:
1619 if not force:
1617 vdirs = []
1620 vdirs = []
1618 match.explicitdir = vdirs.append
1621 match.explicitdir = vdirs.append
1619 match.bad = fail
1622 match.bad = fail
1620
1623
1621 wlock = lock = tr = None
1624 wlock = lock = tr = None
1622 try:
1625 try:
1623 wlock = self.wlock()
1626 wlock = self.wlock()
1624 lock = self.lock() # for recent changelog (see issue4368)
1627 lock = self.lock() # for recent changelog (see issue4368)
1625
1628
1626 wctx = self[None]
1629 wctx = self[None]
1627 merge = len(wctx.parents()) > 1
1630 merge = len(wctx.parents()) > 1
1628
1631
1629 if not force and merge and not match.always():
1632 if not force and merge and not match.always():
1630 raise error.Abort(_('cannot partially commit a merge '
1633 raise error.Abort(_('cannot partially commit a merge '
1631 '(do not specify files or patterns)'))
1634 '(do not specify files or patterns)'))
1632
1635
1633 status = self.status(match=match, clean=force)
1636 status = self.status(match=match, clean=force)
1634 if force:
1637 if force:
1635 status.modified.extend(status.clean) # mq may commit clean files
1638 status.modified.extend(status.clean) # mq may commit clean files
1636
1639
1637 # check subrepos
1640 # check subrepos
1638 subs = []
1641 subs = []
1639 commitsubs = set()
1642 commitsubs = set()
1640 newstate = wctx.substate.copy()
1643 newstate = wctx.substate.copy()
1641 # only manage subrepos and .hgsubstate if .hgsub is present
1644 # only manage subrepos and .hgsubstate if .hgsub is present
1642 if '.hgsub' in wctx:
1645 if '.hgsub' in wctx:
1643 # we'll decide whether to track this ourselves, thanks
1646 # we'll decide whether to track this ourselves, thanks
1644 for c in status.modified, status.added, status.removed:
1647 for c in status.modified, status.added, status.removed:
1645 if '.hgsubstate' in c:
1648 if '.hgsubstate' in c:
1646 c.remove('.hgsubstate')
1649 c.remove('.hgsubstate')
1647
1650
1648 # compare current state to last committed state
1651 # compare current state to last committed state
1649 # build new substate based on last committed state
1652 # build new substate based on last committed state
1650 oldstate = wctx.p1().substate
1653 oldstate = wctx.p1().substate
1651 for s in sorted(newstate.keys()):
1654 for s in sorted(newstate.keys()):
1652 if not match(s):
1655 if not match(s):
1653 # ignore working copy, use old state if present
1656 # ignore working copy, use old state if present
1654 if s in oldstate:
1657 if s in oldstate:
1655 newstate[s] = oldstate[s]
1658 newstate[s] = oldstate[s]
1656 continue
1659 continue
1657 if not force:
1660 if not force:
1658 raise error.Abort(
1661 raise error.Abort(
1659 _("commit with new subrepo %s excluded") % s)
1662 _("commit with new subrepo %s excluded") % s)
1660 dirtyreason = wctx.sub(s).dirtyreason(True)
1663 dirtyreason = wctx.sub(s).dirtyreason(True)
1661 if dirtyreason:
1664 if dirtyreason:
1662 if not self.ui.configbool('ui', 'commitsubrepos'):
1665 if not self.ui.configbool('ui', 'commitsubrepos'):
1663 raise error.Abort(dirtyreason,
1666 raise error.Abort(dirtyreason,
1664 hint=_("use --subrepos for recursive commit"))
1667 hint=_("use --subrepos for recursive commit"))
1665 subs.append(s)
1668 subs.append(s)
1666 commitsubs.add(s)
1669 commitsubs.add(s)
1667 else:
1670 else:
1668 bs = wctx.sub(s).basestate()
1671 bs = wctx.sub(s).basestate()
1669 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1672 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1670 if oldstate.get(s, (None, None, None))[1] != bs:
1673 if oldstate.get(s, (None, None, None))[1] != bs:
1671 subs.append(s)
1674 subs.append(s)
1672
1675
1673 # check for removed subrepos
1676 # check for removed subrepos
1674 for p in wctx.parents():
1677 for p in wctx.parents():
1675 r = [s for s in p.substate if s not in newstate]
1678 r = [s for s in p.substate if s not in newstate]
1676 subs += [s for s in r if match(s)]
1679 subs += [s for s in r if match(s)]
1677 if subs:
1680 if subs:
1678 if (not match('.hgsub') and
1681 if (not match('.hgsub') and
1679 '.hgsub' in (wctx.modified() + wctx.added())):
1682 '.hgsub' in (wctx.modified() + wctx.added())):
1680 raise error.Abort(
1683 raise error.Abort(
1681 _("can't commit subrepos without .hgsub"))
1684 _("can't commit subrepos without .hgsub"))
1682 status.modified.insert(0, '.hgsubstate')
1685 status.modified.insert(0, '.hgsubstate')
1683
1686
1684 elif '.hgsub' in status.removed:
1687 elif '.hgsub' in status.removed:
1685 # clean up .hgsubstate when .hgsub is removed
1688 # clean up .hgsubstate when .hgsub is removed
1686 if ('.hgsubstate' in wctx and
1689 if ('.hgsubstate' in wctx and
1687 '.hgsubstate' not in (status.modified + status.added +
1690 '.hgsubstate' not in (status.modified + status.added +
1688 status.removed)):
1691 status.removed)):
1689 status.removed.insert(0, '.hgsubstate')
1692 status.removed.insert(0, '.hgsubstate')
1690
1693
1691 # make sure all explicit patterns are matched
1694 # make sure all explicit patterns are matched
1692 if not force:
1695 if not force:
1693 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1696 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1694
1697
1695 cctx = context.workingcommitctx(self, status,
1698 cctx = context.workingcommitctx(self, status,
1696 text, user, date, extra)
1699 text, user, date, extra)
1697
1700
1698 # internal config: ui.allowemptycommit
1701 # internal config: ui.allowemptycommit
1699 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1702 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1700 or extra.get('close') or merge or cctx.files()
1703 or extra.get('close') or merge or cctx.files()
1701 or self.ui.configbool('ui', 'allowemptycommit'))
1704 or self.ui.configbool('ui', 'allowemptycommit'))
1702 if not allowemptycommit:
1705 if not allowemptycommit:
1703 return None
1706 return None
1704
1707
1705 if merge and cctx.deleted():
1708 if merge and cctx.deleted():
1706 raise error.Abort(_("cannot commit merge with missing files"))
1709 raise error.Abort(_("cannot commit merge with missing files"))
1707
1710
1708 ms = mergemod.mergestate.read(self)
1711 ms = mergemod.mergestate.read(self)
1709 mergeutil.checkunresolved(ms)
1712 mergeutil.checkunresolved(ms)
1710
1713
1711 if editor:
1714 if editor:
1712 cctx._text = editor(self, cctx, subs)
1715 cctx._text = editor(self, cctx, subs)
1713 edited = (text != cctx._text)
1716 edited = (text != cctx._text)
1714
1717
1715 # Save commit message in case this transaction gets rolled back
1718 # Save commit message in case this transaction gets rolled back
1716 # (e.g. by a pretxncommit hook). Leave the content alone on
1719 # (e.g. by a pretxncommit hook). Leave the content alone on
1717 # the assumption that the user will use the same editor again.
1720 # the assumption that the user will use the same editor again.
1718 msgfn = self.savecommitmessage(cctx._text)
1721 msgfn = self.savecommitmessage(cctx._text)
1719
1722
1720 # commit subs and write new state
1723 # commit subs and write new state
1721 if subs:
1724 if subs:
1722 for s in sorted(commitsubs):
1725 for s in sorted(commitsubs):
1723 sub = wctx.sub(s)
1726 sub = wctx.sub(s)
1724 self.ui.status(_('committing subrepository %s\n') %
1727 self.ui.status(_('committing subrepository %s\n') %
1725 subrepo.subrelpath(sub))
1728 subrepo.subrelpath(sub))
1726 sr = sub.commit(cctx._text, user, date)
1729 sr = sub.commit(cctx._text, user, date)
1727 newstate[s] = (newstate[s][0], sr)
1730 newstate[s] = (newstate[s][0], sr)
1728 subrepo.writestate(self, newstate)
1731 subrepo.writestate(self, newstate)
1729
1732
1730 p1, p2 = self.dirstate.parents()
1733 p1, p2 = self.dirstate.parents()
1731 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1734 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1732 try:
1735 try:
1733 self.hook("precommit", throw=True, parent1=hookp1,
1736 self.hook("precommit", throw=True, parent1=hookp1,
1734 parent2=hookp2)
1737 parent2=hookp2)
1735 tr = self.transaction('commit')
1738 tr = self.transaction('commit')
1736 ret = self.commitctx(cctx, True)
1739 ret = self.commitctx(cctx, True)
1737 except: # re-raises
1740 except: # re-raises
1738 if edited:
1741 if edited:
1739 self.ui.write(
1742 self.ui.write(
1740 _('note: commit message saved in %s\n') % msgfn)
1743 _('note: commit message saved in %s\n') % msgfn)
1741 raise
1744 raise
1742 # update bookmarks, dirstate and mergestate
1745 # update bookmarks, dirstate and mergestate
1743 bookmarks.update(self, [p1, p2], ret)
1746 bookmarks.update(self, [p1, p2], ret)
1744 cctx.markcommitted(ret)
1747 cctx.markcommitted(ret)
1745 ms.reset()
1748 ms.reset()
1746 tr.close()
1749 tr.close()
1747
1750
1748 finally:
1751 finally:
1749 lockmod.release(tr, lock, wlock)
1752 lockmod.release(tr, lock, wlock)
1750
1753
1751 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1754 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1752 # hack for command that use a temporary commit (eg: histedit)
1755 # hack for command that use a temporary commit (eg: histedit)
1753 # temporary commit got stripped before hook release
1756 # temporary commit got stripped before hook release
1754 if self.changelog.hasnode(ret):
1757 if self.changelog.hasnode(ret):
1755 self.hook("commit", node=node, parent1=parent1,
1758 self.hook("commit", node=node, parent1=parent1,
1756 parent2=parent2)
1759 parent2=parent2)
1757 self._afterlock(commithook)
1760 self._afterlock(commithook)
1758 return ret
1761 return ret
1759
1762
1760 @unfilteredmethod
1763 @unfilteredmethod
1761 def commitctx(self, ctx, error=False):
1764 def commitctx(self, ctx, error=False):
1762 """Add a new revision to current repository.
1765 """Add a new revision to current repository.
1763 Revision information is passed via the context argument.
1766 Revision information is passed via the context argument.
1764 """
1767 """
1765
1768
1766 tr = None
1769 tr = None
1767 p1, p2 = ctx.p1(), ctx.p2()
1770 p1, p2 = ctx.p1(), ctx.p2()
1768 user = ctx.user()
1771 user = ctx.user()
1769
1772
1770 lock = self.lock()
1773 lock = self.lock()
1771 try:
1774 try:
1772 tr = self.transaction("commit")
1775 tr = self.transaction("commit")
1773 trp = weakref.proxy(tr)
1776 trp = weakref.proxy(tr)
1774
1777
1775 if ctx.manifestnode():
1778 if ctx.manifestnode():
1776 # reuse an existing manifest revision
1779 # reuse an existing manifest revision
1777 mn = ctx.manifestnode()
1780 mn = ctx.manifestnode()
1778 files = ctx.files()
1781 files = ctx.files()
1779 elif ctx.files():
1782 elif ctx.files():
1780 m1ctx = p1.manifestctx()
1783 m1ctx = p1.manifestctx()
1781 m2ctx = p2.manifestctx()
1784 m2ctx = p2.manifestctx()
1782 mctx = m1ctx.copy()
1785 mctx = m1ctx.copy()
1783
1786
1784 m = mctx.read()
1787 m = mctx.read()
1785 m1 = m1ctx.read()
1788 m1 = m1ctx.read()
1786 m2 = m2ctx.read()
1789 m2 = m2ctx.read()
1787
1790
1788 # check in files
1791 # check in files
1789 added = []
1792 added = []
1790 changed = []
1793 changed = []
1791 removed = list(ctx.removed())
1794 removed = list(ctx.removed())
1792 linkrev = len(self)
1795 linkrev = len(self)
1793 self.ui.note(_("committing files:\n"))
1796 self.ui.note(_("committing files:\n"))
1794 for f in sorted(ctx.modified() + ctx.added()):
1797 for f in sorted(ctx.modified() + ctx.added()):
1795 self.ui.note(f + "\n")
1798 self.ui.note(f + "\n")
1796 try:
1799 try:
1797 fctx = ctx[f]
1800 fctx = ctx[f]
1798 if fctx is None:
1801 if fctx is None:
1799 removed.append(f)
1802 removed.append(f)
1800 else:
1803 else:
1801 added.append(f)
1804 added.append(f)
1802 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1805 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1803 trp, changed)
1806 trp, changed)
1804 m.setflag(f, fctx.flags())
1807 m.setflag(f, fctx.flags())
1805 except OSError as inst:
1808 except OSError as inst:
1806 self.ui.warn(_("trouble committing %s!\n") % f)
1809 self.ui.warn(_("trouble committing %s!\n") % f)
1807 raise
1810 raise
1808 except IOError as inst:
1811 except IOError as inst:
1809 errcode = getattr(inst, 'errno', errno.ENOENT)
1812 errcode = getattr(inst, 'errno', errno.ENOENT)
1810 if error or errcode and errcode != errno.ENOENT:
1813 if error or errcode and errcode != errno.ENOENT:
1811 self.ui.warn(_("trouble committing %s!\n") % f)
1814 self.ui.warn(_("trouble committing %s!\n") % f)
1812 raise
1815 raise
1813
1816
1814 # update manifest
1817 # update manifest
1815 self.ui.note(_("committing manifest\n"))
1818 self.ui.note(_("committing manifest\n"))
1816 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1819 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1817 drop = [f for f in removed if f in m]
1820 drop = [f for f in removed if f in m]
1818 for f in drop:
1821 for f in drop:
1819 del m[f]
1822 del m[f]
1820 mn = mctx.write(trp, linkrev,
1823 mn = mctx.write(trp, linkrev,
1821 p1.manifestnode(), p2.manifestnode(),
1824 p1.manifestnode(), p2.manifestnode(),
1822 added, drop)
1825 added, drop)
1823 files = changed + removed
1826 files = changed + removed
1824 else:
1827 else:
1825 mn = p1.manifestnode()
1828 mn = p1.manifestnode()
1826 files = []
1829 files = []
1827
1830
1828 # update changelog
1831 # update changelog
1829 self.ui.note(_("committing changelog\n"))
1832 self.ui.note(_("committing changelog\n"))
1830 self.changelog.delayupdate(tr)
1833 self.changelog.delayupdate(tr)
1831 n = self.changelog.add(mn, files, ctx.description(),
1834 n = self.changelog.add(mn, files, ctx.description(),
1832 trp, p1.node(), p2.node(),
1835 trp, p1.node(), p2.node(),
1833 user, ctx.date(), ctx.extra().copy())
1836 user, ctx.date(), ctx.extra().copy())
1834 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1837 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1835 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1838 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1836 parent2=xp2)
1839 parent2=xp2)
1837 # set the new commit is proper phase
1840 # set the new commit is proper phase
1838 targetphase = subrepo.newcommitphase(self.ui, ctx)
1841 targetphase = subrepo.newcommitphase(self.ui, ctx)
1839 if targetphase:
1842 if targetphase:
1840 # retract boundary do not alter parent changeset.
1843 # retract boundary do not alter parent changeset.
1841 # if a parent have higher the resulting phase will
1844 # if a parent have higher the resulting phase will
1842 # be compliant anyway
1845 # be compliant anyway
1843 #
1846 #
1844 # if minimal phase was 0 we don't need to retract anything
1847 # if minimal phase was 0 we don't need to retract anything
1845 phases.retractboundary(self, tr, targetphase, [n])
1848 phases.retractboundary(self, tr, targetphase, [n])
1846 tr.close()
1849 tr.close()
1847 return n
1850 return n
1848 finally:
1851 finally:
1849 if tr:
1852 if tr:
1850 tr.release()
1853 tr.release()
1851 lock.release()
1854 lock.release()
1852
1855
1853 @unfilteredmethod
1856 @unfilteredmethod
1854 def destroying(self):
1857 def destroying(self):
1855 '''Inform the repository that nodes are about to be destroyed.
1858 '''Inform the repository that nodes are about to be destroyed.
1856 Intended for use by strip and rollback, so there's a common
1859 Intended for use by strip and rollback, so there's a common
1857 place for anything that has to be done before destroying history.
1860 place for anything that has to be done before destroying history.
1858
1861
1859 This is mostly useful for saving state that is in memory and waiting
1862 This is mostly useful for saving state that is in memory and waiting
1860 to be flushed when the current lock is released. Because a call to
1863 to be flushed when the current lock is released. Because a call to
1861 destroyed is imminent, the repo will be invalidated causing those
1864 destroyed is imminent, the repo will be invalidated causing those
1862 changes to stay in memory (waiting for the next unlock), or vanish
1865 changes to stay in memory (waiting for the next unlock), or vanish
1863 completely.
1866 completely.
1864 '''
1867 '''
1865 # When using the same lock to commit and strip, the phasecache is left
1868 # When using the same lock to commit and strip, the phasecache is left
1866 # dirty after committing. Then when we strip, the repo is invalidated,
1869 # dirty after committing. Then when we strip, the repo is invalidated,
1867 # causing those changes to disappear.
1870 # causing those changes to disappear.
1868 if '_phasecache' in vars(self):
1871 if '_phasecache' in vars(self):
1869 self._phasecache.write()
1872 self._phasecache.write()
1870
1873
1871 @unfilteredmethod
1874 @unfilteredmethod
1872 def destroyed(self):
1875 def destroyed(self):
1873 '''Inform the repository that nodes have been destroyed.
1876 '''Inform the repository that nodes have been destroyed.
1874 Intended for use by strip and rollback, so there's a common
1877 Intended for use by strip and rollback, so there's a common
1875 place for anything that has to be done after destroying history.
1878 place for anything that has to be done after destroying history.
1876 '''
1879 '''
1877 # When one tries to:
1880 # When one tries to:
1878 # 1) destroy nodes thus calling this method (e.g. strip)
1881 # 1) destroy nodes thus calling this method (e.g. strip)
1879 # 2) use phasecache somewhere (e.g. commit)
1882 # 2) use phasecache somewhere (e.g. commit)
1880 #
1883 #
1881 # then 2) will fail because the phasecache contains nodes that were
1884 # then 2) will fail because the phasecache contains nodes that were
1882 # removed. We can either remove phasecache from the filecache,
1885 # removed. We can either remove phasecache from the filecache,
1883 # causing it to reload next time it is accessed, or simply filter
1886 # causing it to reload next time it is accessed, or simply filter
1884 # the removed nodes now and write the updated cache.
1887 # the removed nodes now and write the updated cache.
1885 self._phasecache.filterunknown(self)
1888 self._phasecache.filterunknown(self)
1886 self._phasecache.write()
1889 self._phasecache.write()
1887
1890
1888 # refresh all repository caches
1891 # refresh all repository caches
1889 self.updatecaches()
1892 self.updatecaches()
1890
1893
1891 # Ensure the persistent tag cache is updated. Doing it now
1894 # Ensure the persistent tag cache is updated. Doing it now
1892 # means that the tag cache only has to worry about destroyed
1895 # means that the tag cache only has to worry about destroyed
1893 # heads immediately after a strip/rollback. That in turn
1896 # heads immediately after a strip/rollback. That in turn
1894 # guarantees that "cachetip == currenttip" (comparing both rev
1897 # guarantees that "cachetip == currenttip" (comparing both rev
1895 # and node) always means no nodes have been added or destroyed.
1898 # and node) always means no nodes have been added or destroyed.
1896
1899
1897 # XXX this is suboptimal when qrefresh'ing: we strip the current
1900 # XXX this is suboptimal when qrefresh'ing: we strip the current
1898 # head, refresh the tag cache, then immediately add a new head.
1901 # head, refresh the tag cache, then immediately add a new head.
1899 # But I think doing it this way is necessary for the "instant
1902 # But I think doing it this way is necessary for the "instant
1900 # tag cache retrieval" case to work.
1903 # tag cache retrieval" case to work.
1901 self.invalidate()
1904 self.invalidate()
1902
1905
1903 def walk(self, match, node=None):
1906 def walk(self, match, node=None):
1904 '''
1907 '''
1905 walk recursively through the directory tree or a given
1908 walk recursively through the directory tree or a given
1906 changeset, finding all files matched by the match
1909 changeset, finding all files matched by the match
1907 function
1910 function
1908 '''
1911 '''
1909 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
1912 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
1910 return self[node].walk(match)
1913 return self[node].walk(match)
1911
1914
1912 def status(self, node1='.', node2=None, match=None,
1915 def status(self, node1='.', node2=None, match=None,
1913 ignored=False, clean=False, unknown=False,
1916 ignored=False, clean=False, unknown=False,
1914 listsubrepos=False):
1917 listsubrepos=False):
1915 '''a convenience method that calls node1.status(node2)'''
1918 '''a convenience method that calls node1.status(node2)'''
1916 return self[node1].status(node2, match, ignored, clean, unknown,
1919 return self[node1].status(node2, match, ignored, clean, unknown,
1917 listsubrepos)
1920 listsubrepos)
1918
1921
1919 def addpostdsstatus(self, ps):
1922 def addpostdsstatus(self, ps):
1920 """Add a callback to run within the wlock, at the point at which status
1923 """Add a callback to run within the wlock, at the point at which status
1921 fixups happen.
1924 fixups happen.
1922
1925
1923 On status completion, callback(wctx, status) will be called with the
1926 On status completion, callback(wctx, status) will be called with the
1924 wlock held, unless the dirstate has changed from underneath or the wlock
1927 wlock held, unless the dirstate has changed from underneath or the wlock
1925 couldn't be grabbed.
1928 couldn't be grabbed.
1926
1929
1927 Callbacks should not capture and use a cached copy of the dirstate --
1930 Callbacks should not capture and use a cached copy of the dirstate --
1928 it might change in the meanwhile. Instead, they should access the
1931 it might change in the meanwhile. Instead, they should access the
1929 dirstate via wctx.repo().dirstate.
1932 dirstate via wctx.repo().dirstate.
1930
1933
1931 This list is emptied out after each status run -- extensions should
1934 This list is emptied out after each status run -- extensions should
1932 make sure it adds to this list each time dirstate.status is called.
1935 make sure it adds to this list each time dirstate.status is called.
1933 Extensions should also make sure they don't call this for statuses
1936 Extensions should also make sure they don't call this for statuses
1934 that don't involve the dirstate.
1937 that don't involve the dirstate.
1935 """
1938 """
1936
1939
1937 # The list is located here for uniqueness reasons -- it is actually
1940 # The list is located here for uniqueness reasons -- it is actually
1938 # managed by the workingctx, but that isn't unique per-repo.
1941 # managed by the workingctx, but that isn't unique per-repo.
1939 self._postdsstatus.append(ps)
1942 self._postdsstatus.append(ps)
1940
1943
1941 def postdsstatus(self):
1944 def postdsstatus(self):
1942 """Used by workingctx to get the list of post-dirstate-status hooks."""
1945 """Used by workingctx to get the list of post-dirstate-status hooks."""
1943 return self._postdsstatus
1946 return self._postdsstatus
1944
1947
1945 def clearpostdsstatus(self):
1948 def clearpostdsstatus(self):
1946 """Used by workingctx to clear post-dirstate-status hooks."""
1949 """Used by workingctx to clear post-dirstate-status hooks."""
1947 del self._postdsstatus[:]
1950 del self._postdsstatus[:]
1948
1951
1949 def heads(self, start=None):
1952 def heads(self, start=None):
1950 if start is None:
1953 if start is None:
1951 cl = self.changelog
1954 cl = self.changelog
1952 headrevs = reversed(cl.headrevs())
1955 headrevs = reversed(cl.headrevs())
1953 return [cl.node(rev) for rev in headrevs]
1956 return [cl.node(rev) for rev in headrevs]
1954
1957
1955 heads = self.changelog.heads(start)
1958 heads = self.changelog.heads(start)
1956 # sort the output in rev descending order
1959 # sort the output in rev descending order
1957 return sorted(heads, key=self.changelog.rev, reverse=True)
1960 return sorted(heads, key=self.changelog.rev, reverse=True)
1958
1961
1959 def branchheads(self, branch=None, start=None, closed=False):
1962 def branchheads(self, branch=None, start=None, closed=False):
1960 '''return a (possibly filtered) list of heads for the given branch
1963 '''return a (possibly filtered) list of heads for the given branch
1961
1964
1962 Heads are returned in topological order, from newest to oldest.
1965 Heads are returned in topological order, from newest to oldest.
1963 If branch is None, use the dirstate branch.
1966 If branch is None, use the dirstate branch.
1964 If start is not None, return only heads reachable from start.
1967 If start is not None, return only heads reachable from start.
1965 If closed is True, return heads that are marked as closed as well.
1968 If closed is True, return heads that are marked as closed as well.
1966 '''
1969 '''
1967 if branch is None:
1970 if branch is None:
1968 branch = self[None].branch()
1971 branch = self[None].branch()
1969 branches = self.branchmap()
1972 branches = self.branchmap()
1970 if branch not in branches:
1973 if branch not in branches:
1971 return []
1974 return []
1972 # the cache returns heads ordered lowest to highest
1975 # the cache returns heads ordered lowest to highest
1973 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1976 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1974 if start is not None:
1977 if start is not None:
1975 # filter out the heads that cannot be reached from startrev
1978 # filter out the heads that cannot be reached from startrev
1976 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1979 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1977 bheads = [h for h in bheads if h in fbheads]
1980 bheads = [h for h in bheads if h in fbheads]
1978 return bheads
1981 return bheads
1979
1982
1980 def branches(self, nodes):
1983 def branches(self, nodes):
1981 if not nodes:
1984 if not nodes:
1982 nodes = [self.changelog.tip()]
1985 nodes = [self.changelog.tip()]
1983 b = []
1986 b = []
1984 for n in nodes:
1987 for n in nodes:
1985 t = n
1988 t = n
1986 while True:
1989 while True:
1987 p = self.changelog.parents(n)
1990 p = self.changelog.parents(n)
1988 if p[1] != nullid or p[0] == nullid:
1991 if p[1] != nullid or p[0] == nullid:
1989 b.append((t, n, p[0], p[1]))
1992 b.append((t, n, p[0], p[1]))
1990 break
1993 break
1991 n = p[0]
1994 n = p[0]
1992 return b
1995 return b
1993
1996
1994 def between(self, pairs):
1997 def between(self, pairs):
1995 r = []
1998 r = []
1996
1999
1997 for top, bottom in pairs:
2000 for top, bottom in pairs:
1998 n, l, i = top, [], 0
2001 n, l, i = top, [], 0
1999 f = 1
2002 f = 1
2000
2003
2001 while n != bottom and n != nullid:
2004 while n != bottom and n != nullid:
2002 p = self.changelog.parents(n)[0]
2005 p = self.changelog.parents(n)[0]
2003 if i == f:
2006 if i == f:
2004 l.append(n)
2007 l.append(n)
2005 f = f * 2
2008 f = f * 2
2006 n = p
2009 n = p
2007 i += 1
2010 i += 1
2008
2011
2009 r.append(l)
2012 r.append(l)
2010
2013
2011 return r
2014 return r
2012
2015
2013 def checkpush(self, pushop):
2016 def checkpush(self, pushop):
2014 """Extensions can override this function if additional checks have
2017 """Extensions can override this function if additional checks have
2015 to be performed before pushing, or call it if they override push
2018 to be performed before pushing, or call it if they override push
2016 command.
2019 command.
2017 """
2020 """
2018 pass
2021 pass
2019
2022
2020 @unfilteredpropertycache
2023 @unfilteredpropertycache
2021 def prepushoutgoinghooks(self):
2024 def prepushoutgoinghooks(self):
2022 """Return util.hooks consists of a pushop with repo, remote, outgoing
2025 """Return util.hooks consists of a pushop with repo, remote, outgoing
2023 methods, which are called before pushing changesets.
2026 methods, which are called before pushing changesets.
2024 """
2027 """
2025 return util.hooks()
2028 return util.hooks()
2026
2029
2027 def pushkey(self, namespace, key, old, new):
2030 def pushkey(self, namespace, key, old, new):
2028 try:
2031 try:
2029 tr = self.currenttransaction()
2032 tr = self.currenttransaction()
2030 hookargs = {}
2033 hookargs = {}
2031 if tr is not None:
2034 if tr is not None:
2032 hookargs.update(tr.hookargs)
2035 hookargs.update(tr.hookargs)
2033 hookargs['namespace'] = namespace
2036 hookargs['namespace'] = namespace
2034 hookargs['key'] = key
2037 hookargs['key'] = key
2035 hookargs['old'] = old
2038 hookargs['old'] = old
2036 hookargs['new'] = new
2039 hookargs['new'] = new
2037 self.hook('prepushkey', throw=True, **hookargs)
2040 self.hook('prepushkey', throw=True, **hookargs)
2038 except error.HookAbort as exc:
2041 except error.HookAbort as exc:
2039 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2042 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2040 if exc.hint:
2043 if exc.hint:
2041 self.ui.write_err(_("(%s)\n") % exc.hint)
2044 self.ui.write_err(_("(%s)\n") % exc.hint)
2042 return False
2045 return False
2043 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2046 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2044 ret = pushkey.push(self, namespace, key, old, new)
2047 ret = pushkey.push(self, namespace, key, old, new)
2045 def runhook():
2048 def runhook():
2046 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2049 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2047 ret=ret)
2050 ret=ret)
2048 self._afterlock(runhook)
2051 self._afterlock(runhook)
2049 return ret
2052 return ret
2050
2053
2051 def listkeys(self, namespace):
2054 def listkeys(self, namespace):
2052 self.hook('prelistkeys', throw=True, namespace=namespace)
2055 self.hook('prelistkeys', throw=True, namespace=namespace)
2053 self.ui.debug('listing keys for "%s"\n' % namespace)
2056 self.ui.debug('listing keys for "%s"\n' % namespace)
2054 values = pushkey.list(self, namespace)
2057 values = pushkey.list(self, namespace)
2055 self.hook('listkeys', namespace=namespace, values=values)
2058 self.hook('listkeys', namespace=namespace, values=values)
2056 return values
2059 return values
2057
2060
2058 def debugwireargs(self, one, two, three=None, four=None, five=None):
2061 def debugwireargs(self, one, two, three=None, four=None, five=None):
2059 '''used to test argument passing over the wire'''
2062 '''used to test argument passing over the wire'''
2060 return "%s %s %s %s %s" % (one, two, three, four, five)
2063 return "%s %s %s %s %s" % (one, two, three, four, five)
2061
2064
2062 def savecommitmessage(self, text):
2065 def savecommitmessage(self, text):
2063 fp = self.vfs('last-message.txt', 'wb')
2066 fp = self.vfs('last-message.txt', 'wb')
2064 try:
2067 try:
2065 fp.write(text)
2068 fp.write(text)
2066 finally:
2069 finally:
2067 fp.close()
2070 fp.close()
2068 return self.pathto(fp.name[len(self.root) + 1:])
2071 return self.pathto(fp.name[len(self.root) + 1:])
2069
2072
2070 # used to avoid circular references so destructors work
2073 # used to avoid circular references so destructors work
2071 def aftertrans(files):
2074 def aftertrans(files):
2072 renamefiles = [tuple(t) for t in files]
2075 renamefiles = [tuple(t) for t in files]
2073 def a():
2076 def a():
2074 for vfs, src, dest in renamefiles:
2077 for vfs, src, dest in renamefiles:
2075 # if src and dest refer to a same file, vfs.rename is a no-op,
2078 # if src and dest refer to a same file, vfs.rename is a no-op,
2076 # leaving both src and dest on disk. delete dest to make sure
2079 # leaving both src and dest on disk. delete dest to make sure
2077 # the rename couldn't be such a no-op.
2080 # the rename couldn't be such a no-op.
2078 vfs.tryunlink(dest)
2081 vfs.tryunlink(dest)
2079 try:
2082 try:
2080 vfs.rename(src, dest)
2083 vfs.rename(src, dest)
2081 except OSError: # journal file does not yet exist
2084 except OSError: # journal file does not yet exist
2082 pass
2085 pass
2083 return a
2086 return a
2084
2087
2085 def undoname(fn):
2088 def undoname(fn):
2086 base, name = os.path.split(fn)
2089 base, name = os.path.split(fn)
2087 assert name.startswith('journal')
2090 assert name.startswith('journal')
2088 return os.path.join(base, name.replace('journal', 'undo', 1))
2091 return os.path.join(base, name.replace('journal', 'undo', 1))
2089
2092
2090 def instance(ui, path, create):
2093 def instance(ui, path, create):
2091 return localrepository(ui, util.urllocalpath(path), create)
2094 return localrepository(ui, util.urllocalpath(path), create)
2092
2095
2093 def islocal(path):
2096 def islocal(path):
2094 return True
2097 return True
2095
2098
2096 def newreporequirements(repo):
2099 def newreporequirements(repo):
2097 """Determine the set of requirements for a new local repository.
2100 """Determine the set of requirements for a new local repository.
2098
2101
2099 Extensions can wrap this function to specify custom requirements for
2102 Extensions can wrap this function to specify custom requirements for
2100 new repositories.
2103 new repositories.
2101 """
2104 """
2102 ui = repo.ui
2105 ui = repo.ui
2103 requirements = {'revlogv1'}
2106 requirements = {'revlogv1'}
2104 if ui.configbool('format', 'usestore'):
2107 if ui.configbool('format', 'usestore'):
2105 requirements.add('store')
2108 requirements.add('store')
2106 if ui.configbool('format', 'usefncache'):
2109 if ui.configbool('format', 'usefncache'):
2107 requirements.add('fncache')
2110 requirements.add('fncache')
2108 if ui.configbool('format', 'dotencode'):
2111 if ui.configbool('format', 'dotencode'):
2109 requirements.add('dotencode')
2112 requirements.add('dotencode')
2110
2113
2111 compengine = ui.config('experimental', 'format.compression', 'zlib')
2114 compengine = ui.config('experimental', 'format.compression', 'zlib')
2112 if compengine not in util.compengines:
2115 if compengine not in util.compengines:
2113 raise error.Abort(_('compression engine %s defined by '
2116 raise error.Abort(_('compression engine %s defined by '
2114 'experimental.format.compression not available') %
2117 'experimental.format.compression not available') %
2115 compengine,
2118 compengine,
2116 hint=_('run "hg debuginstall" to list available '
2119 hint=_('run "hg debuginstall" to list available '
2117 'compression engines'))
2120 'compression engines'))
2118
2121
2119 # zlib is the historical default and doesn't need an explicit requirement.
2122 # zlib is the historical default and doesn't need an explicit requirement.
2120 if compengine != 'zlib':
2123 if compengine != 'zlib':
2121 requirements.add('exp-compression-%s' % compengine)
2124 requirements.add('exp-compression-%s' % compengine)
2122
2125
2123 if scmutil.gdinitconfig(ui):
2126 if scmutil.gdinitconfig(ui):
2124 requirements.add('generaldelta')
2127 requirements.add('generaldelta')
2125 if ui.configbool('experimental', 'treemanifest', False):
2128 if ui.configbool('experimental', 'treemanifest', False):
2126 requirements.add('treemanifest')
2129 requirements.add('treemanifest')
2127 if ui.configbool('experimental', 'manifestv2', False):
2130 if ui.configbool('experimental', 'manifestv2', False):
2128 requirements.add('manifestv2')
2131 requirements.add('manifestv2')
2129
2132
2130 revlogv2 = ui.config('experimental', 'revlogv2')
2133 revlogv2 = ui.config('experimental', 'revlogv2')
2131 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2134 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2132 requirements.remove('revlogv1')
2135 requirements.remove('revlogv1')
2133 # generaldelta is implied by revlogv2.
2136 # generaldelta is implied by revlogv2.
2134 requirements.discard('generaldelta')
2137 requirements.discard('generaldelta')
2135 requirements.add(REVLOGV2_REQUIREMENT)
2138 requirements.add(REVLOGV2_REQUIREMENT)
2136
2139
2137 return requirements
2140 return requirements
@@ -1,2054 +1,2064 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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import re
10 import re
11
11
12 from .i18n import _
12 from .i18n import _
13 from . import (
13 from . import (
14 dagop,
14 dagop,
15 destutil,
15 destutil,
16 encoding,
16 encoding,
17 error,
17 error,
18 hbisect,
18 hbisect,
19 match as matchmod,
19 match as matchmod,
20 node,
20 node,
21 obsolete as obsmod,
21 obsolete as obsmod,
22 pathutil,
22 pathutil,
23 phases,
23 phases,
24 registrar,
24 registrar,
25 repoview,
25 repoview,
26 revsetlang,
26 revsetlang,
27 scmutil,
27 scmutil,
28 smartset,
28 smartset,
29 util,
29 util,
30 )
30 )
31
31
32 # helpers for processing parsed tree
32 # helpers for processing parsed tree
33 getsymbol = revsetlang.getsymbol
33 getsymbol = revsetlang.getsymbol
34 getstring = revsetlang.getstring
34 getstring = revsetlang.getstring
35 getinteger = revsetlang.getinteger
35 getinteger = revsetlang.getinteger
36 getboolean = revsetlang.getboolean
36 getboolean = revsetlang.getboolean
37 getlist = revsetlang.getlist
37 getlist = revsetlang.getlist
38 getrange = revsetlang.getrange
38 getrange = revsetlang.getrange
39 getargs = revsetlang.getargs
39 getargs = revsetlang.getargs
40 getargsdict = revsetlang.getargsdict
40 getargsdict = revsetlang.getargsdict
41
41
42 # constants used as an argument of match() and matchany()
42 # constants used as an argument of match() and matchany()
43 anyorder = revsetlang.anyorder
43 anyorder = revsetlang.anyorder
44 defineorder = revsetlang.defineorder
44 defineorder = revsetlang.defineorder
45 followorder = revsetlang.followorder
45 followorder = revsetlang.followorder
46
46
47 baseset = smartset.baseset
47 baseset = smartset.baseset
48 generatorset = smartset.generatorset
48 generatorset = smartset.generatorset
49 spanset = smartset.spanset
49 spanset = smartset.spanset
50 fullreposet = smartset.fullreposet
50 fullreposet = smartset.fullreposet
51
51
52 # helpers
52 # helpers
53
53
54 def getset(repo, subset, x):
54 def getset(repo, subset, x):
55 if not x:
55 if not x:
56 raise error.ParseError(_("missing argument"))
56 raise error.ParseError(_("missing argument"))
57 return methods[x[0]](repo, subset, *x[1:])
57 return methods[x[0]](repo, subset, *x[1:])
58
58
59 def _getrevsource(repo, r):
59 def _getrevsource(repo, r):
60 extra = repo[r].extra()
60 extra = repo[r].extra()
61 for label in ('source', 'transplant_source', 'rebase_source'):
61 for label in ('source', 'transplant_source', 'rebase_source'):
62 if label in extra:
62 if label in extra:
63 try:
63 try:
64 return repo[extra[label]].rev()
64 return repo[extra[label]].rev()
65 except error.RepoLookupError:
65 except error.RepoLookupError:
66 pass
66 pass
67 return None
67 return None
68
68
69 # operator methods
69 # operator methods
70
70
71 def stringset(repo, subset, x):
71 def stringset(repo, subset, x):
72 x = scmutil.intrev(repo[x])
72 x = scmutil.intrev(repo[x])
73 if (x in subset
73 if (x in subset
74 or x == node.nullrev and isinstance(subset, fullreposet)):
74 or x == node.nullrev and isinstance(subset, fullreposet)):
75 return baseset([x])
75 return baseset([x])
76 return baseset()
76 return baseset()
77
77
78 def rangeset(repo, subset, x, y, order):
78 def rangeset(repo, subset, x, y, order):
79 m = getset(repo, fullreposet(repo), x)
79 m = getset(repo, fullreposet(repo), x)
80 n = getset(repo, fullreposet(repo), y)
80 n = getset(repo, fullreposet(repo), y)
81
81
82 if not m or not n:
82 if not m or not n:
83 return baseset()
83 return baseset()
84 return _makerangeset(repo, subset, m.first(), n.last(), order)
84 return _makerangeset(repo, subset, m.first(), n.last(), order)
85
85
86 def rangeall(repo, subset, x, order):
86 def rangeall(repo, subset, x, order):
87 assert x is None
87 assert x is None
88 return _makerangeset(repo, subset, 0, len(repo) - 1, order)
88 return _makerangeset(repo, subset, 0, len(repo) - 1, order)
89
89
90 def rangepre(repo, subset, y, order):
90 def rangepre(repo, subset, y, order):
91 # ':y' can't be rewritten to '0:y' since '0' may be hidden
91 # ':y' can't be rewritten to '0:y' since '0' may be hidden
92 n = getset(repo, fullreposet(repo), y)
92 n = getset(repo, fullreposet(repo), y)
93 if not n:
93 if not n:
94 return baseset()
94 return baseset()
95 return _makerangeset(repo, subset, 0, n.last(), order)
95 return _makerangeset(repo, subset, 0, n.last(), order)
96
96
97 def rangepost(repo, subset, x, order):
97 def rangepost(repo, subset, x, order):
98 m = getset(repo, fullreposet(repo), x)
98 m = getset(repo, fullreposet(repo), x)
99 if not m:
99 if not m:
100 return baseset()
100 return baseset()
101 return _makerangeset(repo, subset, m.first(), len(repo) - 1, order)
101 return _makerangeset(repo, subset, m.first(), len(repo) - 1, order)
102
102
103 def _makerangeset(repo, subset, m, n, order):
103 def _makerangeset(repo, subset, m, n, order):
104 if m == n:
104 if m == n:
105 r = baseset([m])
105 r = baseset([m])
106 elif n == node.wdirrev:
106 elif n == node.wdirrev:
107 r = spanset(repo, m, len(repo)) + baseset([n])
107 r = spanset(repo, m, len(repo)) + baseset([n])
108 elif m == node.wdirrev:
108 elif m == node.wdirrev:
109 r = baseset([m]) + spanset(repo, len(repo) - 1, n - 1)
109 r = baseset([m]) + spanset(repo, len(repo) - 1, n - 1)
110 elif m < n:
110 elif m < n:
111 r = spanset(repo, m, n + 1)
111 r = spanset(repo, m, n + 1)
112 else:
112 else:
113 r = spanset(repo, m, n - 1)
113 r = spanset(repo, m, n - 1)
114
114
115 if order == defineorder:
115 if order == defineorder:
116 return r & subset
116 return r & subset
117 else:
117 else:
118 # carrying the sorting over when possible would be more efficient
118 # carrying the sorting over when possible would be more efficient
119 return subset & r
119 return subset & r
120
120
121 def dagrange(repo, subset, x, y, order):
121 def dagrange(repo, subset, x, y, order):
122 r = fullreposet(repo)
122 r = fullreposet(repo)
123 xs = dagop.reachableroots(repo, getset(repo, r, x), getset(repo, r, y),
123 xs = dagop.reachableroots(repo, getset(repo, r, x), getset(repo, r, y),
124 includepath=True)
124 includepath=True)
125 return subset & xs
125 return subset & xs
126
126
127 def andset(repo, subset, x, y, order):
127 def andset(repo, subset, x, y, order):
128 return getset(repo, getset(repo, subset, x), y)
128 return getset(repo, getset(repo, subset, x), y)
129
129
130 def differenceset(repo, subset, x, y, order):
130 def differenceset(repo, subset, x, y, order):
131 return getset(repo, subset, x) - getset(repo, subset, y)
131 return getset(repo, subset, x) - getset(repo, subset, y)
132
132
133 def _orsetlist(repo, subset, xs):
133 def _orsetlist(repo, subset, xs):
134 assert xs
134 assert xs
135 if len(xs) == 1:
135 if len(xs) == 1:
136 return getset(repo, subset, xs[0])
136 return getset(repo, subset, xs[0])
137 p = len(xs) // 2
137 p = len(xs) // 2
138 a = _orsetlist(repo, subset, xs[:p])
138 a = _orsetlist(repo, subset, xs[:p])
139 b = _orsetlist(repo, subset, xs[p:])
139 b = _orsetlist(repo, subset, xs[p:])
140 return a + b
140 return a + b
141
141
142 def orset(repo, subset, x, order):
142 def orset(repo, subset, x, order):
143 xs = getlist(x)
143 xs = getlist(x)
144 if order == followorder:
144 if order == followorder:
145 # slow path to take the subset order
145 # slow path to take the subset order
146 return subset & _orsetlist(repo, fullreposet(repo), xs)
146 return subset & _orsetlist(repo, fullreposet(repo), xs)
147 else:
147 else:
148 return _orsetlist(repo, subset, xs)
148 return _orsetlist(repo, subset, xs)
149
149
150 def notset(repo, subset, x, order):
150 def notset(repo, subset, x, order):
151 return subset - getset(repo, subset, x)
151 return subset - getset(repo, subset, x)
152
152
153 def listset(repo, subset, *xs):
153 def listset(repo, subset, *xs):
154 raise error.ParseError(_("can't use a list in this context"),
154 raise error.ParseError(_("can't use a list in this context"),
155 hint=_('see hg help "revsets.x or y"'))
155 hint=_('see hg help "revsets.x or y"'))
156
156
157 def keyvaluepair(repo, subset, k, v):
157 def keyvaluepair(repo, subset, k, v):
158 raise error.ParseError(_("can't use a key-value pair in this context"))
158 raise error.ParseError(_("can't use a key-value pair in this context"))
159
159
160 def func(repo, subset, a, b, order):
160 def func(repo, subset, a, b, order):
161 f = getsymbol(a)
161 f = getsymbol(a)
162 if f in symbols:
162 if f in symbols:
163 func = symbols[f]
163 func = symbols[f]
164 if getattr(func, '_takeorder', False):
164 if getattr(func, '_takeorder', False):
165 return func(repo, subset, b, order)
165 return func(repo, subset, b, order)
166 return func(repo, subset, b)
166 return func(repo, subset, b)
167
167
168 keep = lambda fn: getattr(fn, '__doc__', None) is not None
168 keep = lambda fn: getattr(fn, '__doc__', None) is not None
169
169
170 syms = [s for (s, fn) in symbols.items() if keep(fn)]
170 syms = [s for (s, fn) in symbols.items() if keep(fn)]
171 raise error.UnknownIdentifier(f, syms)
171 raise error.UnknownIdentifier(f, syms)
172
172
173 # functions
173 # functions
174
174
175 # symbols are callables like:
175 # symbols are callables like:
176 # fn(repo, subset, x)
176 # fn(repo, subset, x)
177 # with:
177 # with:
178 # repo - current repository instance
178 # repo - current repository instance
179 # subset - of revisions to be examined
179 # subset - of revisions to be examined
180 # x - argument in tree form
180 # x - argument in tree form
181 symbols = {}
181 symbols = {}
182
182
183 # symbols which can't be used for a DoS attack for any given input
183 # symbols which can't be used for a DoS attack for any given input
184 # (e.g. those which accept regexes as plain strings shouldn't be included)
184 # (e.g. those which accept regexes as plain strings shouldn't be included)
185 # functions that just return a lot of changesets (like all) don't count here
185 # functions that just return a lot of changesets (like all) don't count here
186 safesymbols = set()
186 safesymbols = set()
187
187
188 predicate = registrar.revsetpredicate()
188 predicate = registrar.revsetpredicate()
189
189
190 @predicate('_destupdate')
190 @predicate('_destupdate')
191 def _destupdate(repo, subset, x):
191 def _destupdate(repo, subset, x):
192 # experimental revset for update destination
192 # experimental revset for update destination
193 args = getargsdict(x, 'limit', 'clean')
193 args = getargsdict(x, 'limit', 'clean')
194 return subset & baseset([destutil.destupdate(repo, **args)[0]])
194 return subset & baseset([destutil.destupdate(repo, **args)[0]])
195
195
196 @predicate('_destmerge')
196 @predicate('_destmerge')
197 def _destmerge(repo, subset, x):
197 def _destmerge(repo, subset, x):
198 # experimental revset for merge destination
198 # experimental revset for merge destination
199 sourceset = None
199 sourceset = None
200 if x is not None:
200 if x is not None:
201 sourceset = getset(repo, fullreposet(repo), x)
201 sourceset = getset(repo, fullreposet(repo), x)
202 return subset & baseset([destutil.destmerge(repo, sourceset=sourceset)])
202 return subset & baseset([destutil.destmerge(repo, sourceset=sourceset)])
203
203
204 @predicate('adds(pattern)', safe=True)
204 @predicate('adds(pattern)', safe=True)
205 def adds(repo, subset, x):
205 def adds(repo, subset, x):
206 """Changesets that add a file matching pattern.
206 """Changesets that add a file matching pattern.
207
207
208 The pattern without explicit kind like ``glob:`` is expected to be
208 The pattern without explicit kind like ``glob:`` is expected to be
209 relative to the current directory and match against a file or a
209 relative to the current directory and match against a file or a
210 directory.
210 directory.
211 """
211 """
212 # i18n: "adds" is a keyword
212 # i18n: "adds" is a keyword
213 pat = getstring(x, _("adds requires a pattern"))
213 pat = getstring(x, _("adds requires a pattern"))
214 return checkstatus(repo, subset, pat, 1)
214 return checkstatus(repo, subset, pat, 1)
215
215
216 @predicate('ancestor(*changeset)', safe=True)
216 @predicate('ancestor(*changeset)', safe=True)
217 def ancestor(repo, subset, x):
217 def ancestor(repo, subset, x):
218 """A greatest common ancestor of the changesets.
218 """A greatest common ancestor of the changesets.
219
219
220 Accepts 0 or more changesets.
220 Accepts 0 or more changesets.
221 Will return empty list when passed no args.
221 Will return empty list when passed no args.
222 Greatest common ancestor of a single changeset is that changeset.
222 Greatest common ancestor of a single changeset is that changeset.
223 """
223 """
224 # i18n: "ancestor" is a keyword
224 # i18n: "ancestor" is a keyword
225 l = getlist(x)
225 l = getlist(x)
226 rl = fullreposet(repo)
226 rl = fullreposet(repo)
227 anc = None
227 anc = None
228
228
229 # (getset(repo, rl, i) for i in l) generates a list of lists
229 # (getset(repo, rl, i) for i in l) generates a list of lists
230 for revs in (getset(repo, rl, i) for i in l):
230 for revs in (getset(repo, rl, i) for i in l):
231 for r in revs:
231 for r in revs:
232 if anc is None:
232 if anc is None:
233 anc = repo[r]
233 anc = repo[r]
234 else:
234 else:
235 anc = anc.ancestor(repo[r])
235 anc = anc.ancestor(repo[r])
236
236
237 if anc is not None and anc.rev() in subset:
237 if anc is not None and anc.rev() in subset:
238 return baseset([anc.rev()])
238 return baseset([anc.rev()])
239 return baseset()
239 return baseset()
240
240
241 def _ancestors(repo, subset, x, followfirst=False, startdepth=None,
241 def _ancestors(repo, subset, x, followfirst=False, startdepth=None,
242 stopdepth=None):
242 stopdepth=None):
243 heads = getset(repo, fullreposet(repo), x)
243 heads = getset(repo, fullreposet(repo), x)
244 if not heads:
244 if not heads:
245 return baseset()
245 return baseset()
246 s = dagop.revancestors(repo, heads, followfirst, startdepth, stopdepth)
246 s = dagop.revancestors(repo, heads, followfirst, startdepth, stopdepth)
247 return subset & s
247 return subset & s
248
248
249 @predicate('ancestors(set[, depth])', safe=True)
249 @predicate('ancestors(set[, depth])', safe=True)
250 def ancestors(repo, subset, x):
250 def ancestors(repo, subset, x):
251 """Changesets that are ancestors of changesets in set, including the
251 """Changesets that are ancestors of changesets in set, including the
252 given changesets themselves.
252 given changesets themselves.
253
253
254 If depth is specified, the result only includes changesets up to
254 If depth is specified, the result only includes changesets up to
255 the specified generation.
255 the specified generation.
256 """
256 """
257 # startdepth is for internal use only until we can decide the UI
257 # startdepth is for internal use only until we can decide the UI
258 args = getargsdict(x, 'ancestors', 'set depth startdepth')
258 args = getargsdict(x, 'ancestors', 'set depth startdepth')
259 if 'set' not in args:
259 if 'set' not in args:
260 # i18n: "ancestors" is a keyword
260 # i18n: "ancestors" is a keyword
261 raise error.ParseError(_('ancestors takes at least 1 argument'))
261 raise error.ParseError(_('ancestors takes at least 1 argument'))
262 startdepth = stopdepth = None
262 startdepth = stopdepth = None
263 if 'startdepth' in args:
263 if 'startdepth' in args:
264 n = getinteger(args['startdepth'],
264 n = getinteger(args['startdepth'],
265 "ancestors expects an integer startdepth")
265 "ancestors expects an integer startdepth")
266 if n < 0:
266 if n < 0:
267 raise error.ParseError("negative startdepth")
267 raise error.ParseError("negative startdepth")
268 startdepth = n
268 startdepth = n
269 if 'depth' in args:
269 if 'depth' in args:
270 # i18n: "ancestors" is a keyword
270 # i18n: "ancestors" is a keyword
271 n = getinteger(args['depth'], _("ancestors expects an integer depth"))
271 n = getinteger(args['depth'], _("ancestors expects an integer depth"))
272 if n < 0:
272 if n < 0:
273 raise error.ParseError(_("negative depth"))
273 raise error.ParseError(_("negative depth"))
274 stopdepth = n + 1
274 stopdepth = n + 1
275 return _ancestors(repo, subset, args['set'],
275 return _ancestors(repo, subset, args['set'],
276 startdepth=startdepth, stopdepth=stopdepth)
276 startdepth=startdepth, stopdepth=stopdepth)
277
277
278 @predicate('_firstancestors', safe=True)
278 @predicate('_firstancestors', safe=True)
279 def _firstancestors(repo, subset, x):
279 def _firstancestors(repo, subset, x):
280 # ``_firstancestors(set)``
280 # ``_firstancestors(set)``
281 # Like ``ancestors(set)`` but follows only the first parents.
281 # Like ``ancestors(set)`` but follows only the first parents.
282 return _ancestors(repo, subset, x, followfirst=True)
282 return _ancestors(repo, subset, x, followfirst=True)
283
283
284 def _childrenspec(repo, subset, x, n, order):
284 def _childrenspec(repo, subset, x, n, order):
285 """Changesets that are the Nth child of a changeset
285 """Changesets that are the Nth child of a changeset
286 in set.
286 in set.
287 """
287 """
288 cs = set()
288 cs = set()
289 for r in getset(repo, fullreposet(repo), x):
289 for r in getset(repo, fullreposet(repo), x):
290 for i in range(n):
290 for i in range(n):
291 c = repo[r].children()
291 c = repo[r].children()
292 if len(c) == 0:
292 if len(c) == 0:
293 break
293 break
294 if len(c) > 1:
294 if len(c) > 1:
295 raise error.RepoLookupError(
295 raise error.RepoLookupError(
296 _("revision in set has more than one child"))
296 _("revision in set has more than one child"))
297 r = c[0].rev()
297 r = c[0].rev()
298 else:
298 else:
299 cs.add(r)
299 cs.add(r)
300 return subset & cs
300 return subset & cs
301
301
302 def ancestorspec(repo, subset, x, n, order):
302 def ancestorspec(repo, subset, x, n, order):
303 """``set~n``
303 """``set~n``
304 Changesets that are the Nth ancestor (first parents only) of a changeset
304 Changesets that are the Nth ancestor (first parents only) of a changeset
305 in set.
305 in set.
306 """
306 """
307 n = getinteger(n, _("~ expects a number"))
307 n = getinteger(n, _("~ expects a number"))
308 if n < 0:
308 if n < 0:
309 # children lookup
309 # children lookup
310 return _childrenspec(repo, subset, x, -n, order)
310 return _childrenspec(repo, subset, x, -n, order)
311 ps = set()
311 ps = set()
312 cl = repo.changelog
312 cl = repo.changelog
313 for r in getset(repo, fullreposet(repo), x):
313 for r in getset(repo, fullreposet(repo), x):
314 for i in range(n):
314 for i in range(n):
315 try:
315 try:
316 r = cl.parentrevs(r)[0]
316 r = cl.parentrevs(r)[0]
317 except error.WdirUnsupported:
317 except error.WdirUnsupported:
318 r = repo[r].parents()[0].rev()
318 r = repo[r].parents()[0].rev()
319 ps.add(r)
319 ps.add(r)
320 return subset & ps
320 return subset & ps
321
321
322 @predicate('author(string)', safe=True)
322 @predicate('author(string)', safe=True)
323 def author(repo, subset, x):
323 def author(repo, subset, x):
324 """Alias for ``user(string)``.
324 """Alias for ``user(string)``.
325 """
325 """
326 # i18n: "author" is a keyword
326 # i18n: "author" is a keyword
327 n = getstring(x, _("author requires a string"))
327 n = getstring(x, _("author requires a string"))
328 kind, pattern, matcher = _substringmatcher(n, casesensitive=False)
328 kind, pattern, matcher = _substringmatcher(n, casesensitive=False)
329 return subset.filter(lambda x: matcher(repo[x].user()),
329 return subset.filter(lambda x: matcher(repo[x].user()),
330 condrepr=('<user %r>', n))
330 condrepr=('<user %r>', n))
331
331
332 @predicate('bisect(string)', safe=True)
332 @predicate('bisect(string)', safe=True)
333 def bisect(repo, subset, x):
333 def bisect(repo, subset, x):
334 """Changesets marked in the specified bisect status:
334 """Changesets marked in the specified bisect status:
335
335
336 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
336 - ``good``, ``bad``, ``skip``: csets explicitly marked as good/bad/skip
337 - ``goods``, ``bads`` : csets topologically good/bad
337 - ``goods``, ``bads`` : csets topologically good/bad
338 - ``range`` : csets taking part in the bisection
338 - ``range`` : csets taking part in the bisection
339 - ``pruned`` : csets that are goods, bads or skipped
339 - ``pruned`` : csets that are goods, bads or skipped
340 - ``untested`` : csets whose fate is yet unknown
340 - ``untested`` : csets whose fate is yet unknown
341 - ``ignored`` : csets ignored due to DAG topology
341 - ``ignored`` : csets ignored due to DAG topology
342 - ``current`` : the cset currently being bisected
342 - ``current`` : the cset currently being bisected
343 """
343 """
344 # i18n: "bisect" is a keyword
344 # i18n: "bisect" is a keyword
345 status = getstring(x, _("bisect requires a string")).lower()
345 status = getstring(x, _("bisect requires a string")).lower()
346 state = set(hbisect.get(repo, status))
346 state = set(hbisect.get(repo, status))
347 return subset & state
347 return subset & state
348
348
349 # Backward-compatibility
349 # Backward-compatibility
350 # - no help entry so that we do not advertise it any more
350 # - no help entry so that we do not advertise it any more
351 @predicate('bisected', safe=True)
351 @predicate('bisected', safe=True)
352 def bisected(repo, subset, x):
352 def bisected(repo, subset, x):
353 return bisect(repo, subset, x)
353 return bisect(repo, subset, x)
354
354
355 @predicate('bookmark([name])', safe=True)
355 @predicate('bookmark([name])', safe=True)
356 def bookmark(repo, subset, x):
356 def bookmark(repo, subset, x):
357 """The named bookmark or all bookmarks.
357 """The named bookmark or all bookmarks.
358
358
359 Pattern matching is supported for `name`. See :hg:`help revisions.patterns`.
359 Pattern matching is supported for `name`. See :hg:`help revisions.patterns`.
360 """
360 """
361 # i18n: "bookmark" is a keyword
361 # i18n: "bookmark" is a keyword
362 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
362 args = getargs(x, 0, 1, _('bookmark takes one or no arguments'))
363 if args:
363 if args:
364 bm = getstring(args[0],
364 bm = getstring(args[0],
365 # i18n: "bookmark" is a keyword
365 # i18n: "bookmark" is a keyword
366 _('the argument to bookmark must be a string'))
366 _('the argument to bookmark must be a string'))
367 kind, pattern, matcher = util.stringmatcher(bm)
367 kind, pattern, matcher = util.stringmatcher(bm)
368 bms = set()
368 bms = set()
369 if kind == 'literal':
369 if kind == 'literal':
370 bmrev = repo._bookmarks.get(pattern, None)
370 bmrev = repo._bookmarks.get(pattern, None)
371 if not bmrev:
371 if not bmrev:
372 raise error.RepoLookupError(_("bookmark '%s' does not exist")
372 raise error.RepoLookupError(_("bookmark '%s' does not exist")
373 % pattern)
373 % pattern)
374 bms.add(repo[bmrev].rev())
374 bms.add(repo[bmrev].rev())
375 else:
375 else:
376 matchrevs = set()
376 matchrevs = set()
377 for name, bmrev in repo._bookmarks.iteritems():
377 for name, bmrev in repo._bookmarks.iteritems():
378 if matcher(name):
378 if matcher(name):
379 matchrevs.add(bmrev)
379 matchrevs.add(bmrev)
380 if not matchrevs:
380 if not matchrevs:
381 raise error.RepoLookupError(_("no bookmarks exist"
381 raise error.RepoLookupError(_("no bookmarks exist"
382 " that match '%s'") % pattern)
382 " that match '%s'") % pattern)
383 for bmrev in matchrevs:
383 for bmrev in matchrevs:
384 bms.add(repo[bmrev].rev())
384 bms.add(repo[bmrev].rev())
385 else:
385 else:
386 bms = {repo[r].rev() for r in repo._bookmarks.values()}
386 bms = {repo[r].rev() for r in repo._bookmarks.values()}
387 bms -= {node.nullrev}
387 bms -= {node.nullrev}
388 return subset & bms
388 return subset & bms
389
389
390 @predicate('branch(string or set)', safe=True)
390 @predicate('branch(string or set)', safe=True)
391 def branch(repo, subset, x):
391 def branch(repo, subset, x):
392 """
392 """
393 All changesets belonging to the given branch or the branches of the given
393 All changesets belonging to the given branch or the branches of the given
394 changesets.
394 changesets.
395
395
396 Pattern matching is supported for `string`. See
396 Pattern matching is supported for `string`. See
397 :hg:`help revisions.patterns`.
397 :hg:`help revisions.patterns`.
398 """
398 """
399 getbi = repo.revbranchcache().branchinfo
399 getbi = repo.revbranchcache().branchinfo
400 def getbranch(r):
400 def getbranch(r):
401 try:
401 try:
402 return getbi(r)[0]
402 return getbi(r)[0]
403 except error.WdirUnsupported:
403 except error.WdirUnsupported:
404 return repo[r].branch()
404 return repo[r].branch()
405
405
406 try:
406 try:
407 b = getstring(x, '')
407 b = getstring(x, '')
408 except error.ParseError:
408 except error.ParseError:
409 # not a string, but another revspec, e.g. tip()
409 # not a string, but another revspec, e.g. tip()
410 pass
410 pass
411 else:
411 else:
412 kind, pattern, matcher = util.stringmatcher(b)
412 kind, pattern, matcher = util.stringmatcher(b)
413 if kind == 'literal':
413 if kind == 'literal':
414 # note: falls through to the revspec case if no branch with
414 # note: falls through to the revspec case if no branch with
415 # this name exists and pattern kind is not specified explicitly
415 # this name exists and pattern kind is not specified explicitly
416 if pattern in repo.branchmap():
416 if pattern in repo.branchmap():
417 return subset.filter(lambda r: matcher(getbranch(r)),
417 return subset.filter(lambda r: matcher(getbranch(r)),
418 condrepr=('<branch %r>', b))
418 condrepr=('<branch %r>', b))
419 if b.startswith('literal:'):
419 if b.startswith('literal:'):
420 raise error.RepoLookupError(_("branch '%s' does not exist")
420 raise error.RepoLookupError(_("branch '%s' does not exist")
421 % pattern)
421 % pattern)
422 else:
422 else:
423 return subset.filter(lambda r: matcher(getbranch(r)),
423 return subset.filter(lambda r: matcher(getbranch(r)),
424 condrepr=('<branch %r>', b))
424 condrepr=('<branch %r>', b))
425
425
426 s = getset(repo, fullreposet(repo), x)
426 s = getset(repo, fullreposet(repo), x)
427 b = set()
427 b = set()
428 for r in s:
428 for r in s:
429 b.add(getbranch(r))
429 b.add(getbranch(r))
430 c = s.__contains__
430 c = s.__contains__
431 return subset.filter(lambda r: c(r) or getbranch(r) in b,
431 return subset.filter(lambda r: c(r) or getbranch(r) in b,
432 condrepr=lambda: '<branch %r>' % sorted(b))
432 condrepr=lambda: '<branch %r>' % sorted(b))
433
433
434 @predicate('bumped()', safe=True)
434 @predicate('bumped()', safe=True)
435 def bumped(repo, subset, x):
435 def bumped(repo, subset, x):
436 """Mutable changesets marked as successors of public changesets.
436 """Mutable changesets marked as successors of public changesets.
437
437
438 Only non-public and non-obsolete changesets can be `bumped`.
438 Only non-public and non-obsolete changesets can be `bumped`.
439 """
439 """
440 # i18n: "bumped" is a keyword
440 # i18n: "bumped" is a keyword
441 getargs(x, 0, 0, _("bumped takes no arguments"))
441 getargs(x, 0, 0, _("bumped takes no arguments"))
442 bumped = obsmod.getrevs(repo, 'bumped')
442 bumped = obsmod.getrevs(repo, 'bumped')
443 return subset & bumped
443 return subset & bumped
444
444
445 @predicate('bundle()', safe=True)
445 @predicate('bundle()', safe=True)
446 def bundle(repo, subset, x):
446 def bundle(repo, subset, x):
447 """Changesets in the bundle.
447 """Changesets in the bundle.
448
448
449 Bundle must be specified by the -R option."""
449 Bundle must be specified by the -R option."""
450
450
451 try:
451 try:
452 bundlerevs = repo.changelog.bundlerevs
452 bundlerevs = repo.changelog.bundlerevs
453 except AttributeError:
453 except AttributeError:
454 raise error.Abort(_("no bundle provided - specify with -R"))
454 raise error.Abort(_("no bundle provided - specify with -R"))
455 return subset & bundlerevs
455 return subset & bundlerevs
456
456
457 def checkstatus(repo, subset, pat, field):
457 def checkstatus(repo, subset, pat, field):
458 hasset = matchmod.patkind(pat) == 'set'
458 hasset = matchmod.patkind(pat) == 'set'
459
459
460 mcache = [None]
460 mcache = [None]
461 def matches(x):
461 def matches(x):
462 c = repo[x]
462 c = repo[x]
463 if not mcache[0] or hasset:
463 if not mcache[0] or hasset:
464 mcache[0] = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
464 mcache[0] = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
465 m = mcache[0]
465 m = mcache[0]
466 fname = None
466 fname = None
467 if not m.anypats() and len(m.files()) == 1:
467 if not m.anypats() and len(m.files()) == 1:
468 fname = m.files()[0]
468 fname = m.files()[0]
469 if fname is not None:
469 if fname is not None:
470 if fname not in c.files():
470 if fname not in c.files():
471 return False
471 return False
472 else:
472 else:
473 for f in c.files():
473 for f in c.files():
474 if m(f):
474 if m(f):
475 break
475 break
476 else:
476 else:
477 return False
477 return False
478 files = repo.status(c.p1().node(), c.node())[field]
478 files = repo.status(c.p1().node(), c.node())[field]
479 if fname is not None:
479 if fname is not None:
480 if fname in files:
480 if fname in files:
481 return True
481 return True
482 else:
482 else:
483 for f in files:
483 for f in files:
484 if m(f):
484 if m(f):
485 return True
485 return True
486
486
487 return subset.filter(matches, condrepr=('<status[%r] %r>', field, pat))
487 return subset.filter(matches, condrepr=('<status[%r] %r>', field, pat))
488
488
489 def _children(repo, subset, parentset):
489 def _children(repo, subset, parentset):
490 if not parentset:
490 if not parentset:
491 return baseset()
491 return baseset()
492 cs = set()
492 cs = set()
493 pr = repo.changelog.parentrevs
493 pr = repo.changelog.parentrevs
494 minrev = parentset.min()
494 minrev = parentset.min()
495 nullrev = node.nullrev
495 nullrev = node.nullrev
496 for r in subset:
496 for r in subset:
497 if r <= minrev:
497 if r <= minrev:
498 continue
498 continue
499 p1, p2 = pr(r)
499 p1, p2 = pr(r)
500 if p1 in parentset:
500 if p1 in parentset:
501 cs.add(r)
501 cs.add(r)
502 if p2 != nullrev and p2 in parentset:
502 if p2 != nullrev and p2 in parentset:
503 cs.add(r)
503 cs.add(r)
504 return baseset(cs)
504 return baseset(cs)
505
505
506 @predicate('children(set)', safe=True)
506 @predicate('children(set)', safe=True)
507 def children(repo, subset, x):
507 def children(repo, subset, x):
508 """Child changesets of changesets in set.
508 """Child changesets of changesets in set.
509 """
509 """
510 s = getset(repo, fullreposet(repo), x)
510 s = getset(repo, fullreposet(repo), x)
511 cs = _children(repo, subset, s)
511 cs = _children(repo, subset, s)
512 return subset & cs
512 return subset & cs
513
513
514 @predicate('closed()', safe=True)
514 @predicate('closed()', safe=True)
515 def closed(repo, subset, x):
515 def closed(repo, subset, x):
516 """Changeset is closed.
516 """Changeset is closed.
517 """
517 """
518 # i18n: "closed" is a keyword
518 # i18n: "closed" is a keyword
519 getargs(x, 0, 0, _("closed takes no arguments"))
519 getargs(x, 0, 0, _("closed takes no arguments"))
520 return subset.filter(lambda r: repo[r].closesbranch(),
520 return subset.filter(lambda r: repo[r].closesbranch(),
521 condrepr='<branch closed>')
521 condrepr='<branch closed>')
522
522
523 @predicate('contains(pattern)')
523 @predicate('contains(pattern)')
524 def contains(repo, subset, x):
524 def contains(repo, subset, x):
525 """The revision's manifest contains a file matching pattern (but might not
525 """The revision's manifest contains a file matching pattern (but might not
526 modify it). See :hg:`help patterns` for information about file patterns.
526 modify it). See :hg:`help patterns` for information about file patterns.
527
527
528 The pattern without explicit kind like ``glob:`` is expected to be
528 The pattern without explicit kind like ``glob:`` is expected to be
529 relative to the current directory and match against a file exactly
529 relative to the current directory and match against a file exactly
530 for efficiency.
530 for efficiency.
531 """
531 """
532 # i18n: "contains" is a keyword
532 # i18n: "contains" is a keyword
533 pat = getstring(x, _("contains requires a pattern"))
533 pat = getstring(x, _("contains requires a pattern"))
534
534
535 def matches(x):
535 def matches(x):
536 if not matchmod.patkind(pat):
536 if not matchmod.patkind(pat):
537 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
537 pats = pathutil.canonpath(repo.root, repo.getcwd(), pat)
538 if pats in repo[x]:
538 if pats in repo[x]:
539 return True
539 return True
540 else:
540 else:
541 c = repo[x]
541 c = repo[x]
542 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
542 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=c)
543 for f in c.manifest():
543 for f in c.manifest():
544 if m(f):
544 if m(f):
545 return True
545 return True
546 return False
546 return False
547
547
548 return subset.filter(matches, condrepr=('<contains %r>', pat))
548 return subset.filter(matches, condrepr=('<contains %r>', pat))
549
549
550 @predicate('converted([id])', safe=True)
550 @predicate('converted([id])', safe=True)
551 def converted(repo, subset, x):
551 def converted(repo, subset, x):
552 """Changesets converted from the given identifier in the old repository if
552 """Changesets converted from the given identifier in the old repository if
553 present, or all converted changesets if no identifier is specified.
553 present, or all converted changesets if no identifier is specified.
554 """
554 """
555
555
556 # There is exactly no chance of resolving the revision, so do a simple
556 # There is exactly no chance of resolving the revision, so do a simple
557 # string compare and hope for the best
557 # string compare and hope for the best
558
558
559 rev = None
559 rev = None
560 # i18n: "converted" is a keyword
560 # i18n: "converted" is a keyword
561 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
561 l = getargs(x, 0, 1, _('converted takes one or no arguments'))
562 if l:
562 if l:
563 # i18n: "converted" is a keyword
563 # i18n: "converted" is a keyword
564 rev = getstring(l[0], _('converted requires a revision'))
564 rev = getstring(l[0], _('converted requires a revision'))
565
565
566 def _matchvalue(r):
566 def _matchvalue(r):
567 source = repo[r].extra().get('convert_revision', None)
567 source = repo[r].extra().get('convert_revision', None)
568 return source is not None and (rev is None or source.startswith(rev))
568 return source is not None and (rev is None or source.startswith(rev))
569
569
570 return subset.filter(lambda r: _matchvalue(r),
570 return subset.filter(lambda r: _matchvalue(r),
571 condrepr=('<converted %r>', rev))
571 condrepr=('<converted %r>', rev))
572
572
573 @predicate('date(interval)', safe=True)
573 @predicate('date(interval)', safe=True)
574 def date(repo, subset, x):
574 def date(repo, subset, x):
575 """Changesets within the interval, see :hg:`help dates`.
575 """Changesets within the interval, see :hg:`help dates`.
576 """
576 """
577 # i18n: "date" is a keyword
577 # i18n: "date" is a keyword
578 ds = getstring(x, _("date requires a string"))
578 ds = getstring(x, _("date requires a string"))
579 dm = util.matchdate(ds)
579 dm = util.matchdate(ds)
580 return subset.filter(lambda x: dm(repo[x].date()[0]),
580 return subset.filter(lambda x: dm(repo[x].date()[0]),
581 condrepr=('<date %r>', ds))
581 condrepr=('<date %r>', ds))
582
582
583 @predicate('desc(string)', safe=True)
583 @predicate('desc(string)', safe=True)
584 def desc(repo, subset, x):
584 def desc(repo, subset, x):
585 """Search commit message for string. The match is case-insensitive.
585 """Search commit message for string. The match is case-insensitive.
586
586
587 Pattern matching is supported for `string`. See
587 Pattern matching is supported for `string`. See
588 :hg:`help revisions.patterns`.
588 :hg:`help revisions.patterns`.
589 """
589 """
590 # i18n: "desc" is a keyword
590 # i18n: "desc" is a keyword
591 ds = getstring(x, _("desc requires a string"))
591 ds = getstring(x, _("desc requires a string"))
592
592
593 kind, pattern, matcher = _substringmatcher(ds, casesensitive=False)
593 kind, pattern, matcher = _substringmatcher(ds, casesensitive=False)
594
594
595 return subset.filter(lambda r: matcher(repo[r].description()),
595 return subset.filter(lambda r: matcher(repo[r].description()),
596 condrepr=('<desc %r>', ds))
596 condrepr=('<desc %r>', ds))
597
597
598 def _descendants(repo, subset, x, followfirst=False, startdepth=None,
598 def _descendants(repo, subset, x, followfirst=False, startdepth=None,
599 stopdepth=None):
599 stopdepth=None):
600 roots = getset(repo, fullreposet(repo), x)
600 roots = getset(repo, fullreposet(repo), x)
601 if not roots:
601 if not roots:
602 return baseset()
602 return baseset()
603 s = dagop.revdescendants(repo, roots, followfirst, startdepth, stopdepth)
603 s = dagop.revdescendants(repo, roots, followfirst, startdepth, stopdepth)
604 return subset & s
604 return subset & s
605
605
606 @predicate('descendants(set[, depth])', safe=True)
606 @predicate('descendants(set[, depth])', safe=True)
607 def descendants(repo, subset, x):
607 def descendants(repo, subset, x):
608 """Changesets which are descendants of changesets in set, including the
608 """Changesets which are descendants of changesets in set, including the
609 given changesets themselves.
609 given changesets themselves.
610
610
611 If depth is specified, the result only includes changesets up to
611 If depth is specified, the result only includes changesets up to
612 the specified generation.
612 the specified generation.
613 """
613 """
614 # startdepth is for internal use only until we can decide the UI
614 # startdepth is for internal use only until we can decide the UI
615 args = getargsdict(x, 'descendants', 'set depth startdepth')
615 args = getargsdict(x, 'descendants', 'set depth startdepth')
616 if 'set' not in args:
616 if 'set' not in args:
617 # i18n: "descendants" is a keyword
617 # i18n: "descendants" is a keyword
618 raise error.ParseError(_('descendants takes at least 1 argument'))
618 raise error.ParseError(_('descendants takes at least 1 argument'))
619 startdepth = stopdepth = None
619 startdepth = stopdepth = None
620 if 'startdepth' in args:
620 if 'startdepth' in args:
621 n = getinteger(args['startdepth'],
621 n = getinteger(args['startdepth'],
622 "descendants expects an integer startdepth")
622 "descendants expects an integer startdepth")
623 if n < 0:
623 if n < 0:
624 raise error.ParseError("negative startdepth")
624 raise error.ParseError("negative startdepth")
625 startdepth = n
625 startdepth = n
626 if 'depth' in args:
626 if 'depth' in args:
627 # i18n: "descendants" is a keyword
627 # i18n: "descendants" is a keyword
628 n = getinteger(args['depth'], _("descendants expects an integer depth"))
628 n = getinteger(args['depth'], _("descendants expects an integer depth"))
629 if n < 0:
629 if n < 0:
630 raise error.ParseError(_("negative depth"))
630 raise error.ParseError(_("negative depth"))
631 stopdepth = n + 1
631 stopdepth = n + 1
632 return _descendants(repo, subset, args['set'],
632 return _descendants(repo, subset, args['set'],
633 startdepth=startdepth, stopdepth=stopdepth)
633 startdepth=startdepth, stopdepth=stopdepth)
634
634
635 @predicate('_firstdescendants', safe=True)
635 @predicate('_firstdescendants', safe=True)
636 def _firstdescendants(repo, subset, x):
636 def _firstdescendants(repo, subset, x):
637 # ``_firstdescendants(set)``
637 # ``_firstdescendants(set)``
638 # Like ``descendants(set)`` but follows only the first parents.
638 # Like ``descendants(set)`` but follows only the first parents.
639 return _descendants(repo, subset, x, followfirst=True)
639 return _descendants(repo, subset, x, followfirst=True)
640
640
641 @predicate('destination([set])', safe=True)
641 @predicate('destination([set])', safe=True)
642 def destination(repo, subset, x):
642 def destination(repo, subset, x):
643 """Changesets that were created by a graft, transplant or rebase operation,
643 """Changesets that were created by a graft, transplant or rebase operation,
644 with the given revisions specified as the source. Omitting the optional set
644 with the given revisions specified as the source. Omitting the optional set
645 is the same as passing all().
645 is the same as passing all().
646 """
646 """
647 if x is not None:
647 if x is not None:
648 sources = getset(repo, fullreposet(repo), x)
648 sources = getset(repo, fullreposet(repo), x)
649 else:
649 else:
650 sources = fullreposet(repo)
650 sources = fullreposet(repo)
651
651
652 dests = set()
652 dests = set()
653
653
654 # subset contains all of the possible destinations that can be returned, so
654 # subset contains all of the possible destinations that can be returned, so
655 # iterate over them and see if their source(s) were provided in the arg set.
655 # iterate over them and see if their source(s) were provided in the arg set.
656 # Even if the immediate src of r is not in the arg set, src's source (or
656 # Even if the immediate src of r is not in the arg set, src's source (or
657 # further back) may be. Scanning back further than the immediate src allows
657 # further back) may be. Scanning back further than the immediate src allows
658 # transitive transplants and rebases to yield the same results as transitive
658 # transitive transplants and rebases to yield the same results as transitive
659 # grafts.
659 # grafts.
660 for r in subset:
660 for r in subset:
661 src = _getrevsource(repo, r)
661 src = _getrevsource(repo, r)
662 lineage = None
662 lineage = None
663
663
664 while src is not None:
664 while src is not None:
665 if lineage is None:
665 if lineage is None:
666 lineage = list()
666 lineage = list()
667
667
668 lineage.append(r)
668 lineage.append(r)
669
669
670 # The visited lineage is a match if the current source is in the arg
670 # The visited lineage is a match if the current source is in the arg
671 # set. Since every candidate dest is visited by way of iterating
671 # set. Since every candidate dest is visited by way of iterating
672 # subset, any dests further back in the lineage will be tested by a
672 # subset, any dests further back in the lineage will be tested by a
673 # different iteration over subset. Likewise, if the src was already
673 # different iteration over subset. Likewise, if the src was already
674 # selected, the current lineage can be selected without going back
674 # selected, the current lineage can be selected without going back
675 # further.
675 # further.
676 if src in sources or src in dests:
676 if src in sources or src in dests:
677 dests.update(lineage)
677 dests.update(lineage)
678 break
678 break
679
679
680 r = src
680 r = src
681 src = _getrevsource(repo, r)
681 src = _getrevsource(repo, r)
682
682
683 return subset.filter(dests.__contains__,
683 return subset.filter(dests.__contains__,
684 condrepr=lambda: '<destination %r>' % sorted(dests))
684 condrepr=lambda: '<destination %r>' % sorted(dests))
685
685
686 @predicate('divergent()', safe=True)
686 @predicate('divergent()', safe=True)
687 def divergent(repo, subset, x):
687 def divergent(repo, subset, x):
688 """
688 """
689 Final successors of changesets with an alternative set of final successors.
689 Final successors of changesets with an alternative set of final successors.
690 """
690 """
691 # i18n: "divergent" is a keyword
691 # i18n: "divergent" is a keyword
692 getargs(x, 0, 0, _("divergent takes no arguments"))
692 getargs(x, 0, 0, _("divergent takes no arguments"))
693 divergent = obsmod.getrevs(repo, 'divergent')
693 divergent = obsmod.getrevs(repo, 'divergent')
694 return subset & divergent
694 return subset & divergent
695
695
696 @predicate('extinct()', safe=True)
696 @predicate('extinct()', safe=True)
697 def extinct(repo, subset, x):
697 def extinct(repo, subset, x):
698 """Obsolete changesets with obsolete descendants only.
698 """Obsolete changesets with obsolete descendants only.
699 """
699 """
700 # i18n: "extinct" is a keyword
700 # i18n: "extinct" is a keyword
701 getargs(x, 0, 0, _("extinct takes no arguments"))
701 getargs(x, 0, 0, _("extinct takes no arguments"))
702 extincts = obsmod.getrevs(repo, 'extinct')
702 extincts = obsmod.getrevs(repo, 'extinct')
703 return subset & extincts
703 return subset & extincts
704
704
705 @predicate('extra(label, [value])', safe=True)
705 @predicate('extra(label, [value])', safe=True)
706 def extra(repo, subset, x):
706 def extra(repo, subset, x):
707 """Changesets with the given label in the extra metadata, with the given
707 """Changesets with the given label in the extra metadata, with the given
708 optional value.
708 optional value.
709
709
710 Pattern matching is supported for `value`. See
710 Pattern matching is supported for `value`. See
711 :hg:`help revisions.patterns`.
711 :hg:`help revisions.patterns`.
712 """
712 """
713 args = getargsdict(x, 'extra', 'label value')
713 args = getargsdict(x, 'extra', 'label value')
714 if 'label' not in args:
714 if 'label' not in args:
715 # i18n: "extra" is a keyword
715 # i18n: "extra" is a keyword
716 raise error.ParseError(_('extra takes at least 1 argument'))
716 raise error.ParseError(_('extra takes at least 1 argument'))
717 # i18n: "extra" is a keyword
717 # i18n: "extra" is a keyword
718 label = getstring(args['label'], _('first argument to extra must be '
718 label = getstring(args['label'], _('first argument to extra must be '
719 'a string'))
719 'a string'))
720 value = None
720 value = None
721
721
722 if 'value' in args:
722 if 'value' in args:
723 # i18n: "extra" is a keyword
723 # i18n: "extra" is a keyword
724 value = getstring(args['value'], _('second argument to extra must be '
724 value = getstring(args['value'], _('second argument to extra must be '
725 'a string'))
725 'a string'))
726 kind, value, matcher = util.stringmatcher(value)
726 kind, value, matcher = util.stringmatcher(value)
727
727
728 def _matchvalue(r):
728 def _matchvalue(r):
729 extra = repo[r].extra()
729 extra = repo[r].extra()
730 return label in extra and (value is None or matcher(extra[label]))
730 return label in extra and (value is None or matcher(extra[label]))
731
731
732 return subset.filter(lambda r: _matchvalue(r),
732 return subset.filter(lambda r: _matchvalue(r),
733 condrepr=('<extra[%r] %r>', label, value))
733 condrepr=('<extra[%r] %r>', label, value))
734
734
735 @predicate('filelog(pattern)', safe=True)
735 @predicate('filelog(pattern)', safe=True)
736 def filelog(repo, subset, x):
736 def filelog(repo, subset, x):
737 """Changesets connected to the specified filelog.
737 """Changesets connected to the specified filelog.
738
738
739 For performance reasons, visits only revisions mentioned in the file-level
739 For performance reasons, visits only revisions mentioned in the file-level
740 filelog, rather than filtering through all changesets (much faster, but
740 filelog, rather than filtering through all changesets (much faster, but
741 doesn't include deletes or duplicate changes). For a slower, more accurate
741 doesn't include deletes or duplicate changes). For a slower, more accurate
742 result, use ``file()``.
742 result, use ``file()``.
743
743
744 The pattern without explicit kind like ``glob:`` is expected to be
744 The pattern without explicit kind like ``glob:`` is expected to be
745 relative to the current directory and match against a file exactly
745 relative to the current directory and match against a file exactly
746 for efficiency.
746 for efficiency.
747
747
748 If some linkrev points to revisions filtered by the current repoview, we'll
748 If some linkrev points to revisions filtered by the current repoview, we'll
749 work around it to return a non-filtered value.
749 work around it to return a non-filtered value.
750 """
750 """
751
751
752 # i18n: "filelog" is a keyword
752 # i18n: "filelog" is a keyword
753 pat = getstring(x, _("filelog requires a pattern"))
753 pat = getstring(x, _("filelog requires a pattern"))
754 s = set()
754 s = set()
755 cl = repo.changelog
755 cl = repo.changelog
756
756
757 if not matchmod.patkind(pat):
757 if not matchmod.patkind(pat):
758 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
758 f = pathutil.canonpath(repo.root, repo.getcwd(), pat)
759 files = [f]
759 files = [f]
760 else:
760 else:
761 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
761 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[None])
762 files = (f for f in repo[None] if m(f))
762 files = (f for f in repo[None] if m(f))
763
763
764 for f in files:
764 for f in files:
765 fl = repo.file(f)
765 fl = repo.file(f)
766 known = {}
766 known = {}
767 scanpos = 0
767 scanpos = 0
768 for fr in list(fl):
768 for fr in list(fl):
769 fn = fl.node(fr)
769 fn = fl.node(fr)
770 if fn in known:
770 if fn in known:
771 s.add(known[fn])
771 s.add(known[fn])
772 continue
772 continue
773
773
774 lr = fl.linkrev(fr)
774 lr = fl.linkrev(fr)
775 if lr in cl:
775 if lr in cl:
776 s.add(lr)
776 s.add(lr)
777 elif scanpos is not None:
777 elif scanpos is not None:
778 # lowest matching changeset is filtered, scan further
778 # lowest matching changeset is filtered, scan further
779 # ahead in changelog
779 # ahead in changelog
780 start = max(lr, scanpos) + 1
780 start = max(lr, scanpos) + 1
781 scanpos = None
781 scanpos = None
782 for r in cl.revs(start):
782 for r in cl.revs(start):
783 # minimize parsing of non-matching entries
783 # minimize parsing of non-matching entries
784 if f in cl.revision(r) and f in cl.readfiles(r):
784 if f in cl.revision(r) and f in cl.readfiles(r):
785 try:
785 try:
786 # try to use manifest delta fastpath
786 # try to use manifest delta fastpath
787 n = repo[r].filenode(f)
787 n = repo[r].filenode(f)
788 if n not in known:
788 if n not in known:
789 if n == fn:
789 if n == fn:
790 s.add(r)
790 s.add(r)
791 scanpos = r
791 scanpos = r
792 break
792 break
793 else:
793 else:
794 known[n] = r
794 known[n] = r
795 except error.ManifestLookupError:
795 except error.ManifestLookupError:
796 # deletion in changelog
796 # deletion in changelog
797 continue
797 continue
798
798
799 return subset & s
799 return subset & s
800
800
801 @predicate('first(set, [n])', safe=True, takeorder=True)
801 @predicate('first(set, [n])', safe=True, takeorder=True)
802 def first(repo, subset, x, order):
802 def first(repo, subset, x, order):
803 """An alias for limit().
803 """An alias for limit().
804 """
804 """
805 return limit(repo, subset, x, order)
805 return limit(repo, subset, x, order)
806
806
807 def _follow(repo, subset, x, name, followfirst=False):
807 def _follow(repo, subset, x, name, followfirst=False):
808 l = getargs(x, 0, 2, _("%s takes no arguments or a pattern "
808 l = getargs(x, 0, 2, _("%s takes no arguments or a pattern "
809 "and an optional revset") % name)
809 "and an optional revset") % name)
810 c = repo['.']
810 c = repo['.']
811 if l:
811 if l:
812 x = getstring(l[0], _("%s expected a pattern") % name)
812 x = getstring(l[0], _("%s expected a pattern") % name)
813 rev = None
813 rev = None
814 if len(l) >= 2:
814 if len(l) >= 2:
815 revs = getset(repo, fullreposet(repo), l[1])
815 revs = getset(repo, fullreposet(repo), l[1])
816 if len(revs) != 1:
816 if len(revs) != 1:
817 raise error.RepoLookupError(
817 raise error.RepoLookupError(
818 _("%s expected one starting revision") % name)
818 _("%s expected one starting revision") % name)
819 rev = revs.last()
819 rev = revs.last()
820 c = repo[rev]
820 c = repo[rev]
821 matcher = matchmod.match(repo.root, repo.getcwd(), [x],
821 matcher = matchmod.match(repo.root, repo.getcwd(), [x],
822 ctx=repo[rev], default='path')
822 ctx=repo[rev], default='path')
823
823
824 files = c.manifest().walk(matcher)
824 files = c.manifest().walk(matcher)
825
825
826 s = set()
826 s = set()
827 for fname in files:
827 for fname in files:
828 fctx = c[fname]
828 fctx = c[fname]
829 s = s.union(set(c.rev() for c in fctx.ancestors(followfirst)))
829 s = s.union(set(c.rev() for c in fctx.ancestors(followfirst)))
830 # include the revision responsible for the most recent version
830 # include the revision responsible for the most recent version
831 s.add(fctx.introrev())
831 s.add(fctx.introrev())
832 else:
832 else:
833 s = dagop.revancestors(repo, baseset([c.rev()]), followfirst)
833 s = dagop.revancestors(repo, baseset([c.rev()]), followfirst)
834
834
835 return subset & s
835 return subset & s
836
836
837 @predicate('follow([pattern[, startrev]])', safe=True)
837 @predicate('follow([pattern[, startrev]])', safe=True)
838 def follow(repo, subset, x):
838 def follow(repo, subset, x):
839 """
839 """
840 An alias for ``::.`` (ancestors of the working directory's first parent).
840 An alias for ``::.`` (ancestors of the working directory's first parent).
841 If pattern is specified, the histories of files matching given
841 If pattern is specified, the histories of files matching given
842 pattern in the revision given by startrev are followed, including copies.
842 pattern in the revision given by startrev are followed, including copies.
843 """
843 """
844 return _follow(repo, subset, x, 'follow')
844 return _follow(repo, subset, x, 'follow')
845
845
846 @predicate('_followfirst', safe=True)
846 @predicate('_followfirst', safe=True)
847 def _followfirst(repo, subset, x):
847 def _followfirst(repo, subset, x):
848 # ``followfirst([pattern[, startrev]])``
848 # ``followfirst([pattern[, startrev]])``
849 # Like ``follow([pattern[, startrev]])`` but follows only the first parent
849 # Like ``follow([pattern[, startrev]])`` but follows only the first parent
850 # of every revisions or files revisions.
850 # of every revisions or files revisions.
851 return _follow(repo, subset, x, '_followfirst', followfirst=True)
851 return _follow(repo, subset, x, '_followfirst', followfirst=True)
852
852
853 @predicate('followlines(file, fromline:toline[, startrev=., descend=False])',
853 @predicate('followlines(file, fromline:toline[, startrev=., descend=False])',
854 safe=True)
854 safe=True)
855 def followlines(repo, subset, x):
855 def followlines(repo, subset, x):
856 """Changesets modifying `file` in line range ('fromline', 'toline').
856 """Changesets modifying `file` in line range ('fromline', 'toline').
857
857
858 Line range corresponds to 'file' content at 'startrev' and should hence be
858 Line range corresponds to 'file' content at 'startrev' and should hence be
859 consistent with file size. If startrev is not specified, working directory's
859 consistent with file size. If startrev is not specified, working directory's
860 parent is used.
860 parent is used.
861
861
862 By default, ancestors of 'startrev' are returned. If 'descend' is True,
862 By default, ancestors of 'startrev' are returned. If 'descend' is True,
863 descendants of 'startrev' are returned though renames are (currently) not
863 descendants of 'startrev' are returned though renames are (currently) not
864 followed in this direction.
864 followed in this direction.
865 """
865 """
866 args = getargsdict(x, 'followlines', 'file *lines startrev descend')
866 args = getargsdict(x, 'followlines', 'file *lines startrev descend')
867 if len(args['lines']) != 1:
867 if len(args['lines']) != 1:
868 raise error.ParseError(_("followlines requires a line range"))
868 raise error.ParseError(_("followlines requires a line range"))
869
869
870 rev = '.'
870 rev = '.'
871 if 'startrev' in args:
871 if 'startrev' in args:
872 revs = getset(repo, fullreposet(repo), args['startrev'])
872 revs = getset(repo, fullreposet(repo), args['startrev'])
873 if len(revs) != 1:
873 if len(revs) != 1:
874 raise error.ParseError(
874 raise error.ParseError(
875 # i18n: "followlines" is a keyword
875 # i18n: "followlines" is a keyword
876 _("followlines expects exactly one revision"))
876 _("followlines expects exactly one revision"))
877 rev = revs.last()
877 rev = revs.last()
878
878
879 pat = getstring(args['file'], _("followlines requires a pattern"))
879 pat = getstring(args['file'], _("followlines requires a pattern"))
880 if not matchmod.patkind(pat):
880 if not matchmod.patkind(pat):
881 fname = pathutil.canonpath(repo.root, repo.getcwd(), pat)
881 fname = pathutil.canonpath(repo.root, repo.getcwd(), pat)
882 else:
882 else:
883 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[rev])
883 m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=repo[rev])
884 files = [f for f in repo[rev] if m(f)]
884 files = [f for f in repo[rev] if m(f)]
885 if len(files) != 1:
885 if len(files) != 1:
886 # i18n: "followlines" is a keyword
886 # i18n: "followlines" is a keyword
887 raise error.ParseError(_("followlines expects exactly one file"))
887 raise error.ParseError(_("followlines expects exactly one file"))
888 fname = files[0]
888 fname = files[0]
889
889
890 # i18n: "followlines" is a keyword
890 # i18n: "followlines" is a keyword
891 lr = getrange(args['lines'][0], _("followlines expects a line range"))
891 lr = getrange(args['lines'][0], _("followlines expects a line range"))
892 fromline, toline = [getinteger(a, _("line range bounds must be integers"))
892 fromline, toline = [getinteger(a, _("line range bounds must be integers"))
893 for a in lr]
893 for a in lr]
894 fromline, toline = util.processlinerange(fromline, toline)
894 fromline, toline = util.processlinerange(fromline, toline)
895
895
896 fctx = repo[rev].filectx(fname)
896 fctx = repo[rev].filectx(fname)
897 descend = False
897 descend = False
898 if 'descend' in args:
898 if 'descend' in args:
899 descend = getboolean(args['descend'],
899 descend = getboolean(args['descend'],
900 # i18n: "descend" is a keyword
900 # i18n: "descend" is a keyword
901 _("descend argument must be a boolean"))
901 _("descend argument must be a boolean"))
902 if descend:
902 if descend:
903 rs = generatorset(
903 rs = generatorset(
904 (c.rev() for c, _linerange
904 (c.rev() for c, _linerange
905 in dagop.blockdescendants(fctx, fromline, toline)),
905 in dagop.blockdescendants(fctx, fromline, toline)),
906 iterasc=True)
906 iterasc=True)
907 else:
907 else:
908 rs = generatorset(
908 rs = generatorset(
909 (c.rev() for c, _linerange
909 (c.rev() for c, _linerange
910 in dagop.blockancestors(fctx, fromline, toline)),
910 in dagop.blockancestors(fctx, fromline, toline)),
911 iterasc=False)
911 iterasc=False)
912 return subset & rs
912 return subset & rs
913
913
914 @predicate('all()', safe=True)
914 @predicate('all()', safe=True)
915 def getall(repo, subset, x):
915 def getall(repo, subset, x):
916 """All changesets, the same as ``0:tip``.
916 """All changesets, the same as ``0:tip``.
917 """
917 """
918 # i18n: "all" is a keyword
918 # i18n: "all" is a keyword
919 getargs(x, 0, 0, _("all takes no arguments"))
919 getargs(x, 0, 0, _("all takes no arguments"))
920 return subset & spanset(repo) # drop "null" if any
920 return subset & spanset(repo) # drop "null" if any
921
921
922 @predicate('grep(regex)')
922 @predicate('grep(regex)')
923 def grep(repo, subset, x):
923 def grep(repo, subset, x):
924 """Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
924 """Like ``keyword(string)`` but accepts a regex. Use ``grep(r'...')``
925 to ensure special escape characters are handled correctly. Unlike
925 to ensure special escape characters are handled correctly. Unlike
926 ``keyword(string)``, the match is case-sensitive.
926 ``keyword(string)``, the match is case-sensitive.
927 """
927 """
928 try:
928 try:
929 # i18n: "grep" is a keyword
929 # i18n: "grep" is a keyword
930 gr = re.compile(getstring(x, _("grep requires a string")))
930 gr = re.compile(getstring(x, _("grep requires a string")))
931 except re.error as e:
931 except re.error as e:
932 raise error.ParseError(_('invalid match pattern: %s') % e)
932 raise error.ParseError(_('invalid match pattern: %s') % e)
933
933
934 def matches(x):
934 def matches(x):
935 c = repo[x]
935 c = repo[x]
936 for e in c.files() + [c.user(), c.description()]:
936 for e in c.files() + [c.user(), c.description()]:
937 if gr.search(e):
937 if gr.search(e):
938 return True
938 return True
939 return False
939 return False
940
940
941 return subset.filter(matches, condrepr=('<grep %r>', gr.pattern))
941 return subset.filter(matches, condrepr=('<grep %r>', gr.pattern))
942
942
943 @predicate('_matchfiles', safe=True)
943 @predicate('_matchfiles', safe=True)
944 def _matchfiles(repo, subset, x):
944 def _matchfiles(repo, subset, x):
945 # _matchfiles takes a revset list of prefixed arguments:
945 # _matchfiles takes a revset list of prefixed arguments:
946 #
946 #
947 # [p:foo, i:bar, x:baz]
947 # [p:foo, i:bar, x:baz]
948 #
948 #
949 # builds a match object from them and filters subset. Allowed
949 # builds a match object from them and filters subset. Allowed
950 # prefixes are 'p:' for regular patterns, 'i:' for include
950 # prefixes are 'p:' for regular patterns, 'i:' for include
951 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
951 # patterns and 'x:' for exclude patterns. Use 'r:' prefix to pass
952 # a revision identifier, or the empty string to reference the
952 # a revision identifier, or the empty string to reference the
953 # working directory, from which the match object is
953 # working directory, from which the match object is
954 # initialized. Use 'd:' to set the default matching mode, default
954 # initialized. Use 'd:' to set the default matching mode, default
955 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
955 # to 'glob'. At most one 'r:' and 'd:' argument can be passed.
956
956
957 l = getargs(x, 1, -1, "_matchfiles requires at least one argument")
957 l = getargs(x, 1, -1, "_matchfiles requires at least one argument")
958 pats, inc, exc = [], [], []
958 pats, inc, exc = [], [], []
959 rev, default = None, None
959 rev, default = None, None
960 for arg in l:
960 for arg in l:
961 s = getstring(arg, "_matchfiles requires string arguments")
961 s = getstring(arg, "_matchfiles requires string arguments")
962 prefix, value = s[:2], s[2:]
962 prefix, value = s[:2], s[2:]
963 if prefix == 'p:':
963 if prefix == 'p:':
964 pats.append(value)
964 pats.append(value)
965 elif prefix == 'i:':
965 elif prefix == 'i:':
966 inc.append(value)
966 inc.append(value)
967 elif prefix == 'x:':
967 elif prefix == 'x:':
968 exc.append(value)
968 exc.append(value)
969 elif prefix == 'r:':
969 elif prefix == 'r:':
970 if rev is not None:
970 if rev is not None:
971 raise error.ParseError('_matchfiles expected at most one '
971 raise error.ParseError('_matchfiles expected at most one '
972 'revision')
972 'revision')
973 if value != '': # empty means working directory; leave rev as None
973 if value != '': # empty means working directory; leave rev as None
974 rev = value
974 rev = value
975 elif prefix == 'd:':
975 elif prefix == 'd:':
976 if default is not None:
976 if default is not None:
977 raise error.ParseError('_matchfiles expected at most one '
977 raise error.ParseError('_matchfiles expected at most one '
978 'default mode')
978 'default mode')
979 default = value
979 default = value
980 else:
980 else:
981 raise error.ParseError('invalid _matchfiles prefix: %s' % prefix)
981 raise error.ParseError('invalid _matchfiles prefix: %s' % prefix)
982 if not default:
982 if not default:
983 default = 'glob'
983 default = 'glob'
984
984
985 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
985 m = matchmod.match(repo.root, repo.getcwd(), pats, include=inc,
986 exclude=exc, ctx=repo[rev], default=default)
986 exclude=exc, ctx=repo[rev], default=default)
987
987
988 # This directly read the changelog data as creating changectx for all
988 # This directly read the changelog data as creating changectx for all
989 # revisions is quite expensive.
989 # revisions is quite expensive.
990 getfiles = repo.changelog.readfiles
990 getfiles = repo.changelog.readfiles
991 wdirrev = node.wdirrev
991 wdirrev = node.wdirrev
992 def matches(x):
992 def matches(x):
993 if x == wdirrev:
993 if x == wdirrev:
994 files = repo[x].files()
994 files = repo[x].files()
995 else:
995 else:
996 files = getfiles(x)
996 files = getfiles(x)
997 for f in files:
997 for f in files:
998 if m(f):
998 if m(f):
999 return True
999 return True
1000 return False
1000 return False
1001
1001
1002 return subset.filter(matches,
1002 return subset.filter(matches,
1003 condrepr=('<matchfiles patterns=%r, include=%r '
1003 condrepr=('<matchfiles patterns=%r, include=%r '
1004 'exclude=%r, default=%r, rev=%r>',
1004 'exclude=%r, default=%r, rev=%r>',
1005 pats, inc, exc, default, rev))
1005 pats, inc, exc, default, rev))
1006
1006
1007 @predicate('file(pattern)', safe=True)
1007 @predicate('file(pattern)', safe=True)
1008 def hasfile(repo, subset, x):
1008 def hasfile(repo, subset, x):
1009 """Changesets affecting files matched by pattern.
1009 """Changesets affecting files matched by pattern.
1010
1010
1011 For a faster but less accurate result, consider using ``filelog()``
1011 For a faster but less accurate result, consider using ``filelog()``
1012 instead.
1012 instead.
1013
1013
1014 This predicate uses ``glob:`` as the default kind of pattern.
1014 This predicate uses ``glob:`` as the default kind of pattern.
1015 """
1015 """
1016 # i18n: "file" is a keyword
1016 # i18n: "file" is a keyword
1017 pat = getstring(x, _("file requires a pattern"))
1017 pat = getstring(x, _("file requires a pattern"))
1018 return _matchfiles(repo, subset, ('string', 'p:' + pat))
1018 return _matchfiles(repo, subset, ('string', 'p:' + pat))
1019
1019
1020 @predicate('head()', safe=True)
1020 @predicate('head()', safe=True)
1021 def head(repo, subset, x):
1021 def head(repo, subset, x):
1022 """Changeset is a named branch head.
1022 """Changeset is a named branch head.
1023 """
1023 """
1024 # i18n: "head" is a keyword
1024 # i18n: "head" is a keyword
1025 getargs(x, 0, 0, _("head takes no arguments"))
1025 getargs(x, 0, 0, _("head takes no arguments"))
1026 hs = set()
1026 hs = set()
1027 cl = repo.changelog
1027 cl = repo.changelog
1028 for ls in repo.branchmap().itervalues():
1028 for ls in repo.branchmap().itervalues():
1029 hs.update(cl.rev(h) for h in ls)
1029 hs.update(cl.rev(h) for h in ls)
1030 return subset & baseset(hs)
1030 return subset & baseset(hs)
1031
1031
1032 @predicate('heads(set)', safe=True)
1032 @predicate('heads(set)', safe=True)
1033 def heads(repo, subset, x):
1033 def heads(repo, subset, x):
1034 """Members of set with no children in set.
1034 """Members of set with no children in set.
1035 """
1035 """
1036 s = getset(repo, subset, x)
1036 s = getset(repo, subset, x)
1037 ps = parents(repo, subset, x)
1037 ps = parents(repo, subset, x)
1038 return s - ps
1038 return s - ps
1039
1039
1040 @predicate('hidden()', safe=True)
1040 @predicate('hidden()', safe=True)
1041 def hidden(repo, subset, x):
1041 def hidden(repo, subset, x):
1042 """Hidden changesets.
1042 """Hidden changesets.
1043 """
1043 """
1044 # i18n: "hidden" is a keyword
1044 # i18n: "hidden" is a keyword
1045 getargs(x, 0, 0, _("hidden takes no arguments"))
1045 getargs(x, 0, 0, _("hidden takes no arguments"))
1046 hiddenrevs = repoview.filterrevs(repo, 'visible')
1046 hiddenrevs = repoview.filterrevs(repo, 'visible')
1047 return subset & hiddenrevs
1047 return subset & hiddenrevs
1048
1048
1049 @predicate('keyword(string)', safe=True)
1049 @predicate('keyword(string)', safe=True)
1050 def keyword(repo, subset, x):
1050 def keyword(repo, subset, x):
1051 """Search commit message, user name, and names of changed files for
1051 """Search commit message, user name, and names of changed files for
1052 string. The match is case-insensitive.
1052 string. The match is case-insensitive.
1053
1053
1054 For a regular expression or case sensitive search of these fields, use
1054 For a regular expression or case sensitive search of these fields, use
1055 ``grep(regex)``.
1055 ``grep(regex)``.
1056 """
1056 """
1057 # i18n: "keyword" is a keyword
1057 # i18n: "keyword" is a keyword
1058 kw = encoding.lower(getstring(x, _("keyword requires a string")))
1058 kw = encoding.lower(getstring(x, _("keyword requires a string")))
1059
1059
1060 def matches(r):
1060 def matches(r):
1061 c = repo[r]
1061 c = repo[r]
1062 return any(kw in encoding.lower(t)
1062 return any(kw in encoding.lower(t)
1063 for t in c.files() + [c.user(), c.description()])
1063 for t in c.files() + [c.user(), c.description()])
1064
1064
1065 return subset.filter(matches, condrepr=('<keyword %r>', kw))
1065 return subset.filter(matches, condrepr=('<keyword %r>', kw))
1066
1066
1067 @predicate('limit(set[, n[, offset]])', safe=True, takeorder=True)
1067 @predicate('limit(set[, n[, offset]])', safe=True, takeorder=True)
1068 def limit(repo, subset, x, order):
1068 def limit(repo, subset, x, order):
1069 """First n members of set, defaulting to 1, starting from offset.
1069 """First n members of set, defaulting to 1, starting from offset.
1070 """
1070 """
1071 args = getargsdict(x, 'limit', 'set n offset')
1071 args = getargsdict(x, 'limit', 'set n offset')
1072 if 'set' not in args:
1072 if 'set' not in args:
1073 # i18n: "limit" is a keyword
1073 # i18n: "limit" is a keyword
1074 raise error.ParseError(_("limit requires one to three arguments"))
1074 raise error.ParseError(_("limit requires one to three arguments"))
1075 # i18n: "limit" is a keyword
1075 # i18n: "limit" is a keyword
1076 lim = getinteger(args.get('n'), _("limit expects a number"), default=1)
1076 lim = getinteger(args.get('n'), _("limit expects a number"), default=1)
1077 if lim < 0:
1077 if lim < 0:
1078 raise error.ParseError(_("negative number to select"))
1078 raise error.ParseError(_("negative number to select"))
1079 # i18n: "limit" is a keyword
1079 # i18n: "limit" is a keyword
1080 ofs = getinteger(args.get('offset'), _("limit expects a number"), default=0)
1080 ofs = getinteger(args.get('offset'), _("limit expects a number"), default=0)
1081 if ofs < 0:
1081 if ofs < 0:
1082 raise error.ParseError(_("negative offset"))
1082 raise error.ParseError(_("negative offset"))
1083 os = getset(repo, fullreposet(repo), args['set'])
1083 os = getset(repo, fullreposet(repo), args['set'])
1084 ls = os.slice(ofs, ofs + lim)
1084 ls = os.slice(ofs, ofs + lim)
1085 if order == followorder and lim > 1:
1085 if order == followorder and lim > 1:
1086 return subset & ls
1086 return subset & ls
1087 return ls & subset
1087 return ls & subset
1088
1088
1089 @predicate('last(set, [n])', safe=True, takeorder=True)
1089 @predicate('last(set, [n])', safe=True, takeorder=True)
1090 def last(repo, subset, x, order):
1090 def last(repo, subset, x, order):
1091 """Last n members of set, defaulting to 1.
1091 """Last n members of set, defaulting to 1.
1092 """
1092 """
1093 # i18n: "last" is a keyword
1093 # i18n: "last" is a keyword
1094 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1094 l = getargs(x, 1, 2, _("last requires one or two arguments"))
1095 lim = 1
1095 lim = 1
1096 if len(l) == 2:
1096 if len(l) == 2:
1097 # i18n: "last" is a keyword
1097 # i18n: "last" is a keyword
1098 lim = getinteger(l[1], _("last expects a number"))
1098 lim = getinteger(l[1], _("last expects a number"))
1099 if lim < 0:
1099 if lim < 0:
1100 raise error.ParseError(_("negative number to select"))
1100 raise error.ParseError(_("negative number to select"))
1101 os = getset(repo, fullreposet(repo), l[0])
1101 os = getset(repo, fullreposet(repo), l[0])
1102 os.reverse()
1102 os.reverse()
1103 ls = os.slice(0, lim)
1103 ls = os.slice(0, lim)
1104 if order == followorder and lim > 1:
1104 if order == followorder and lim > 1:
1105 return subset & ls
1105 return subset & ls
1106 ls.reverse()
1106 ls.reverse()
1107 return ls & subset
1107 return ls & subset
1108
1108
1109 @predicate('max(set)', safe=True)
1109 @predicate('max(set)', safe=True)
1110 def maxrev(repo, subset, x):
1110 def maxrev(repo, subset, x):
1111 """Changeset with highest revision number in set.
1111 """Changeset with highest revision number in set.
1112 """
1112 """
1113 os = getset(repo, fullreposet(repo), x)
1113 os = getset(repo, fullreposet(repo), x)
1114 try:
1114 try:
1115 m = os.max()
1115 m = os.max()
1116 if m in subset:
1116 if m in subset:
1117 return baseset([m], datarepr=('<max %r, %r>', subset, os))
1117 return baseset([m], datarepr=('<max %r, %r>', subset, os))
1118 except ValueError:
1118 except ValueError:
1119 # os.max() throws a ValueError when the collection is empty.
1119 # os.max() throws a ValueError when the collection is empty.
1120 # Same as python's max().
1120 # Same as python's max().
1121 pass
1121 pass
1122 return baseset(datarepr=('<max %r, %r>', subset, os))
1122 return baseset(datarepr=('<max %r, %r>', subset, os))
1123
1123
1124 @predicate('merge()', safe=True)
1124 @predicate('merge()', safe=True)
1125 def merge(repo, subset, x):
1125 def merge(repo, subset, x):
1126 """Changeset is a merge changeset.
1126 """Changeset is a merge changeset.
1127 """
1127 """
1128 # i18n: "merge" is a keyword
1128 # i18n: "merge" is a keyword
1129 getargs(x, 0, 0, _("merge takes no arguments"))
1129 getargs(x, 0, 0, _("merge takes no arguments"))
1130 cl = repo.changelog
1130 cl = repo.changelog
1131 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1,
1131 return subset.filter(lambda r: cl.parentrevs(r)[1] != -1,
1132 condrepr='<merge>')
1132 condrepr='<merge>')
1133
1133
1134 @predicate('branchpoint()', safe=True)
1134 @predicate('branchpoint()', safe=True)
1135 def branchpoint(repo, subset, x):
1135 def branchpoint(repo, subset, x):
1136 """Changesets with more than one child.
1136 """Changesets with more than one child.
1137 """
1137 """
1138 # i18n: "branchpoint" is a keyword
1138 # i18n: "branchpoint" is a keyword
1139 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1139 getargs(x, 0, 0, _("branchpoint takes no arguments"))
1140 cl = repo.changelog
1140 cl = repo.changelog
1141 if not subset:
1141 if not subset:
1142 return baseset()
1142 return baseset()
1143 # XXX this should be 'parentset.min()' assuming 'parentset' is a smartset
1143 # XXX this should be 'parentset.min()' assuming 'parentset' is a smartset
1144 # (and if it is not, it should.)
1144 # (and if it is not, it should.)
1145 baserev = min(subset)
1145 baserev = min(subset)
1146 parentscount = [0]*(len(repo) - baserev)
1146 parentscount = [0]*(len(repo) - baserev)
1147 for r in cl.revs(start=baserev + 1):
1147 for r in cl.revs(start=baserev + 1):
1148 for p in cl.parentrevs(r):
1148 for p in cl.parentrevs(r):
1149 if p >= baserev:
1149 if p >= baserev:
1150 parentscount[p - baserev] += 1
1150 parentscount[p - baserev] += 1
1151 return subset.filter(lambda r: parentscount[r - baserev] > 1,
1151 return subset.filter(lambda r: parentscount[r - baserev] > 1,
1152 condrepr='<branchpoint>')
1152 condrepr='<branchpoint>')
1153
1153
1154 @predicate('min(set)', safe=True)
1154 @predicate('min(set)', safe=True)
1155 def minrev(repo, subset, x):
1155 def minrev(repo, subset, x):
1156 """Changeset with lowest revision number in set.
1156 """Changeset with lowest revision number in set.
1157 """
1157 """
1158 os = getset(repo, fullreposet(repo), x)
1158 os = getset(repo, fullreposet(repo), x)
1159 try:
1159 try:
1160 m = os.min()
1160 m = os.min()
1161 if m in subset:
1161 if m in subset:
1162 return baseset([m], datarepr=('<min %r, %r>', subset, os))
1162 return baseset([m], datarepr=('<min %r, %r>', subset, os))
1163 except ValueError:
1163 except ValueError:
1164 # os.min() throws a ValueError when the collection is empty.
1164 # os.min() throws a ValueError when the collection is empty.
1165 # Same as python's min().
1165 # Same as python's min().
1166 pass
1166 pass
1167 return baseset(datarepr=('<min %r, %r>', subset, os))
1167 return baseset(datarepr=('<min %r, %r>', subset, os))
1168
1168
1169 @predicate('modifies(pattern)', safe=True)
1169 @predicate('modifies(pattern)', safe=True)
1170 def modifies(repo, subset, x):
1170 def modifies(repo, subset, x):
1171 """Changesets modifying files matched by pattern.
1171 """Changesets modifying files matched by pattern.
1172
1172
1173 The pattern without explicit kind like ``glob:`` is expected to be
1173 The pattern without explicit kind like ``glob:`` is expected to be
1174 relative to the current directory and match against a file or a
1174 relative to the current directory and match against a file or a
1175 directory.
1175 directory.
1176 """
1176 """
1177 # i18n: "modifies" is a keyword
1177 # i18n: "modifies" is a keyword
1178 pat = getstring(x, _("modifies requires a pattern"))
1178 pat = getstring(x, _("modifies requires a pattern"))
1179 return checkstatus(repo, subset, pat, 0)
1179 return checkstatus(repo, subset, pat, 0)
1180
1180
1181 @predicate('named(namespace)')
1181 @predicate('named(namespace)')
1182 def named(repo, subset, x):
1182 def named(repo, subset, x):
1183 """The changesets in a given namespace.
1183 """The changesets in a given namespace.
1184
1184
1185 Pattern matching is supported for `namespace`. See
1185 Pattern matching is supported for `namespace`. See
1186 :hg:`help revisions.patterns`.
1186 :hg:`help revisions.patterns`.
1187 """
1187 """
1188 # i18n: "named" is a keyword
1188 # i18n: "named" is a keyword
1189 args = getargs(x, 1, 1, _('named requires a namespace argument'))
1189 args = getargs(x, 1, 1, _('named requires a namespace argument'))
1190
1190
1191 ns = getstring(args[0],
1191 ns = getstring(args[0],
1192 # i18n: "named" is a keyword
1192 # i18n: "named" is a keyword
1193 _('the argument to named must be a string'))
1193 _('the argument to named must be a string'))
1194 kind, pattern, matcher = util.stringmatcher(ns)
1194 kind, pattern, matcher = util.stringmatcher(ns)
1195 namespaces = set()
1195 namespaces = set()
1196 if kind == 'literal':
1196 if kind == 'literal':
1197 if pattern not in repo.names:
1197 if pattern not in repo.names:
1198 raise error.RepoLookupError(_("namespace '%s' does not exist")
1198 raise error.RepoLookupError(_("namespace '%s' does not exist")
1199 % ns)
1199 % ns)
1200 namespaces.add(repo.names[pattern])
1200 namespaces.add(repo.names[pattern])
1201 else:
1201 else:
1202 for name, ns in repo.names.iteritems():
1202 for name, ns in repo.names.iteritems():
1203 if matcher(name):
1203 if matcher(name):
1204 namespaces.add(ns)
1204 namespaces.add(ns)
1205 if not namespaces:
1205 if not namespaces:
1206 raise error.RepoLookupError(_("no namespace exists"
1206 raise error.RepoLookupError(_("no namespace exists"
1207 " that match '%s'") % pattern)
1207 " that match '%s'") % pattern)
1208
1208
1209 names = set()
1209 names = set()
1210 for ns in namespaces:
1210 for ns in namespaces:
1211 for name in ns.listnames(repo):
1211 for name in ns.listnames(repo):
1212 if name not in ns.deprecated:
1212 if name not in ns.deprecated:
1213 names.update(repo[n].rev() for n in ns.nodes(repo, name))
1213 names.update(repo[n].rev() for n in ns.nodes(repo, name))
1214
1214
1215 names -= {node.nullrev}
1215 names -= {node.nullrev}
1216 return subset & names
1216 return subset & names
1217
1217
1218 @predicate('id(string)', safe=True)
1218 @predicate('id(string)', safe=True)
1219 def node_(repo, subset, x):
1219 def node_(repo, subset, x):
1220 """Revision non-ambiguously specified by the given hex string prefix.
1220 """Revision non-ambiguously specified by the given hex string prefix.
1221 """
1221 """
1222 # i18n: "id" is a keyword
1222 # i18n: "id" is a keyword
1223 l = getargs(x, 1, 1, _("id requires one argument"))
1223 l = getargs(x, 1, 1, _("id requires one argument"))
1224 # i18n: "id" is a keyword
1224 # i18n: "id" is a keyword
1225 n = getstring(l[0], _("id requires a string"))
1225 n = getstring(l[0], _("id requires a string"))
1226 if len(n) == 40:
1226 if len(n) == 40:
1227 try:
1227 try:
1228 rn = repo.changelog.rev(node.bin(n))
1228 rn = repo.changelog.rev(node.bin(n))
1229 except error.WdirUnsupported:
1229 except error.WdirUnsupported:
1230 rn = node.wdirrev
1230 rn = node.wdirrev
1231 except (LookupError, TypeError):
1231 except (LookupError, TypeError):
1232 rn = None
1232 rn = None
1233 else:
1233 else:
1234 rn = None
1234 rn = None
1235 try:
1235 try:
1236 pm = repo.changelog._partialmatch(n)
1236 pm = repo.changelog._partialmatch(n)
1237 if pm is not None:
1237 if pm is not None:
1238 rn = repo.changelog.rev(pm)
1238 rn = repo.changelog.rev(pm)
1239 except error.WdirUnsupported:
1239 except error.WdirUnsupported:
1240 rn = node.wdirrev
1240 rn = node.wdirrev
1241
1241
1242 if rn is None:
1242 if rn is None:
1243 return baseset()
1243 return baseset()
1244 result = baseset([rn])
1244 result = baseset([rn])
1245 return result & subset
1245 return result & subset
1246
1246
1247 @predicate('obsolete()', safe=True)
1247 @predicate('obsolete()', safe=True)
1248 def obsolete(repo, subset, x):
1248 def obsolete(repo, subset, x):
1249 """Mutable changeset with a newer version."""
1249 """Mutable changeset with a newer version."""
1250 # i18n: "obsolete" is a keyword
1250 # i18n: "obsolete" is a keyword
1251 getargs(x, 0, 0, _("obsolete takes no arguments"))
1251 getargs(x, 0, 0, _("obsolete takes no arguments"))
1252 obsoletes = obsmod.getrevs(repo, 'obsolete')
1252 obsoletes = obsmod.getrevs(repo, 'obsolete')
1253 return subset & obsoletes
1253 return subset & obsoletes
1254
1254
1255 @predicate('only(set, [set])', safe=True)
1255 @predicate('only(set, [set])', safe=True)
1256 def only(repo, subset, x):
1256 def only(repo, subset, x):
1257 """Changesets that are ancestors of the first set that are not ancestors
1257 """Changesets that are ancestors of the first set that are not ancestors
1258 of any other head in the repo. If a second set is specified, the result
1258 of any other head in the repo. If a second set is specified, the result
1259 is ancestors of the first set that are not ancestors of the second set
1259 is ancestors of the first set that are not ancestors of the second set
1260 (i.e. ::<set1> - ::<set2>).
1260 (i.e. ::<set1> - ::<set2>).
1261 """
1261 """
1262 cl = repo.changelog
1262 cl = repo.changelog
1263 # i18n: "only" is a keyword
1263 # i18n: "only" is a keyword
1264 args = getargs(x, 1, 2, _('only takes one or two arguments'))
1264 args = getargs(x, 1, 2, _('only takes one or two arguments'))
1265 include = getset(repo, fullreposet(repo), args[0])
1265 include = getset(repo, fullreposet(repo), args[0])
1266 if len(args) == 1:
1266 if len(args) == 1:
1267 if not include:
1267 if not include:
1268 return baseset()
1268 return baseset()
1269
1269
1270 descendants = set(dagop.revdescendants(repo, include, False))
1270 descendants = set(dagop.revdescendants(repo, include, False))
1271 exclude = [rev for rev in cl.headrevs()
1271 exclude = [rev for rev in cl.headrevs()
1272 if not rev in descendants and not rev in include]
1272 if not rev in descendants and not rev in include]
1273 else:
1273 else:
1274 exclude = getset(repo, fullreposet(repo), args[1])
1274 exclude = getset(repo, fullreposet(repo), args[1])
1275
1275
1276 results = set(cl.findmissingrevs(common=exclude, heads=include))
1276 results = set(cl.findmissingrevs(common=exclude, heads=include))
1277 # XXX we should turn this into a baseset instead of a set, smartset may do
1277 # XXX we should turn this into a baseset instead of a set, smartset may do
1278 # some optimizations from the fact this is a baseset.
1278 # some optimizations from the fact this is a baseset.
1279 return subset & results
1279 return subset & results
1280
1280
1281 @predicate('origin([set])', safe=True)
1281 @predicate('origin([set])', safe=True)
1282 def origin(repo, subset, x):
1282 def origin(repo, subset, x):
1283 """
1283 """
1284 Changesets that were specified as a source for the grafts, transplants or
1284 Changesets that were specified as a source for the grafts, transplants or
1285 rebases that created the given revisions. Omitting the optional set is the
1285 rebases that created the given revisions. Omitting the optional set is the
1286 same as passing all(). If a changeset created by these operations is itself
1286 same as passing all(). If a changeset created by these operations is itself
1287 specified as a source for one of these operations, only the source changeset
1287 specified as a source for one of these operations, only the source changeset
1288 for the first operation is selected.
1288 for the first operation is selected.
1289 """
1289 """
1290 if x is not None:
1290 if x is not None:
1291 dests = getset(repo, fullreposet(repo), x)
1291 dests = getset(repo, fullreposet(repo), x)
1292 else:
1292 else:
1293 dests = fullreposet(repo)
1293 dests = fullreposet(repo)
1294
1294
1295 def _firstsrc(rev):
1295 def _firstsrc(rev):
1296 src = _getrevsource(repo, rev)
1296 src = _getrevsource(repo, rev)
1297 if src is None:
1297 if src is None:
1298 return None
1298 return None
1299
1299
1300 while True:
1300 while True:
1301 prev = _getrevsource(repo, src)
1301 prev = _getrevsource(repo, src)
1302
1302
1303 if prev is None:
1303 if prev is None:
1304 return src
1304 return src
1305 src = prev
1305 src = prev
1306
1306
1307 o = {_firstsrc(r) for r in dests}
1307 o = {_firstsrc(r) for r in dests}
1308 o -= {None}
1308 o -= {None}
1309 # XXX we should turn this into a baseset instead of a set, smartset may do
1309 # XXX we should turn this into a baseset instead of a set, smartset may do
1310 # some optimizations from the fact this is a baseset.
1310 # some optimizations from the fact this is a baseset.
1311 return subset & o
1311 return subset & o
1312
1312
1313 @predicate('outgoing([path])', safe=False)
1313 @predicate('outgoing([path])', safe=False)
1314 def outgoing(repo, subset, x):
1314 def outgoing(repo, subset, x):
1315 """Changesets not found in the specified destination repository, or the
1315 """Changesets not found in the specified destination repository, or the
1316 default push location.
1316 default push location.
1317 """
1317 """
1318 # Avoid cycles.
1318 # Avoid cycles.
1319 from . import (
1319 from . import (
1320 discovery,
1320 discovery,
1321 hg,
1321 hg,
1322 )
1322 )
1323 # i18n: "outgoing" is a keyword
1323 # i18n: "outgoing" is a keyword
1324 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1324 l = getargs(x, 0, 1, _("outgoing takes one or no arguments"))
1325 # i18n: "outgoing" is a keyword
1325 # i18n: "outgoing" is a keyword
1326 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1326 dest = l and getstring(l[0], _("outgoing requires a repository path")) or ''
1327 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1327 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
1328 dest, branches = hg.parseurl(dest)
1328 dest, branches = hg.parseurl(dest)
1329 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1329 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1330 if revs:
1330 if revs:
1331 revs = [repo.lookup(rev) for rev in revs]
1331 revs = [repo.lookup(rev) for rev in revs]
1332 other = hg.peer(repo, {}, dest)
1332 other = hg.peer(repo, {}, dest)
1333 repo.ui.pushbuffer()
1333 repo.ui.pushbuffer()
1334 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1334 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs)
1335 repo.ui.popbuffer()
1335 repo.ui.popbuffer()
1336 cl = repo.changelog
1336 cl = repo.changelog
1337 o = {cl.rev(r) for r in outgoing.missing}
1337 o = {cl.rev(r) for r in outgoing.missing}
1338 return subset & o
1338 return subset & o
1339
1339
1340 @predicate('p1([set])', safe=True)
1340 @predicate('p1([set])', safe=True)
1341 def p1(repo, subset, x):
1341 def p1(repo, subset, x):
1342 """First parent of changesets in set, or the working directory.
1342 """First parent of changesets in set, or the working directory.
1343 """
1343 """
1344 if x is None:
1344 if x is None:
1345 p = repo[x].p1().rev()
1345 p = repo[x].p1().rev()
1346 if p >= 0:
1346 if p >= 0:
1347 return subset & baseset([p])
1347 return subset & baseset([p])
1348 return baseset()
1348 return baseset()
1349
1349
1350 ps = set()
1350 ps = set()
1351 cl = repo.changelog
1351 cl = repo.changelog
1352 for r in getset(repo, fullreposet(repo), x):
1352 for r in getset(repo, fullreposet(repo), x):
1353 try:
1353 try:
1354 ps.add(cl.parentrevs(r)[0])
1354 ps.add(cl.parentrevs(r)[0])
1355 except error.WdirUnsupported:
1355 except error.WdirUnsupported:
1356 ps.add(repo[r].parents()[0].rev())
1356 ps.add(repo[r].parents()[0].rev())
1357 ps -= {node.nullrev}
1357 ps -= {node.nullrev}
1358 # XXX we should turn this into a baseset instead of a set, smartset may do
1358 # XXX we should turn this into a baseset instead of a set, smartset may do
1359 # some optimizations from the fact this is a baseset.
1359 # some optimizations from the fact this is a baseset.
1360 return subset & ps
1360 return subset & ps
1361
1361
1362 @predicate('p2([set])', safe=True)
1362 @predicate('p2([set])', safe=True)
1363 def p2(repo, subset, x):
1363 def p2(repo, subset, x):
1364 """Second parent of changesets in set, or the working directory.
1364 """Second parent of changesets in set, or the working directory.
1365 """
1365 """
1366 if x is None:
1366 if x is None:
1367 ps = repo[x].parents()
1367 ps = repo[x].parents()
1368 try:
1368 try:
1369 p = ps[1].rev()
1369 p = ps[1].rev()
1370 if p >= 0:
1370 if p >= 0:
1371 return subset & baseset([p])
1371 return subset & baseset([p])
1372 return baseset()
1372 return baseset()
1373 except IndexError:
1373 except IndexError:
1374 return baseset()
1374 return baseset()
1375
1375
1376 ps = set()
1376 ps = set()
1377 cl = repo.changelog
1377 cl = repo.changelog
1378 for r in getset(repo, fullreposet(repo), x):
1378 for r in getset(repo, fullreposet(repo), x):
1379 try:
1379 try:
1380 ps.add(cl.parentrevs(r)[1])
1380 ps.add(cl.parentrevs(r)[1])
1381 except error.WdirUnsupported:
1381 except error.WdirUnsupported:
1382 parents = repo[r].parents()
1382 parents = repo[r].parents()
1383 if len(parents) == 2:
1383 if len(parents) == 2:
1384 ps.add(parents[1])
1384 ps.add(parents[1])
1385 ps -= {node.nullrev}
1385 ps -= {node.nullrev}
1386 # XXX we should turn this into a baseset instead of a set, smartset may do
1386 # XXX we should turn this into a baseset instead of a set, smartset may do
1387 # some optimizations from the fact this is a baseset.
1387 # some optimizations from the fact this is a baseset.
1388 return subset & ps
1388 return subset & ps
1389
1389
1390 def parentpost(repo, subset, x, order):
1390 def parentpost(repo, subset, x, order):
1391 return p1(repo, subset, x)
1391 return p1(repo, subset, x)
1392
1392
1393 @predicate('parents([set])', safe=True)
1393 @predicate('parents([set])', safe=True)
1394 def parents(repo, subset, x):
1394 def parents(repo, subset, x):
1395 """
1395 """
1396 The set of all parents for all changesets in set, or the working directory.
1396 The set of all parents for all changesets in set, or the working directory.
1397 """
1397 """
1398 if x is None:
1398 if x is None:
1399 ps = set(p.rev() for p in repo[x].parents())
1399 ps = set(p.rev() for p in repo[x].parents())
1400 else:
1400 else:
1401 ps = set()
1401 ps = set()
1402 cl = repo.changelog
1402 cl = repo.changelog
1403 up = ps.update
1403 up = ps.update
1404 parentrevs = cl.parentrevs
1404 parentrevs = cl.parentrevs
1405 for r in getset(repo, fullreposet(repo), x):
1405 for r in getset(repo, fullreposet(repo), x):
1406 try:
1406 try:
1407 up(parentrevs(r))
1407 up(parentrevs(r))
1408 except error.WdirUnsupported:
1408 except error.WdirUnsupported:
1409 up(p.rev() for p in repo[r].parents())
1409 up(p.rev() for p in repo[r].parents())
1410 ps -= {node.nullrev}
1410 ps -= {node.nullrev}
1411 return subset & ps
1411 return subset & ps
1412
1412
1413 def _phase(repo, subset, *targets):
1413 def _phase(repo, subset, *targets):
1414 """helper to select all rev in <targets> phases"""
1414 """helper to select all rev in <targets> phases"""
1415 s = repo._phasecache.getrevset(repo, targets)
1415 s = repo._phasecache.getrevset(repo, targets)
1416 return subset & s
1416 return subset & s
1417
1417
1418 @predicate('draft()', safe=True)
1418 @predicate('draft()', safe=True)
1419 def draft(repo, subset, x):
1419 def draft(repo, subset, x):
1420 """Changeset in draft phase."""
1420 """Changeset in draft phase."""
1421 # i18n: "draft" is a keyword
1421 # i18n: "draft" is a keyword
1422 getargs(x, 0, 0, _("draft takes no arguments"))
1422 getargs(x, 0, 0, _("draft takes no arguments"))
1423 target = phases.draft
1423 target = phases.draft
1424 return _phase(repo, subset, target)
1424 return _phase(repo, subset, target)
1425
1425
1426 @predicate('secret()', safe=True)
1426 @predicate('secret()', safe=True)
1427 def secret(repo, subset, x):
1427 def secret(repo, subset, x):
1428 """Changeset in secret phase."""
1428 """Changeset in secret phase."""
1429 # i18n: "secret" is a keyword
1429 # i18n: "secret" is a keyword
1430 getargs(x, 0, 0, _("secret takes no arguments"))
1430 getargs(x, 0, 0, _("secret takes no arguments"))
1431 target = phases.secret
1431 target = phases.secret
1432 return _phase(repo, subset, target)
1432 return _phase(repo, subset, target)
1433
1433
1434 def parentspec(repo, subset, x, n, order):
1434 def parentspec(repo, subset, x, n, order):
1435 """``set^0``
1435 """``set^0``
1436 The set.
1436 The set.
1437 ``set^1`` (or ``set^``), ``set^2``
1437 ``set^1`` (or ``set^``), ``set^2``
1438 First or second parent, respectively, of all changesets in set.
1438 First or second parent, respectively, of all changesets in set.
1439 """
1439 """
1440 try:
1440 try:
1441 n = int(n[1])
1441 n = int(n[1])
1442 if n not in (0, 1, 2):
1442 if n not in (0, 1, 2):
1443 raise ValueError
1443 raise ValueError
1444 except (TypeError, ValueError):
1444 except (TypeError, ValueError):
1445 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1445 raise error.ParseError(_("^ expects a number 0, 1, or 2"))
1446 ps = set()
1446 ps = set()
1447 cl = repo.changelog
1447 cl = repo.changelog
1448 for r in getset(repo, fullreposet(repo), x):
1448 for r in getset(repo, fullreposet(repo), x):
1449 if n == 0:
1449 if n == 0:
1450 ps.add(r)
1450 ps.add(r)
1451 elif n == 1:
1451 elif n == 1:
1452 try:
1452 try:
1453 ps.add(cl.parentrevs(r)[0])
1453 ps.add(cl.parentrevs(r)[0])
1454 except error.WdirUnsupported:
1454 except error.WdirUnsupported:
1455 ps.add(repo[r].parents()[0].rev())
1455 ps.add(repo[r].parents()[0].rev())
1456 else:
1456 else:
1457 try:
1457 try:
1458 parents = cl.parentrevs(r)
1458 parents = cl.parentrevs(r)
1459 if parents[1] != node.nullrev:
1459 if parents[1] != node.nullrev:
1460 ps.add(parents[1])
1460 ps.add(parents[1])
1461 except error.WdirUnsupported:
1461 except error.WdirUnsupported:
1462 parents = repo[r].parents()
1462 parents = repo[r].parents()
1463 if len(parents) == 2:
1463 if len(parents) == 2:
1464 ps.add(parents[1].rev())
1464 ps.add(parents[1].rev())
1465 return subset & ps
1465 return subset & ps
1466
1466
1467 @predicate('present(set)', safe=True)
1467 @predicate('present(set)', safe=True)
1468 def present(repo, subset, x):
1468 def present(repo, subset, x):
1469 """An empty set, if any revision in set isn't found; otherwise,
1469 """An empty set, if any revision in set isn't found; otherwise,
1470 all revisions in set.
1470 all revisions in set.
1471
1471
1472 If any of specified revisions is not present in the local repository,
1472 If any of specified revisions is not present in the local repository,
1473 the query is normally aborted. But this predicate allows the query
1473 the query is normally aborted. But this predicate allows the query
1474 to continue even in such cases.
1474 to continue even in such cases.
1475 """
1475 """
1476 try:
1476 try:
1477 return getset(repo, subset, x)
1477 return getset(repo, subset, x)
1478 except error.RepoLookupError:
1478 except error.RepoLookupError:
1479 return baseset()
1479 return baseset()
1480
1480
1481 # for internal use
1481 # for internal use
1482 @predicate('_notpublic', safe=True)
1482 @predicate('_notpublic', safe=True)
1483 def _notpublic(repo, subset, x):
1483 def _notpublic(repo, subset, x):
1484 getargs(x, 0, 0, "_notpublic takes no arguments")
1484 getargs(x, 0, 0, "_notpublic takes no arguments")
1485 return _phase(repo, subset, phases.draft, phases.secret)
1485 return _phase(repo, subset, phases.draft, phases.secret)
1486
1486
1487 @predicate('public()', safe=True)
1487 @predicate('public()', safe=True)
1488 def public(repo, subset, x):
1488 def public(repo, subset, x):
1489 """Changeset in public phase."""
1489 """Changeset in public phase."""
1490 # i18n: "public" is a keyword
1490 # i18n: "public" is a keyword
1491 getargs(x, 0, 0, _("public takes no arguments"))
1491 getargs(x, 0, 0, _("public takes no arguments"))
1492 phase = repo._phasecache.phase
1492 phase = repo._phasecache.phase
1493 target = phases.public
1493 target = phases.public
1494 condition = lambda r: phase(repo, r) == target
1494 condition = lambda r: phase(repo, r) == target
1495 return subset.filter(condition, condrepr=('<phase %r>', target),
1495 return subset.filter(condition, condrepr=('<phase %r>', target),
1496 cache=False)
1496 cache=False)
1497
1497
1498 @predicate('remote([id [,path]])', safe=False)
1498 @predicate('remote([id [,path]])', safe=False)
1499 def remote(repo, subset, x):
1499 def remote(repo, subset, x):
1500 """Local revision that corresponds to the given identifier in a
1500 """Local revision that corresponds to the given identifier in a
1501 remote repository, if present. Here, the '.' identifier is a
1501 remote repository, if present. Here, the '.' identifier is a
1502 synonym for the current local branch.
1502 synonym for the current local branch.
1503 """
1503 """
1504
1504
1505 from . import hg # avoid start-up nasties
1505 from . import hg # avoid start-up nasties
1506 # i18n: "remote" is a keyword
1506 # i18n: "remote" is a keyword
1507 l = getargs(x, 0, 2, _("remote takes zero, one, or two arguments"))
1507 l = getargs(x, 0, 2, _("remote takes zero, one, or two arguments"))
1508
1508
1509 q = '.'
1509 q = '.'
1510 if len(l) > 0:
1510 if len(l) > 0:
1511 # i18n: "remote" is a keyword
1511 # i18n: "remote" is a keyword
1512 q = getstring(l[0], _("remote requires a string id"))
1512 q = getstring(l[0], _("remote requires a string id"))
1513 if q == '.':
1513 if q == '.':
1514 q = repo['.'].branch()
1514 q = repo['.'].branch()
1515
1515
1516 dest = ''
1516 dest = ''
1517 if len(l) > 1:
1517 if len(l) > 1:
1518 # i18n: "remote" is a keyword
1518 # i18n: "remote" is a keyword
1519 dest = getstring(l[1], _("remote requires a repository path"))
1519 dest = getstring(l[1], _("remote requires a repository path"))
1520 dest = repo.ui.expandpath(dest or 'default')
1520 dest = repo.ui.expandpath(dest or 'default')
1521 dest, branches = hg.parseurl(dest)
1521 dest, branches = hg.parseurl(dest)
1522 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1522 revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
1523 if revs:
1523 if revs:
1524 revs = [repo.lookup(rev) for rev in revs]
1524 revs = [repo.lookup(rev) for rev in revs]
1525 other = hg.peer(repo, {}, dest)
1525 other = hg.peer(repo, {}, dest)
1526 n = other.lookup(q)
1526 n = other.lookup(q)
1527 if n in repo:
1527 if n in repo:
1528 r = repo[n].rev()
1528 r = repo[n].rev()
1529 if r in subset:
1529 if r in subset:
1530 return baseset([r])
1530 return baseset([r])
1531 return baseset()
1531 return baseset()
1532
1532
1533 @predicate('removes(pattern)', safe=True)
1533 @predicate('removes(pattern)', safe=True)
1534 def removes(repo, subset, x):
1534 def removes(repo, subset, x):
1535 """Changesets which remove files matching pattern.
1535 """Changesets which remove files matching pattern.
1536
1536
1537 The pattern without explicit kind like ``glob:`` is expected to be
1537 The pattern without explicit kind like ``glob:`` is expected to be
1538 relative to the current directory and match against a file or a
1538 relative to the current directory and match against a file or a
1539 directory.
1539 directory.
1540 """
1540 """
1541 # i18n: "removes" is a keyword
1541 # i18n: "removes" is a keyword
1542 pat = getstring(x, _("removes requires a pattern"))
1542 pat = getstring(x, _("removes requires a pattern"))
1543 return checkstatus(repo, subset, pat, 2)
1543 return checkstatus(repo, subset, pat, 2)
1544
1544
1545 @predicate('rev(number)', safe=True)
1545 @predicate('rev(number)', safe=True)
1546 def rev(repo, subset, x):
1546 def rev(repo, subset, x):
1547 """Revision with the given numeric identifier.
1547 """Revision with the given numeric identifier.
1548 """
1548 """
1549 # i18n: "rev" is a keyword
1549 # i18n: "rev" is a keyword
1550 l = getargs(x, 1, 1, _("rev requires one argument"))
1550 l = getargs(x, 1, 1, _("rev requires one argument"))
1551 try:
1551 try:
1552 # i18n: "rev" is a keyword
1552 # i18n: "rev" is a keyword
1553 l = int(getstring(l[0], _("rev requires a number")))
1553 l = int(getstring(l[0], _("rev requires a number")))
1554 except (TypeError, ValueError):
1554 except (TypeError, ValueError):
1555 # i18n: "rev" is a keyword
1555 # i18n: "rev" is a keyword
1556 raise error.ParseError(_("rev expects a number"))
1556 raise error.ParseError(_("rev expects a number"))
1557 if l not in repo.changelog and l not in (node.nullrev, node.wdirrev):
1557 if l not in repo.changelog and l not in (node.nullrev, node.wdirrev):
1558 return baseset()
1558 return baseset()
1559 return subset & baseset([l])
1559 return subset & baseset([l])
1560
1560
1561 @predicate('matching(revision [, field])', safe=True)
1561 @predicate('matching(revision [, field])', safe=True)
1562 def matching(repo, subset, x):
1562 def matching(repo, subset, x):
1563 """Changesets in which a given set of fields match the set of fields in the
1563 """Changesets in which a given set of fields match the set of fields in the
1564 selected revision or set.
1564 selected revision or set.
1565
1565
1566 To match more than one field pass the list of fields to match separated
1566 To match more than one field pass the list of fields to match separated
1567 by spaces (e.g. ``author description``).
1567 by spaces (e.g. ``author description``).
1568
1568
1569 Valid fields are most regular revision fields and some special fields.
1569 Valid fields are most regular revision fields and some special fields.
1570
1570
1571 Regular revision fields are ``description``, ``author``, ``branch``,
1571 Regular revision fields are ``description``, ``author``, ``branch``,
1572 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1572 ``date``, ``files``, ``phase``, ``parents``, ``substate``, ``user``
1573 and ``diff``.
1573 and ``diff``.
1574 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1574 Note that ``author`` and ``user`` are synonyms. ``diff`` refers to the
1575 contents of the revision. Two revisions matching their ``diff`` will
1575 contents of the revision. Two revisions matching their ``diff`` will
1576 also match their ``files``.
1576 also match their ``files``.
1577
1577
1578 Special fields are ``summary`` and ``metadata``:
1578 Special fields are ``summary`` and ``metadata``:
1579 ``summary`` matches the first line of the description.
1579 ``summary`` matches the first line of the description.
1580 ``metadata`` is equivalent to matching ``description user date``
1580 ``metadata`` is equivalent to matching ``description user date``
1581 (i.e. it matches the main metadata fields).
1581 (i.e. it matches the main metadata fields).
1582
1582
1583 ``metadata`` is the default field which is used when no fields are
1583 ``metadata`` is the default field which is used when no fields are
1584 specified. You can match more than one field at a time.
1584 specified. You can match more than one field at a time.
1585 """
1585 """
1586 # i18n: "matching" is a keyword
1586 # i18n: "matching" is a keyword
1587 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1587 l = getargs(x, 1, 2, _("matching takes 1 or 2 arguments"))
1588
1588
1589 revs = getset(repo, fullreposet(repo), l[0])
1589 revs = getset(repo, fullreposet(repo), l[0])
1590
1590
1591 fieldlist = ['metadata']
1591 fieldlist = ['metadata']
1592 if len(l) > 1:
1592 if len(l) > 1:
1593 fieldlist = getstring(l[1],
1593 fieldlist = getstring(l[1],
1594 # i18n: "matching" is a keyword
1594 # i18n: "matching" is a keyword
1595 _("matching requires a string "
1595 _("matching requires a string "
1596 "as its second argument")).split()
1596 "as its second argument")).split()
1597
1597
1598 # Make sure that there are no repeated fields,
1598 # Make sure that there are no repeated fields,
1599 # expand the 'special' 'metadata' field type
1599 # expand the 'special' 'metadata' field type
1600 # and check the 'files' whenever we check the 'diff'
1600 # and check the 'files' whenever we check the 'diff'
1601 fields = []
1601 fields = []
1602 for field in fieldlist:
1602 for field in fieldlist:
1603 if field == 'metadata':
1603 if field == 'metadata':
1604 fields += ['user', 'description', 'date']
1604 fields += ['user', 'description', 'date']
1605 elif field == 'diff':
1605 elif field == 'diff':
1606 # a revision matching the diff must also match the files
1606 # a revision matching the diff must also match the files
1607 # since matching the diff is very costly, make sure to
1607 # since matching the diff is very costly, make sure to
1608 # also match the files first
1608 # also match the files first
1609 fields += ['files', 'diff']
1609 fields += ['files', 'diff']
1610 else:
1610 else:
1611 if field == 'author':
1611 if field == 'author':
1612 field = 'user'
1612 field = 'user'
1613 fields.append(field)
1613 fields.append(field)
1614 fields = set(fields)
1614 fields = set(fields)
1615 if 'summary' in fields and 'description' in fields:
1615 if 'summary' in fields and 'description' in fields:
1616 # If a revision matches its description it also matches its summary
1616 # If a revision matches its description it also matches its summary
1617 fields.discard('summary')
1617 fields.discard('summary')
1618
1618
1619 # We may want to match more than one field
1619 # We may want to match more than one field
1620 # Not all fields take the same amount of time to be matched
1620 # Not all fields take the same amount of time to be matched
1621 # Sort the selected fields in order of increasing matching cost
1621 # Sort the selected fields in order of increasing matching cost
1622 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1622 fieldorder = ['phase', 'parents', 'user', 'date', 'branch', 'summary',
1623 'files', 'description', 'substate', 'diff']
1623 'files', 'description', 'substate', 'diff']
1624 def fieldkeyfunc(f):
1624 def fieldkeyfunc(f):
1625 try:
1625 try:
1626 return fieldorder.index(f)
1626 return fieldorder.index(f)
1627 except ValueError:
1627 except ValueError:
1628 # assume an unknown field is very costly
1628 # assume an unknown field is very costly
1629 return len(fieldorder)
1629 return len(fieldorder)
1630 fields = list(fields)
1630 fields = list(fields)
1631 fields.sort(key=fieldkeyfunc)
1631 fields.sort(key=fieldkeyfunc)
1632
1632
1633 # Each field will be matched with its own "getfield" function
1633 # Each field will be matched with its own "getfield" function
1634 # which will be added to the getfieldfuncs array of functions
1634 # which will be added to the getfieldfuncs array of functions
1635 getfieldfuncs = []
1635 getfieldfuncs = []
1636 _funcs = {
1636 _funcs = {
1637 'user': lambda r: repo[r].user(),
1637 'user': lambda r: repo[r].user(),
1638 'branch': lambda r: repo[r].branch(),
1638 'branch': lambda r: repo[r].branch(),
1639 'date': lambda r: repo[r].date(),
1639 'date': lambda r: repo[r].date(),
1640 'description': lambda r: repo[r].description(),
1640 'description': lambda r: repo[r].description(),
1641 'files': lambda r: repo[r].files(),
1641 'files': lambda r: repo[r].files(),
1642 'parents': lambda r: repo[r].parents(),
1642 'parents': lambda r: repo[r].parents(),
1643 'phase': lambda r: repo[r].phase(),
1643 'phase': lambda r: repo[r].phase(),
1644 'substate': lambda r: repo[r].substate,
1644 'substate': lambda r: repo[r].substate,
1645 'summary': lambda r: repo[r].description().splitlines()[0],
1645 'summary': lambda r: repo[r].description().splitlines()[0],
1646 'diff': lambda r: list(repo[r].diff(git=True),)
1646 'diff': lambda r: list(repo[r].diff(git=True),)
1647 }
1647 }
1648 for info in fields:
1648 for info in fields:
1649 getfield = _funcs.get(info, None)
1649 getfield = _funcs.get(info, None)
1650 if getfield is None:
1650 if getfield is None:
1651 raise error.ParseError(
1651 raise error.ParseError(
1652 # i18n: "matching" is a keyword
1652 # i18n: "matching" is a keyword
1653 _("unexpected field name passed to matching: %s") % info)
1653 _("unexpected field name passed to matching: %s") % info)
1654 getfieldfuncs.append(getfield)
1654 getfieldfuncs.append(getfield)
1655 # convert the getfield array of functions into a "getinfo" function
1655 # convert the getfield array of functions into a "getinfo" function
1656 # which returns an array of field values (or a single value if there
1656 # which returns an array of field values (or a single value if there
1657 # is only one field to match)
1657 # is only one field to match)
1658 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1658 getinfo = lambda r: [f(r) for f in getfieldfuncs]
1659
1659
1660 def matches(x):
1660 def matches(x):
1661 for rev in revs:
1661 for rev in revs:
1662 target = getinfo(rev)
1662 target = getinfo(rev)
1663 match = True
1663 match = True
1664 for n, f in enumerate(getfieldfuncs):
1664 for n, f in enumerate(getfieldfuncs):
1665 if target[n] != f(x):
1665 if target[n] != f(x):
1666 match = False
1666 match = False
1667 if match:
1667 if match:
1668 return True
1668 return True
1669 return False
1669 return False
1670
1670
1671 return subset.filter(matches, condrepr=('<matching%r %r>', fields, revs))
1671 return subset.filter(matches, condrepr=('<matching%r %r>', fields, revs))
1672
1672
1673 @predicate('reverse(set)', safe=True, takeorder=True)
1673 @predicate('reverse(set)', safe=True, takeorder=True)
1674 def reverse(repo, subset, x, order):
1674 def reverse(repo, subset, x, order):
1675 """Reverse order of set.
1675 """Reverse order of set.
1676 """
1676 """
1677 l = getset(repo, subset, x)
1677 l = getset(repo, subset, x)
1678 if order == defineorder:
1678 if order == defineorder:
1679 l.reverse()
1679 l.reverse()
1680 return l
1680 return l
1681
1681
1682 @predicate('roots(set)', safe=True)
1682 @predicate('roots(set)', safe=True)
1683 def roots(repo, subset, x):
1683 def roots(repo, subset, x):
1684 """Changesets in set with no parent changeset in set.
1684 """Changesets in set with no parent changeset in set.
1685 """
1685 """
1686 s = getset(repo, fullreposet(repo), x)
1686 s = getset(repo, fullreposet(repo), x)
1687 parents = repo.changelog.parentrevs
1687 parents = repo.changelog.parentrevs
1688 def filter(r):
1688 def filter(r):
1689 for p in parents(r):
1689 for p in parents(r):
1690 if 0 <= p and p in s:
1690 if 0 <= p and p in s:
1691 return False
1691 return False
1692 return True
1692 return True
1693 return subset & s.filter(filter, condrepr='<roots>')
1693 return subset & s.filter(filter, condrepr='<roots>')
1694
1694
1695 _sortkeyfuncs = {
1695 _sortkeyfuncs = {
1696 'rev': lambda c: c.rev(),
1696 'rev': lambda c: c.rev(),
1697 'branch': lambda c: c.branch(),
1697 'branch': lambda c: c.branch(),
1698 'desc': lambda c: c.description(),
1698 'desc': lambda c: c.description(),
1699 'user': lambda c: c.user(),
1699 'user': lambda c: c.user(),
1700 'author': lambda c: c.user(),
1700 'author': lambda c: c.user(),
1701 'date': lambda c: c.date()[0],
1701 'date': lambda c: c.date()[0],
1702 }
1702 }
1703
1703
1704 def _getsortargs(x):
1704 def _getsortargs(x):
1705 """Parse sort options into (set, [(key, reverse)], opts)"""
1705 """Parse sort options into (set, [(key, reverse)], opts)"""
1706 args = getargsdict(x, 'sort', 'set keys topo.firstbranch')
1706 args = getargsdict(x, 'sort', 'set keys topo.firstbranch')
1707 if 'set' not in args:
1707 if 'set' not in args:
1708 # i18n: "sort" is a keyword
1708 # i18n: "sort" is a keyword
1709 raise error.ParseError(_('sort requires one or two arguments'))
1709 raise error.ParseError(_('sort requires one or two arguments'))
1710 keys = "rev"
1710 keys = "rev"
1711 if 'keys' in args:
1711 if 'keys' in args:
1712 # i18n: "sort" is a keyword
1712 # i18n: "sort" is a keyword
1713 keys = getstring(args['keys'], _("sort spec must be a string"))
1713 keys = getstring(args['keys'], _("sort spec must be a string"))
1714
1714
1715 keyflags = []
1715 keyflags = []
1716 for k in keys.split():
1716 for k in keys.split():
1717 fk = k
1717 fk = k
1718 reverse = (k[0] == '-')
1718 reverse = (k[0] == '-')
1719 if reverse:
1719 if reverse:
1720 k = k[1:]
1720 k = k[1:]
1721 if k not in _sortkeyfuncs and k != 'topo':
1721 if k not in _sortkeyfuncs and k != 'topo':
1722 raise error.ParseError(_("unknown sort key %r") % fk)
1722 raise error.ParseError(_("unknown sort key %r") % fk)
1723 keyflags.append((k, reverse))
1723 keyflags.append((k, reverse))
1724
1724
1725 if len(keyflags) > 1 and any(k == 'topo' for k, reverse in keyflags):
1725 if len(keyflags) > 1 and any(k == 'topo' for k, reverse in keyflags):
1726 # i18n: "topo" is a keyword
1726 # i18n: "topo" is a keyword
1727 raise error.ParseError(_('topo sort order cannot be combined '
1727 raise error.ParseError(_('topo sort order cannot be combined '
1728 'with other sort keys'))
1728 'with other sort keys'))
1729
1729
1730 opts = {}
1730 opts = {}
1731 if 'topo.firstbranch' in args:
1731 if 'topo.firstbranch' in args:
1732 if any(k == 'topo' for k, reverse in keyflags):
1732 if any(k == 'topo' for k, reverse in keyflags):
1733 opts['topo.firstbranch'] = args['topo.firstbranch']
1733 opts['topo.firstbranch'] = args['topo.firstbranch']
1734 else:
1734 else:
1735 # i18n: "topo" and "topo.firstbranch" are keywords
1735 # i18n: "topo" and "topo.firstbranch" are keywords
1736 raise error.ParseError(_('topo.firstbranch can only be used '
1736 raise error.ParseError(_('topo.firstbranch can only be used '
1737 'when using the topo sort key'))
1737 'when using the topo sort key'))
1738
1738
1739 return args['set'], keyflags, opts
1739 return args['set'], keyflags, opts
1740
1740
1741 @predicate('sort(set[, [-]key... [, ...]])', safe=True, takeorder=True)
1741 @predicate('sort(set[, [-]key... [, ...]])', safe=True, takeorder=True)
1742 def sort(repo, subset, x, order):
1742 def sort(repo, subset, x, order):
1743 """Sort set by keys. The default sort order is ascending, specify a key
1743 """Sort set by keys. The default sort order is ascending, specify a key
1744 as ``-key`` to sort in descending order.
1744 as ``-key`` to sort in descending order.
1745
1745
1746 The keys can be:
1746 The keys can be:
1747
1747
1748 - ``rev`` for the revision number,
1748 - ``rev`` for the revision number,
1749 - ``branch`` for the branch name,
1749 - ``branch`` for the branch name,
1750 - ``desc`` for the commit message (description),
1750 - ``desc`` for the commit message (description),
1751 - ``user`` for user name (``author`` can be used as an alias),
1751 - ``user`` for user name (``author`` can be used as an alias),
1752 - ``date`` for the commit date
1752 - ``date`` for the commit date
1753 - ``topo`` for a reverse topographical sort
1753 - ``topo`` for a reverse topographical sort
1754
1754
1755 The ``topo`` sort order cannot be combined with other sort keys. This sort
1755 The ``topo`` sort order cannot be combined with other sort keys. This sort
1756 takes one optional argument, ``topo.firstbranch``, which takes a revset that
1756 takes one optional argument, ``topo.firstbranch``, which takes a revset that
1757 specifies what topographical branches to prioritize in the sort.
1757 specifies what topographical branches to prioritize in the sort.
1758
1758
1759 """
1759 """
1760 s, keyflags, opts = _getsortargs(x)
1760 s, keyflags, opts = _getsortargs(x)
1761 revs = getset(repo, subset, s)
1761 revs = getset(repo, subset, s)
1762
1762
1763 if not keyflags or order != defineorder:
1763 if not keyflags or order != defineorder:
1764 return revs
1764 return revs
1765 if len(keyflags) == 1 and keyflags[0][0] == "rev":
1765 if len(keyflags) == 1 and keyflags[0][0] == "rev":
1766 revs.sort(reverse=keyflags[0][1])
1766 revs.sort(reverse=keyflags[0][1])
1767 return revs
1767 return revs
1768 elif keyflags[0][0] == "topo":
1768 elif keyflags[0][0] == "topo":
1769 firstbranch = ()
1769 firstbranch = ()
1770 if 'topo.firstbranch' in opts:
1770 if 'topo.firstbranch' in opts:
1771 firstbranch = getset(repo, subset, opts['topo.firstbranch'])
1771 firstbranch = getset(repo, subset, opts['topo.firstbranch'])
1772 revs = baseset(dagop.toposort(revs, repo.changelog.parentrevs,
1772 revs = baseset(dagop.toposort(revs, repo.changelog.parentrevs,
1773 firstbranch),
1773 firstbranch),
1774 istopo=True)
1774 istopo=True)
1775 if keyflags[0][1]:
1775 if keyflags[0][1]:
1776 revs.reverse()
1776 revs.reverse()
1777 return revs
1777 return revs
1778
1778
1779 # sort() is guaranteed to be stable
1779 # sort() is guaranteed to be stable
1780 ctxs = [repo[r] for r in revs]
1780 ctxs = [repo[r] for r in revs]
1781 for k, reverse in reversed(keyflags):
1781 for k, reverse in reversed(keyflags):
1782 ctxs.sort(key=_sortkeyfuncs[k], reverse=reverse)
1782 ctxs.sort(key=_sortkeyfuncs[k], reverse=reverse)
1783 return baseset([c.rev() for c in ctxs])
1783 return baseset([c.rev() for c in ctxs])
1784
1784
1785 @predicate('subrepo([pattern])')
1785 @predicate('subrepo([pattern])')
1786 def subrepo(repo, subset, x):
1786 def subrepo(repo, subset, x):
1787 """Changesets that add, modify or remove the given subrepo. If no subrepo
1787 """Changesets that add, modify or remove the given subrepo. If no subrepo
1788 pattern is named, any subrepo changes are returned.
1788 pattern is named, any subrepo changes are returned.
1789 """
1789 """
1790 # i18n: "subrepo" is a keyword
1790 # i18n: "subrepo" is a keyword
1791 args = getargs(x, 0, 1, _('subrepo takes at most one argument'))
1791 args = getargs(x, 0, 1, _('subrepo takes at most one argument'))
1792 pat = None
1792 pat = None
1793 if len(args) != 0:
1793 if len(args) != 0:
1794 pat = getstring(args[0], _("subrepo requires a pattern"))
1794 pat = getstring(args[0], _("subrepo requires a pattern"))
1795
1795
1796 m = matchmod.exact(repo.root, repo.root, ['.hgsubstate'])
1796 m = matchmod.exact(repo.root, repo.root, ['.hgsubstate'])
1797
1797
1798 def submatches(names):
1798 def submatches(names):
1799 k, p, m = util.stringmatcher(pat)
1799 k, p, m = util.stringmatcher(pat)
1800 for name in names:
1800 for name in names:
1801 if m(name):
1801 if m(name):
1802 yield name
1802 yield name
1803
1803
1804 def matches(x):
1804 def matches(x):
1805 c = repo[x]
1805 c = repo[x]
1806 s = repo.status(c.p1().node(), c.node(), match=m)
1806 s = repo.status(c.p1().node(), c.node(), match=m)
1807
1807
1808 if pat is None:
1808 if pat is None:
1809 return s.added or s.modified or s.removed
1809 return s.added or s.modified or s.removed
1810
1810
1811 if s.added:
1811 if s.added:
1812 return any(submatches(c.substate.keys()))
1812 return any(submatches(c.substate.keys()))
1813
1813
1814 if s.modified:
1814 if s.modified:
1815 subs = set(c.p1().substate.keys())
1815 subs = set(c.p1().substate.keys())
1816 subs.update(c.substate.keys())
1816 subs.update(c.substate.keys())
1817
1817
1818 for path in submatches(subs):
1818 for path in submatches(subs):
1819 if c.p1().substate.get(path) != c.substate.get(path):
1819 if c.p1().substate.get(path) != c.substate.get(path):
1820 return True
1820 return True
1821
1821
1822 if s.removed:
1822 if s.removed:
1823 return any(submatches(c.p1().substate.keys()))
1823 return any(submatches(c.p1().substate.keys()))
1824
1824
1825 return False
1825 return False
1826
1826
1827 return subset.filter(matches, condrepr=('<subrepo %r>', pat))
1827 return subset.filter(matches, condrepr=('<subrepo %r>', pat))
1828
1828
1829 def _substringmatcher(pattern, casesensitive=True):
1829 def _substringmatcher(pattern, casesensitive=True):
1830 kind, pattern, matcher = util.stringmatcher(pattern,
1830 kind, pattern, matcher = util.stringmatcher(pattern,
1831 casesensitive=casesensitive)
1831 casesensitive=casesensitive)
1832 if kind == 'literal':
1832 if kind == 'literal':
1833 if not casesensitive:
1833 if not casesensitive:
1834 pattern = encoding.lower(pattern)
1834 pattern = encoding.lower(pattern)
1835 matcher = lambda s: pattern in encoding.lower(s)
1835 matcher = lambda s: pattern in encoding.lower(s)
1836 else:
1836 else:
1837 matcher = lambda s: pattern in s
1837 matcher = lambda s: pattern in s
1838 return kind, pattern, matcher
1838 return kind, pattern, matcher
1839
1839
1840 @predicate('tag([name])', safe=True)
1840 @predicate('tag([name])', safe=True)
1841 def tag(repo, subset, x):
1841 def tag(repo, subset, x):
1842 """The specified tag by name, or all tagged revisions if no name is given.
1842 """The specified tag by name, or all tagged revisions if no name is given.
1843
1843
1844 Pattern matching is supported for `name`. See
1844 Pattern matching is supported for `name`. See
1845 :hg:`help revisions.patterns`.
1845 :hg:`help revisions.patterns`.
1846 """
1846 """
1847 # i18n: "tag" is a keyword
1847 # i18n: "tag" is a keyword
1848 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1848 args = getargs(x, 0, 1, _("tag takes one or no arguments"))
1849 cl = repo.changelog
1849 cl = repo.changelog
1850 if args:
1850 if args:
1851 pattern = getstring(args[0],
1851 pattern = getstring(args[0],
1852 # i18n: "tag" is a keyword
1852 # i18n: "tag" is a keyword
1853 _('the argument to tag must be a string'))
1853 _('the argument to tag must be a string'))
1854 kind, pattern, matcher = util.stringmatcher(pattern)
1854 kind, pattern, matcher = util.stringmatcher(pattern)
1855 if kind == 'literal':
1855 if kind == 'literal':
1856 # avoid resolving all tags
1856 # avoid resolving all tags
1857 tn = repo._tagscache.tags.get(pattern, None)
1857 tn = repo._tagscache.tags.get(pattern, None)
1858 if tn is None:
1858 if tn is None:
1859 raise error.RepoLookupError(_("tag '%s' does not exist")
1859 raise error.RepoLookupError(_("tag '%s' does not exist")
1860 % pattern)
1860 % pattern)
1861 s = {repo[tn].rev()}
1861 s = {repo[tn].rev()}
1862 else:
1862 else:
1863 s = {cl.rev(n) for t, n in repo.tagslist() if matcher(t)}
1863 s = {cl.rev(n) for t, n in repo.tagslist() if matcher(t)}
1864 else:
1864 else:
1865 s = {cl.rev(n) for t, n in repo.tagslist() if t != 'tip'}
1865 s = {cl.rev(n) for t, n in repo.tagslist() if t != 'tip'}
1866 return subset & s
1866 return subset & s
1867
1867
1868 @predicate('tagged', safe=True)
1868 @predicate('tagged', safe=True)
1869 def tagged(repo, subset, x):
1869 def tagged(repo, subset, x):
1870 return tag(repo, subset, x)
1870 return tag(repo, subset, x)
1871
1871
1872 @predicate('unstable()', safe=True)
1872 @predicate('unstable()', safe=True)
1873 def unstable(repo, subset, x):
1873 def unstable(repo, subset, x):
1874 """Non-obsolete changesets with obsolete ancestors.
1874 """Non-obsolete changesets with obsolete ancestors.
1875 """
1875 """
1876 # i18n: "unstable" is a keyword
1876 # i18n: "unstable" is a keyword
1877 getargs(x, 0, 0, _("unstable takes no arguments"))
1877 getargs(x, 0, 0, _("unstable takes no arguments"))
1878 unstables = obsmod.getrevs(repo, 'unstable')
1878 unstables = obsmod.getrevs(repo, 'unstable')
1879 return subset & unstables
1879 return subset & unstables
1880
1880
1881
1881
1882 @predicate('user(string)', safe=True)
1882 @predicate('user(string)', safe=True)
1883 def user(repo, subset, x):
1883 def user(repo, subset, x):
1884 """User name contains string. The match is case-insensitive.
1884 """User name contains string. The match is case-insensitive.
1885
1885
1886 Pattern matching is supported for `string`. See
1886 Pattern matching is supported for `string`. See
1887 :hg:`help revisions.patterns`.
1887 :hg:`help revisions.patterns`.
1888 """
1888 """
1889 return author(repo, subset, x)
1889 return author(repo, subset, x)
1890
1890
1891 @predicate('wdir()', safe=True)
1891 @predicate('wdir()', safe=True)
1892 def wdir(repo, subset, x):
1892 def wdir(repo, subset, x):
1893 """Working directory. (EXPERIMENTAL)"""
1893 """Working directory. (EXPERIMENTAL)"""
1894 # i18n: "wdir" is a keyword
1894 # i18n: "wdir" is a keyword
1895 getargs(x, 0, 0, _("wdir takes no arguments"))
1895 getargs(x, 0, 0, _("wdir takes no arguments"))
1896 if node.wdirrev in subset or isinstance(subset, fullreposet):
1896 if node.wdirrev in subset or isinstance(subset, fullreposet):
1897 return baseset([node.wdirrev])
1897 return baseset([node.wdirrev])
1898 return baseset()
1898 return baseset()
1899
1899
1900 def _orderedlist(repo, subset, x):
1900 def _orderedlist(repo, subset, x):
1901 s = getstring(x, "internal error")
1901 s = getstring(x, "internal error")
1902 if not s:
1902 if not s:
1903 return baseset()
1903 return baseset()
1904 # remove duplicates here. it's difficult for caller to deduplicate sets
1904 # remove duplicates here. it's difficult for caller to deduplicate sets
1905 # because different symbols can point to the same rev.
1905 # because different symbols can point to the same rev.
1906 cl = repo.changelog
1906 cl = repo.changelog
1907 ls = []
1907 ls = []
1908 seen = set()
1908 seen = set()
1909 for t in s.split('\0'):
1909 for t in s.split('\0'):
1910 try:
1910 try:
1911 # fast path for integer revision
1911 # fast path for integer revision
1912 r = int(t)
1912 r = int(t)
1913 if str(r) != t or r not in cl:
1913 if str(r) != t or r not in cl:
1914 raise ValueError
1914 raise ValueError
1915 revs = [r]
1915 revs = [r]
1916 except ValueError:
1916 except ValueError:
1917 revs = stringset(repo, subset, t)
1917 revs = stringset(repo, subset, t)
1918
1918
1919 for r in revs:
1919 for r in revs:
1920 if r in seen:
1920 if r in seen:
1921 continue
1921 continue
1922 if (r in subset
1922 if (r in subset
1923 or r == node.nullrev and isinstance(subset, fullreposet)):
1923 or r == node.nullrev and isinstance(subset, fullreposet)):
1924 ls.append(r)
1924 ls.append(r)
1925 seen.add(r)
1925 seen.add(r)
1926 return baseset(ls)
1926 return baseset(ls)
1927
1927
1928 # for internal use
1928 # for internal use
1929 @predicate('_list', safe=True, takeorder=True)
1929 @predicate('_list', safe=True, takeorder=True)
1930 def _list(repo, subset, x, order):
1930 def _list(repo, subset, x, order):
1931 if order == followorder:
1931 if order == followorder:
1932 # slow path to take the subset order
1932 # slow path to take the subset order
1933 return subset & _orderedlist(repo, fullreposet(repo), x)
1933 return subset & _orderedlist(repo, fullreposet(repo), x)
1934 else:
1934 else:
1935 return _orderedlist(repo, subset, x)
1935 return _orderedlist(repo, subset, x)
1936
1936
1937 def _orderedintlist(repo, subset, x):
1937 def _orderedintlist(repo, subset, x):
1938 s = getstring(x, "internal error")
1938 s = getstring(x, "internal error")
1939 if not s:
1939 if not s:
1940 return baseset()
1940 return baseset()
1941 ls = [int(r) for r in s.split('\0')]
1941 ls = [int(r) for r in s.split('\0')]
1942 s = subset
1942 s = subset
1943 return baseset([r for r in ls if r in s])
1943 return baseset([r for r in ls if r in s])
1944
1944
1945 # for internal use
1945 # for internal use
1946 @predicate('_intlist', safe=True, takeorder=True)
1946 @predicate('_intlist', safe=True, takeorder=True)
1947 def _intlist(repo, subset, x, order):
1947 def _intlist(repo, subset, x, order):
1948 if order == followorder:
1948 if order == followorder:
1949 # slow path to take the subset order
1949 # slow path to take the subset order
1950 return subset & _orderedintlist(repo, fullreposet(repo), x)
1950 return subset & _orderedintlist(repo, fullreposet(repo), x)
1951 else:
1951 else:
1952 return _orderedintlist(repo, subset, x)
1952 return _orderedintlist(repo, subset, x)
1953
1953
1954 def _orderedhexlist(repo, subset, x):
1954 def _orderedhexlist(repo, subset, x):
1955 s = getstring(x, "internal error")
1955 s = getstring(x, "internal error")
1956 if not s:
1956 if not s:
1957 return baseset()
1957 return baseset()
1958 cl = repo.changelog
1958 cl = repo.changelog
1959 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
1959 ls = [cl.rev(node.bin(r)) for r in s.split('\0')]
1960 s = subset
1960 s = subset
1961 return baseset([r for r in ls if r in s])
1961 return baseset([r for r in ls if r in s])
1962
1962
1963 # for internal use
1963 # for internal use
1964 @predicate('_hexlist', safe=True, takeorder=True)
1964 @predicate('_hexlist', safe=True, takeorder=True)
1965 def _hexlist(repo, subset, x, order):
1965 def _hexlist(repo, subset, x, order):
1966 if order == followorder:
1966 if order == followorder:
1967 # slow path to take the subset order
1967 # slow path to take the subset order
1968 return subset & _orderedhexlist(repo, fullreposet(repo), x)
1968 return subset & _orderedhexlist(repo, fullreposet(repo), x)
1969 else:
1969 else:
1970 return _orderedhexlist(repo, subset, x)
1970 return _orderedhexlist(repo, subset, x)
1971
1971
1972 methods = {
1972 methods = {
1973 "range": rangeset,
1973 "range": rangeset,
1974 "rangeall": rangeall,
1974 "rangeall": rangeall,
1975 "rangepre": rangepre,
1975 "rangepre": rangepre,
1976 "rangepost": rangepost,
1976 "rangepost": rangepost,
1977 "dagrange": dagrange,
1977 "dagrange": dagrange,
1978 "string": stringset,
1978 "string": stringset,
1979 "symbol": stringset,
1979 "symbol": stringset,
1980 "and": andset,
1980 "and": andset,
1981 "or": orset,
1981 "or": orset,
1982 "not": notset,
1982 "not": notset,
1983 "difference": differenceset,
1983 "difference": differenceset,
1984 "list": listset,
1984 "list": listset,
1985 "keyvalue": keyvaluepair,
1985 "keyvalue": keyvaluepair,
1986 "func": func,
1986 "func": func,
1987 "ancestor": ancestorspec,
1987 "ancestor": ancestorspec,
1988 "parent": parentspec,
1988 "parent": parentspec,
1989 "parentpost": parentpost,
1989 "parentpost": parentpost,
1990 }
1990 }
1991
1991
1992 def posttreebuilthook(tree, repo):
1992 def posttreebuilthook(tree, repo):
1993 # hook for extensions to execute code on the optimized tree
1993 # hook for extensions to execute code on the optimized tree
1994 pass
1994 pass
1995
1995
1996 def match(ui, spec, repo=None, order=defineorder):
1996 def match(ui, spec, repo=None, order=defineorder):
1997 """Create a matcher for a single revision spec
1997 """Create a matcher for a single revision spec
1998
1998
1999 If order=followorder, a matcher takes the ordering specified by the input
1999 If order=followorder, a matcher takes the ordering specified by the input
2000 set.
2000 set.
2001 """
2001 """
2002 return matchany(ui, [spec], repo=repo, order=order)
2002 return matchany(ui, [spec], repo=repo, order=order)
2003
2003
2004 def matchany(ui, specs, repo=None, order=defineorder):
2004 def matchany(ui, specs, repo=None, order=defineorder, localalias=None):
2005 """Create a matcher that will include any revisions matching one of the
2005 """Create a matcher that will include any revisions matching one of the
2006 given specs
2006 given specs
2007
2007
2008 If order=followorder, a matcher takes the ordering specified by the input
2008 If order=followorder, a matcher takes the ordering specified by the input
2009 set.
2009 set.
2010
2011 If localalias is not None, it is a dict {name: definitionstring}. It takes
2012 precedence over [revsetalias] config section.
2010 """
2013 """
2011 if not specs:
2014 if not specs:
2012 def mfunc(repo, subset=None):
2015 def mfunc(repo, subset=None):
2013 return baseset()
2016 return baseset()
2014 return mfunc
2017 return mfunc
2015 if not all(specs):
2018 if not all(specs):
2016 raise error.ParseError(_("empty query"))
2019 raise error.ParseError(_("empty query"))
2017 lookup = None
2020 lookup = None
2018 if repo:
2021 if repo:
2019 lookup = repo.__contains__
2022 lookup = repo.__contains__
2020 if len(specs) == 1:
2023 if len(specs) == 1:
2021 tree = revsetlang.parse(specs[0], lookup)
2024 tree = revsetlang.parse(specs[0], lookup)
2022 else:
2025 else:
2023 tree = ('or',
2026 tree = ('or',
2024 ('list',) + tuple(revsetlang.parse(s, lookup) for s in specs))
2027 ('list',) + tuple(revsetlang.parse(s, lookup) for s in specs))
2025
2028
2029 aliases = []
2030 warn = None
2026 if ui:
2031 if ui:
2027 tree = revsetlang.expandaliases(ui, tree)
2032 aliases.extend(ui.configitems('revsetalias'))
2033 warn = ui.warn
2034 if localalias:
2035 aliases.extend(localalias.items())
2036 if aliases:
2037 tree = revsetlang.expandaliases(tree, aliases, warn=warn)
2028 tree = revsetlang.foldconcat(tree)
2038 tree = revsetlang.foldconcat(tree)
2029 tree = revsetlang.analyze(tree, order)
2039 tree = revsetlang.analyze(tree, order)
2030 tree = revsetlang.optimize(tree)
2040 tree = revsetlang.optimize(tree)
2031 posttreebuilthook(tree, repo)
2041 posttreebuilthook(tree, repo)
2032 return makematcher(tree)
2042 return makematcher(tree)
2033
2043
2034 def makematcher(tree):
2044 def makematcher(tree):
2035 """Create a matcher from an evaluatable tree"""
2045 """Create a matcher from an evaluatable tree"""
2036 def mfunc(repo, subset=None):
2046 def mfunc(repo, subset=None):
2037 if subset is None:
2047 if subset is None:
2038 subset = fullreposet(repo)
2048 subset = fullreposet(repo)
2039 return getset(repo, subset, tree)
2049 return getset(repo, subset, tree)
2040 return mfunc
2050 return mfunc
2041
2051
2042 def loadpredicate(ui, extname, registrarobj):
2052 def loadpredicate(ui, extname, registrarobj):
2043 """Load revset predicates from specified registrarobj
2053 """Load revset predicates from specified registrarobj
2044 """
2054 """
2045 for name, func in registrarobj._table.iteritems():
2055 for name, func in registrarobj._table.iteritems():
2046 symbols[name] = func
2056 symbols[name] = func
2047 if func._safe:
2057 if func._safe:
2048 safesymbols.add(name)
2058 safesymbols.add(name)
2049
2059
2050 # load built-in predicates explicitly to setup safesymbols
2060 # load built-in predicates explicitly to setup safesymbols
2051 loadpredicate(None, None, predicate)
2061 loadpredicate(None, None, predicate)
2052
2062
2053 # tell hggettext to extract docstrings from these functions:
2063 # tell hggettext to extract docstrings from these functions:
2054 i18nfunctions = symbols.values()
2064 i18nfunctions = symbols.values()
@@ -1,723 +1,725 b''
1 # revsetlang.py - parser, tokenizer and utility for revision set language
1 # revsetlang.py - parser, tokenizer and utility for revision set language
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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import string
10 import string
11
11
12 from .i18n import _
12 from .i18n import _
13 from . import (
13 from . import (
14 error,
14 error,
15 node,
15 node,
16 parser,
16 parser,
17 pycompat,
17 pycompat,
18 util,
18 util,
19 )
19 )
20
20
21 elements = {
21 elements = {
22 # token-type: binding-strength, primary, prefix, infix, suffix
22 # token-type: binding-strength, primary, prefix, infix, suffix
23 "(": (21, None, ("group", 1, ")"), ("func", 1, ")"), None),
23 "(": (21, None, ("group", 1, ")"), ("func", 1, ")"), None),
24 "##": (20, None, None, ("_concat", 20), None),
24 "##": (20, None, None, ("_concat", 20), None),
25 "~": (18, None, None, ("ancestor", 18), None),
25 "~": (18, None, None, ("ancestor", 18), None),
26 "^": (18, None, None, ("parent", 18), "parentpost"),
26 "^": (18, None, None, ("parent", 18), "parentpost"),
27 "-": (5, None, ("negate", 19), ("minus", 5), None),
27 "-": (5, None, ("negate", 19), ("minus", 5), None),
28 "::": (17, None, ("dagrangepre", 17), ("dagrange", 17), "dagrangepost"),
28 "::": (17, None, ("dagrangepre", 17), ("dagrange", 17), "dagrangepost"),
29 "..": (17, None, ("dagrangepre", 17), ("dagrange", 17), "dagrangepost"),
29 "..": (17, None, ("dagrangepre", 17), ("dagrange", 17), "dagrangepost"),
30 ":": (15, "rangeall", ("rangepre", 15), ("range", 15), "rangepost"),
30 ":": (15, "rangeall", ("rangepre", 15), ("range", 15), "rangepost"),
31 "not": (10, None, ("not", 10), None, None),
31 "not": (10, None, ("not", 10), None, None),
32 "!": (10, None, ("not", 10), None, None),
32 "!": (10, None, ("not", 10), None, None),
33 "and": (5, None, None, ("and", 5), None),
33 "and": (5, None, None, ("and", 5), None),
34 "&": (5, None, None, ("and", 5), None),
34 "&": (5, None, None, ("and", 5), None),
35 "%": (5, None, None, ("only", 5), "onlypost"),
35 "%": (5, None, None, ("only", 5), "onlypost"),
36 "or": (4, None, None, ("or", 4), None),
36 "or": (4, None, None, ("or", 4), None),
37 "|": (4, None, None, ("or", 4), None),
37 "|": (4, None, None, ("or", 4), None),
38 "+": (4, None, None, ("or", 4), None),
38 "+": (4, None, None, ("or", 4), None),
39 "=": (3, None, None, ("keyvalue", 3), None),
39 "=": (3, None, None, ("keyvalue", 3), None),
40 ",": (2, None, None, ("list", 2), None),
40 ",": (2, None, None, ("list", 2), None),
41 ")": (0, None, None, None, None),
41 ")": (0, None, None, None, None),
42 "symbol": (0, "symbol", None, None, None),
42 "symbol": (0, "symbol", None, None, None),
43 "string": (0, "string", None, None, None),
43 "string": (0, "string", None, None, None),
44 "end": (0, None, None, None, None),
44 "end": (0, None, None, None, None),
45 }
45 }
46
46
47 keywords = {'and', 'or', 'not'}
47 keywords = {'and', 'or', 'not'}
48
48
49 _quoteletters = {'"', "'"}
49 _quoteletters = {'"', "'"}
50 _simpleopletters = set(pycompat.iterbytestr("():=,-|&+!~^%"))
50 _simpleopletters = set(pycompat.iterbytestr("():=,-|&+!~^%"))
51
51
52 # default set of valid characters for the initial letter of symbols
52 # default set of valid characters for the initial letter of symbols
53 _syminitletters = set(pycompat.iterbytestr(
53 _syminitletters = set(pycompat.iterbytestr(
54 string.ascii_letters.encode('ascii') +
54 string.ascii_letters.encode('ascii') +
55 string.digits.encode('ascii') +
55 string.digits.encode('ascii') +
56 '._@')) | set(map(pycompat.bytechr, xrange(128, 256)))
56 '._@')) | set(map(pycompat.bytechr, xrange(128, 256)))
57
57
58 # default set of valid characters for non-initial letters of symbols
58 # default set of valid characters for non-initial letters of symbols
59 _symletters = _syminitletters | set(pycompat.iterbytestr('-/'))
59 _symletters = _syminitletters | set(pycompat.iterbytestr('-/'))
60
60
61 def tokenize(program, lookup=None, syminitletters=None, symletters=None):
61 def tokenize(program, lookup=None, syminitletters=None, symletters=None):
62 '''
62 '''
63 Parse a revset statement into a stream of tokens
63 Parse a revset statement into a stream of tokens
64
64
65 ``syminitletters`` is the set of valid characters for the initial
65 ``syminitletters`` is the set of valid characters for the initial
66 letter of symbols.
66 letter of symbols.
67
67
68 By default, character ``c`` is recognized as valid for initial
68 By default, character ``c`` is recognized as valid for initial
69 letter of symbols, if ``c.isalnum() or c in '._@' or ord(c) > 127``.
69 letter of symbols, if ``c.isalnum() or c in '._@' or ord(c) > 127``.
70
70
71 ``symletters`` is the set of valid characters for non-initial
71 ``symletters`` is the set of valid characters for non-initial
72 letters of symbols.
72 letters of symbols.
73
73
74 By default, character ``c`` is recognized as valid for non-initial
74 By default, character ``c`` is recognized as valid for non-initial
75 letters of symbols, if ``c.isalnum() or c in '-._/@' or ord(c) > 127``.
75 letters of symbols, if ``c.isalnum() or c in '-._/@' or ord(c) > 127``.
76
76
77 Check that @ is a valid unquoted token character (issue3686):
77 Check that @ is a valid unquoted token character (issue3686):
78 >>> list(tokenize("@::"))
78 >>> list(tokenize("@::"))
79 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
79 [('symbol', '@', 0), ('::', None, 1), ('end', None, 3)]
80
80
81 '''
81 '''
82 program = pycompat.bytestr(program)
82 program = pycompat.bytestr(program)
83 if syminitletters is None:
83 if syminitletters is None:
84 syminitletters = _syminitletters
84 syminitletters = _syminitletters
85 if symletters is None:
85 if symletters is None:
86 symletters = _symletters
86 symletters = _symletters
87
87
88 if program and lookup:
88 if program and lookup:
89 # attempt to parse old-style ranges first to deal with
89 # attempt to parse old-style ranges first to deal with
90 # things like old-tag which contain query metacharacters
90 # things like old-tag which contain query metacharacters
91 parts = program.split(':', 1)
91 parts = program.split(':', 1)
92 if all(lookup(sym) for sym in parts if sym):
92 if all(lookup(sym) for sym in parts if sym):
93 if parts[0]:
93 if parts[0]:
94 yield ('symbol', parts[0], 0)
94 yield ('symbol', parts[0], 0)
95 if len(parts) > 1:
95 if len(parts) > 1:
96 s = len(parts[0])
96 s = len(parts[0])
97 yield (':', None, s)
97 yield (':', None, s)
98 if parts[1]:
98 if parts[1]:
99 yield ('symbol', parts[1], s + 1)
99 yield ('symbol', parts[1], s + 1)
100 yield ('end', None, len(program))
100 yield ('end', None, len(program))
101 return
101 return
102
102
103 pos, l = 0, len(program)
103 pos, l = 0, len(program)
104 while pos < l:
104 while pos < l:
105 c = program[pos]
105 c = program[pos]
106 if c.isspace(): # skip inter-token whitespace
106 if c.isspace(): # skip inter-token whitespace
107 pass
107 pass
108 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
108 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
109 yield ('::', None, pos)
109 yield ('::', None, pos)
110 pos += 1 # skip ahead
110 pos += 1 # skip ahead
111 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
111 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
112 yield ('..', None, pos)
112 yield ('..', None, pos)
113 pos += 1 # skip ahead
113 pos += 1 # skip ahead
114 elif c == '#' and program[pos:pos + 2] == '##': # look ahead carefully
114 elif c == '#' and program[pos:pos + 2] == '##': # look ahead carefully
115 yield ('##', None, pos)
115 yield ('##', None, pos)
116 pos += 1 # skip ahead
116 pos += 1 # skip ahead
117 elif c in _simpleopletters: # handle simple operators
117 elif c in _simpleopletters: # handle simple operators
118 yield (c, None, pos)
118 yield (c, None, pos)
119 elif (c in _quoteletters or c == 'r' and
119 elif (c in _quoteletters or c == 'r' and
120 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
120 program[pos:pos + 2] in ("r'", 'r"')): # handle quoted strings
121 if c == 'r':
121 if c == 'r':
122 pos += 1
122 pos += 1
123 c = program[pos]
123 c = program[pos]
124 decode = lambda x: x
124 decode = lambda x: x
125 else:
125 else:
126 decode = parser.unescapestr
126 decode = parser.unescapestr
127 pos += 1
127 pos += 1
128 s = pos
128 s = pos
129 while pos < l: # find closing quote
129 while pos < l: # find closing quote
130 d = program[pos]
130 d = program[pos]
131 if d == '\\': # skip over escaped characters
131 if d == '\\': # skip over escaped characters
132 pos += 2
132 pos += 2
133 continue
133 continue
134 if d == c:
134 if d == c:
135 yield ('string', decode(program[s:pos]), s)
135 yield ('string', decode(program[s:pos]), s)
136 break
136 break
137 pos += 1
137 pos += 1
138 else:
138 else:
139 raise error.ParseError(_("unterminated string"), s)
139 raise error.ParseError(_("unterminated string"), s)
140 # gather up a symbol/keyword
140 # gather up a symbol/keyword
141 elif c in syminitletters:
141 elif c in syminitletters:
142 s = pos
142 s = pos
143 pos += 1
143 pos += 1
144 while pos < l: # find end of symbol
144 while pos < l: # find end of symbol
145 d = program[pos]
145 d = program[pos]
146 if d not in symletters:
146 if d not in symletters:
147 break
147 break
148 if d == '.' and program[pos - 1] == '.': # special case for ..
148 if d == '.' and program[pos - 1] == '.': # special case for ..
149 pos -= 1
149 pos -= 1
150 break
150 break
151 pos += 1
151 pos += 1
152 sym = program[s:pos]
152 sym = program[s:pos]
153 if sym in keywords: # operator keywords
153 if sym in keywords: # operator keywords
154 yield (sym, None, s)
154 yield (sym, None, s)
155 elif '-' in sym:
155 elif '-' in sym:
156 # some jerk gave us foo-bar-baz, try to check if it's a symbol
156 # some jerk gave us foo-bar-baz, try to check if it's a symbol
157 if lookup and lookup(sym):
157 if lookup and lookup(sym):
158 # looks like a real symbol
158 # looks like a real symbol
159 yield ('symbol', sym, s)
159 yield ('symbol', sym, s)
160 else:
160 else:
161 # looks like an expression
161 # looks like an expression
162 parts = sym.split('-')
162 parts = sym.split('-')
163 for p in parts[:-1]:
163 for p in parts[:-1]:
164 if p: # possible consecutive -
164 if p: # possible consecutive -
165 yield ('symbol', p, s)
165 yield ('symbol', p, s)
166 s += len(p)
166 s += len(p)
167 yield ('-', None, pos)
167 yield ('-', None, pos)
168 s += 1
168 s += 1
169 if parts[-1]: # possible trailing -
169 if parts[-1]: # possible trailing -
170 yield ('symbol', parts[-1], s)
170 yield ('symbol', parts[-1], s)
171 else:
171 else:
172 yield ('symbol', sym, s)
172 yield ('symbol', sym, s)
173 pos -= 1
173 pos -= 1
174 else:
174 else:
175 raise error.ParseError(_("syntax error in revset '%s'") %
175 raise error.ParseError(_("syntax error in revset '%s'") %
176 program, pos)
176 program, pos)
177 pos += 1
177 pos += 1
178 yield ('end', None, pos)
178 yield ('end', None, pos)
179
179
180 # helpers
180 # helpers
181
181
182 _notset = object()
182 _notset = object()
183
183
184 def getsymbol(x):
184 def getsymbol(x):
185 if x and x[0] == 'symbol':
185 if x and x[0] == 'symbol':
186 return x[1]
186 return x[1]
187 raise error.ParseError(_('not a symbol'))
187 raise error.ParseError(_('not a symbol'))
188
188
189 def getstring(x, err):
189 def getstring(x, err):
190 if x and (x[0] == 'string' or x[0] == 'symbol'):
190 if x and (x[0] == 'string' or x[0] == 'symbol'):
191 return x[1]
191 return x[1]
192 raise error.ParseError(err)
192 raise error.ParseError(err)
193
193
194 def getinteger(x, err, default=_notset):
194 def getinteger(x, err, default=_notset):
195 if not x and default is not _notset:
195 if not x and default is not _notset:
196 return default
196 return default
197 try:
197 try:
198 return int(getstring(x, err))
198 return int(getstring(x, err))
199 except ValueError:
199 except ValueError:
200 raise error.ParseError(err)
200 raise error.ParseError(err)
201
201
202 def getboolean(x, err):
202 def getboolean(x, err):
203 value = util.parsebool(getsymbol(x))
203 value = util.parsebool(getsymbol(x))
204 if value is not None:
204 if value is not None:
205 return value
205 return value
206 raise error.ParseError(err)
206 raise error.ParseError(err)
207
207
208 def getlist(x):
208 def getlist(x):
209 if not x:
209 if not x:
210 return []
210 return []
211 if x[0] == 'list':
211 if x[0] == 'list':
212 return list(x[1:])
212 return list(x[1:])
213 return [x]
213 return [x]
214
214
215 def getrange(x, err):
215 def getrange(x, err):
216 if not x:
216 if not x:
217 raise error.ParseError(err)
217 raise error.ParseError(err)
218 op = x[0]
218 op = x[0]
219 if op == 'range':
219 if op == 'range':
220 return x[1], x[2]
220 return x[1], x[2]
221 elif op == 'rangepre':
221 elif op == 'rangepre':
222 return None, x[1]
222 return None, x[1]
223 elif op == 'rangepost':
223 elif op == 'rangepost':
224 return x[1], None
224 return x[1], None
225 elif op == 'rangeall':
225 elif op == 'rangeall':
226 return None, None
226 return None, None
227 raise error.ParseError(err)
227 raise error.ParseError(err)
228
228
229 def getargs(x, min, max, err):
229 def getargs(x, min, max, err):
230 l = getlist(x)
230 l = getlist(x)
231 if len(l) < min or (max >= 0 and len(l) > max):
231 if len(l) < min or (max >= 0 and len(l) > max):
232 raise error.ParseError(err)
232 raise error.ParseError(err)
233 return l
233 return l
234
234
235 def getargsdict(x, funcname, keys):
235 def getargsdict(x, funcname, keys):
236 return parser.buildargsdict(getlist(x), funcname, parser.splitargspec(keys),
236 return parser.buildargsdict(getlist(x), funcname, parser.splitargspec(keys),
237 keyvaluenode='keyvalue', keynode='symbol')
237 keyvaluenode='keyvalue', keynode='symbol')
238
238
239 def _isnamedfunc(x, funcname):
239 def _isnamedfunc(x, funcname):
240 """Check if given tree matches named function"""
240 """Check if given tree matches named function"""
241 return x and x[0] == 'func' and getsymbol(x[1]) == funcname
241 return x and x[0] == 'func' and getsymbol(x[1]) == funcname
242
242
243 def _isposargs(x, n):
243 def _isposargs(x, n):
244 """Check if given tree is n-length list of positional arguments"""
244 """Check if given tree is n-length list of positional arguments"""
245 l = getlist(x)
245 l = getlist(x)
246 return len(l) == n and all(y and y[0] != 'keyvalue' for y in l)
246 return len(l) == n and all(y and y[0] != 'keyvalue' for y in l)
247
247
248 def _matchnamedfunc(x, funcname):
248 def _matchnamedfunc(x, funcname):
249 """Return args tree if given tree matches named function; otherwise None
249 """Return args tree if given tree matches named function; otherwise None
250
250
251 This can't be used for testing a nullary function since its args tree
251 This can't be used for testing a nullary function since its args tree
252 is also None. Use _isnamedfunc() instead.
252 is also None. Use _isnamedfunc() instead.
253 """
253 """
254 if not _isnamedfunc(x, funcname):
254 if not _isnamedfunc(x, funcname):
255 return
255 return
256 return x[2]
256 return x[2]
257
257
258 # Constants for ordering requirement, used in _analyze():
258 # Constants for ordering requirement, used in _analyze():
259 #
259 #
260 # If 'define', any nested functions and operations can change the ordering of
260 # If 'define', any nested functions and operations can change the ordering of
261 # the entries in the set. If 'follow', any nested functions and operations
261 # the entries in the set. If 'follow', any nested functions and operations
262 # should take the ordering specified by the first operand to the '&' operator.
262 # should take the ordering specified by the first operand to the '&' operator.
263 #
263 #
264 # For instance,
264 # For instance,
265 #
265 #
266 # X & (Y | Z)
266 # X & (Y | Z)
267 # ^ ^^^^^^^
267 # ^ ^^^^^^^
268 # | follow
268 # | follow
269 # define
269 # define
270 #
270 #
271 # will be evaluated as 'or(y(x()), z(x()))', where 'x()' can change the order
271 # will be evaluated as 'or(y(x()), z(x()))', where 'x()' can change the order
272 # of the entries in the set, but 'y()', 'z()' and 'or()' shouldn't.
272 # of the entries in the set, but 'y()', 'z()' and 'or()' shouldn't.
273 #
273 #
274 # 'any' means the order doesn't matter. For instance,
274 # 'any' means the order doesn't matter. For instance,
275 #
275 #
276 # X & !Y
276 # X & !Y
277 # ^
277 # ^
278 # any
278 # any
279 #
279 #
280 # 'y()' can either enforce its ordering requirement or take the ordering
280 # 'y()' can either enforce its ordering requirement or take the ordering
281 # specified by 'x()' because 'not()' doesn't care the order.
281 # specified by 'x()' because 'not()' doesn't care the order.
282 #
282 #
283 # Transition of ordering requirement:
283 # Transition of ordering requirement:
284 #
284 #
285 # 1. starts with 'define'
285 # 1. starts with 'define'
286 # 2. shifts to 'follow' by 'x & y'
286 # 2. shifts to 'follow' by 'x & y'
287 # 3. changes back to 'define' on function call 'f(x)' or function-like
287 # 3. changes back to 'define' on function call 'f(x)' or function-like
288 # operation 'x (f) y' because 'f' may have its own ordering requirement
288 # operation 'x (f) y' because 'f' may have its own ordering requirement
289 # for 'x' and 'y' (e.g. 'first(x)')
289 # for 'x' and 'y' (e.g. 'first(x)')
290 #
290 #
291 anyorder = 'any' # don't care the order
291 anyorder = 'any' # don't care the order
292 defineorder = 'define' # should define the order
292 defineorder = 'define' # should define the order
293 followorder = 'follow' # must follow the current order
293 followorder = 'follow' # must follow the current order
294
294
295 # transition table for 'x & y', from the current expression 'x' to 'y'
295 # transition table for 'x & y', from the current expression 'x' to 'y'
296 _tofolloworder = {
296 _tofolloworder = {
297 anyorder: anyorder,
297 anyorder: anyorder,
298 defineorder: followorder,
298 defineorder: followorder,
299 followorder: followorder,
299 followorder: followorder,
300 }
300 }
301
301
302 def _matchonly(revs, bases):
302 def _matchonly(revs, bases):
303 """
303 """
304 >>> f = lambda *args: _matchonly(*map(parse, args))
304 >>> f = lambda *args: _matchonly(*map(parse, args))
305 >>> f('ancestors(A)', 'not ancestors(B)')
305 >>> f('ancestors(A)', 'not ancestors(B)')
306 ('list', ('symbol', 'A'), ('symbol', 'B'))
306 ('list', ('symbol', 'A'), ('symbol', 'B'))
307 """
307 """
308 ta = _matchnamedfunc(revs, 'ancestors')
308 ta = _matchnamedfunc(revs, 'ancestors')
309 tb = bases and bases[0] == 'not' and _matchnamedfunc(bases[1], 'ancestors')
309 tb = bases and bases[0] == 'not' and _matchnamedfunc(bases[1], 'ancestors')
310 if _isposargs(ta, 1) and _isposargs(tb, 1):
310 if _isposargs(ta, 1) and _isposargs(tb, 1):
311 return ('list', ta, tb)
311 return ('list', ta, tb)
312
312
313 def _fixops(x):
313 def _fixops(x):
314 """Rewrite raw parsed tree to resolve ambiguous syntax which cannot be
314 """Rewrite raw parsed tree to resolve ambiguous syntax which cannot be
315 handled well by our simple top-down parser"""
315 handled well by our simple top-down parser"""
316 if not isinstance(x, tuple):
316 if not isinstance(x, tuple):
317 return x
317 return x
318
318
319 op = x[0]
319 op = x[0]
320 if op == 'parent':
320 if op == 'parent':
321 # x^:y means (x^) : y, not x ^ (:y)
321 # x^:y means (x^) : y, not x ^ (:y)
322 # x^: means (x^) :, not x ^ (:)
322 # x^: means (x^) :, not x ^ (:)
323 post = ('parentpost', x[1])
323 post = ('parentpost', x[1])
324 if x[2][0] == 'dagrangepre':
324 if x[2][0] == 'dagrangepre':
325 return _fixops(('dagrange', post, x[2][1]))
325 return _fixops(('dagrange', post, x[2][1]))
326 elif x[2][0] == 'rangepre':
326 elif x[2][0] == 'rangepre':
327 return _fixops(('range', post, x[2][1]))
327 return _fixops(('range', post, x[2][1]))
328 elif x[2][0] == 'rangeall':
328 elif x[2][0] == 'rangeall':
329 return _fixops(('rangepost', post))
329 return _fixops(('rangepost', post))
330 elif op == 'or':
330 elif op == 'or':
331 # make number of arguments deterministic:
331 # make number of arguments deterministic:
332 # x + y + z -> (or x y z) -> (or (list x y z))
332 # x + y + z -> (or x y z) -> (or (list x y z))
333 return (op, _fixops(('list',) + x[1:]))
333 return (op, _fixops(('list',) + x[1:]))
334
334
335 return (op,) + tuple(_fixops(y) for y in x[1:])
335 return (op,) + tuple(_fixops(y) for y in x[1:])
336
336
337 def _analyze(x, order):
337 def _analyze(x, order):
338 if x is None:
338 if x is None:
339 return x
339 return x
340
340
341 op = x[0]
341 op = x[0]
342 if op == 'minus':
342 if op == 'minus':
343 return _analyze(('and', x[1], ('not', x[2])), order)
343 return _analyze(('and', x[1], ('not', x[2])), order)
344 elif op == 'only':
344 elif op == 'only':
345 t = ('func', ('symbol', 'only'), ('list', x[1], x[2]))
345 t = ('func', ('symbol', 'only'), ('list', x[1], x[2]))
346 return _analyze(t, order)
346 return _analyze(t, order)
347 elif op == 'onlypost':
347 elif op == 'onlypost':
348 return _analyze(('func', ('symbol', 'only'), x[1]), order)
348 return _analyze(('func', ('symbol', 'only'), x[1]), order)
349 elif op == 'dagrangepre':
349 elif op == 'dagrangepre':
350 return _analyze(('func', ('symbol', 'ancestors'), x[1]), order)
350 return _analyze(('func', ('symbol', 'ancestors'), x[1]), order)
351 elif op == 'dagrangepost':
351 elif op == 'dagrangepost':
352 return _analyze(('func', ('symbol', 'descendants'), x[1]), order)
352 return _analyze(('func', ('symbol', 'descendants'), x[1]), order)
353 elif op == 'negate':
353 elif op == 'negate':
354 s = getstring(x[1], _("can't negate that"))
354 s = getstring(x[1], _("can't negate that"))
355 return _analyze(('string', '-' + s), order)
355 return _analyze(('string', '-' + s), order)
356 elif op in ('string', 'symbol'):
356 elif op in ('string', 'symbol'):
357 return x
357 return x
358 elif op == 'and':
358 elif op == 'and':
359 ta = _analyze(x[1], order)
359 ta = _analyze(x[1], order)
360 tb = _analyze(x[2], _tofolloworder[order])
360 tb = _analyze(x[2], _tofolloworder[order])
361 return (op, ta, tb, order)
361 return (op, ta, tb, order)
362 elif op == 'or':
362 elif op == 'or':
363 return (op, _analyze(x[1], order), order)
363 return (op, _analyze(x[1], order), order)
364 elif op == 'not':
364 elif op == 'not':
365 return (op, _analyze(x[1], anyorder), order)
365 return (op, _analyze(x[1], anyorder), order)
366 elif op == 'rangeall':
366 elif op == 'rangeall':
367 return (op, None, order)
367 return (op, None, order)
368 elif op in ('rangepre', 'rangepost', 'parentpost'):
368 elif op in ('rangepre', 'rangepost', 'parentpost'):
369 return (op, _analyze(x[1], defineorder), order)
369 return (op, _analyze(x[1], defineorder), order)
370 elif op == 'group':
370 elif op == 'group':
371 return _analyze(x[1], order)
371 return _analyze(x[1], order)
372 elif op in ('dagrange', 'range', 'parent', 'ancestor'):
372 elif op in ('dagrange', 'range', 'parent', 'ancestor'):
373 ta = _analyze(x[1], defineorder)
373 ta = _analyze(x[1], defineorder)
374 tb = _analyze(x[2], defineorder)
374 tb = _analyze(x[2], defineorder)
375 return (op, ta, tb, order)
375 return (op, ta, tb, order)
376 elif op == 'list':
376 elif op == 'list':
377 return (op,) + tuple(_analyze(y, order) for y in x[1:])
377 return (op,) + tuple(_analyze(y, order) for y in x[1:])
378 elif op == 'keyvalue':
378 elif op == 'keyvalue':
379 return (op, x[1], _analyze(x[2], order))
379 return (op, x[1], _analyze(x[2], order))
380 elif op == 'func':
380 elif op == 'func':
381 f = getsymbol(x[1])
381 f = getsymbol(x[1])
382 d = defineorder
382 d = defineorder
383 if f == 'present':
383 if f == 'present':
384 # 'present(set)' is known to return the argument set with no
384 # 'present(set)' is known to return the argument set with no
385 # modification, so forward the current order to its argument
385 # modification, so forward the current order to its argument
386 d = order
386 d = order
387 return (op, x[1], _analyze(x[2], d), order)
387 return (op, x[1], _analyze(x[2], d), order)
388 raise ValueError('invalid operator %r' % op)
388 raise ValueError('invalid operator %r' % op)
389
389
390 def analyze(x, order=defineorder):
390 def analyze(x, order=defineorder):
391 """Transform raw parsed tree to evaluatable tree which can be fed to
391 """Transform raw parsed tree to evaluatable tree which can be fed to
392 optimize() or getset()
392 optimize() or getset()
393
393
394 All pseudo operations should be mapped to real operations or functions
394 All pseudo operations should be mapped to real operations or functions
395 defined in methods or symbols table respectively.
395 defined in methods or symbols table respectively.
396
396
397 'order' specifies how the current expression 'x' is ordered (see the
397 'order' specifies how the current expression 'x' is ordered (see the
398 constants defined above.)
398 constants defined above.)
399 """
399 """
400 return _analyze(x, order)
400 return _analyze(x, order)
401
401
402 def _optimize(x, small):
402 def _optimize(x, small):
403 if x is None:
403 if x is None:
404 return 0, x
404 return 0, x
405
405
406 smallbonus = 1
406 smallbonus = 1
407 if small:
407 if small:
408 smallbonus = .5
408 smallbonus = .5
409
409
410 op = x[0]
410 op = x[0]
411 if op in ('string', 'symbol'):
411 if op in ('string', 'symbol'):
412 return smallbonus, x # single revisions are small
412 return smallbonus, x # single revisions are small
413 elif op == 'and':
413 elif op == 'and':
414 wa, ta = _optimize(x[1], True)
414 wa, ta = _optimize(x[1], True)
415 wb, tb = _optimize(x[2], True)
415 wb, tb = _optimize(x[2], True)
416 order = x[3]
416 order = x[3]
417 w = min(wa, wb)
417 w = min(wa, wb)
418
418
419 # (::x and not ::y)/(not ::y and ::x) have a fast path
419 # (::x and not ::y)/(not ::y and ::x) have a fast path
420 tm = _matchonly(ta, tb) or _matchonly(tb, ta)
420 tm = _matchonly(ta, tb) or _matchonly(tb, ta)
421 if tm:
421 if tm:
422 return w, ('func', ('symbol', 'only'), tm, order)
422 return w, ('func', ('symbol', 'only'), tm, order)
423
423
424 if tb is not None and tb[0] == 'not':
424 if tb is not None and tb[0] == 'not':
425 return wa, ('difference', ta, tb[1], order)
425 return wa, ('difference', ta, tb[1], order)
426
426
427 if wa > wb:
427 if wa > wb:
428 return w, (op, tb, ta, order)
428 return w, (op, tb, ta, order)
429 return w, (op, ta, tb, order)
429 return w, (op, ta, tb, order)
430 elif op == 'or':
430 elif op == 'or':
431 # fast path for machine-generated expression, that is likely to have
431 # fast path for machine-generated expression, that is likely to have
432 # lots of trivial revisions: 'a + b + c()' to '_list(a b) + c()'
432 # lots of trivial revisions: 'a + b + c()' to '_list(a b) + c()'
433 order = x[2]
433 order = x[2]
434 ws, ts, ss = [], [], []
434 ws, ts, ss = [], [], []
435 def flushss():
435 def flushss():
436 if not ss:
436 if not ss:
437 return
437 return
438 if len(ss) == 1:
438 if len(ss) == 1:
439 w, t = ss[0]
439 w, t = ss[0]
440 else:
440 else:
441 s = '\0'.join(t[1] for w, t in ss)
441 s = '\0'.join(t[1] for w, t in ss)
442 y = ('func', ('symbol', '_list'), ('string', s), order)
442 y = ('func', ('symbol', '_list'), ('string', s), order)
443 w, t = _optimize(y, False)
443 w, t = _optimize(y, False)
444 ws.append(w)
444 ws.append(w)
445 ts.append(t)
445 ts.append(t)
446 del ss[:]
446 del ss[:]
447 for y in getlist(x[1]):
447 for y in getlist(x[1]):
448 w, t = _optimize(y, False)
448 w, t = _optimize(y, False)
449 if t is not None and (t[0] == 'string' or t[0] == 'symbol'):
449 if t is not None and (t[0] == 'string' or t[0] == 'symbol'):
450 ss.append((w, t))
450 ss.append((w, t))
451 continue
451 continue
452 flushss()
452 flushss()
453 ws.append(w)
453 ws.append(w)
454 ts.append(t)
454 ts.append(t)
455 flushss()
455 flushss()
456 if len(ts) == 1:
456 if len(ts) == 1:
457 return ws[0], ts[0] # 'or' operation is fully optimized out
457 return ws[0], ts[0] # 'or' operation is fully optimized out
458 if order != defineorder:
458 if order != defineorder:
459 # reorder by weight only when f(a + b) == f(b + a)
459 # reorder by weight only when f(a + b) == f(b + a)
460 ts = [wt[1] for wt in sorted(zip(ws, ts), key=lambda wt: wt[0])]
460 ts = [wt[1] for wt in sorted(zip(ws, ts), key=lambda wt: wt[0])]
461 return max(ws), (op, ('list',) + tuple(ts), order)
461 return max(ws), (op, ('list',) + tuple(ts), order)
462 elif op == 'not':
462 elif op == 'not':
463 # Optimize not public() to _notpublic() because we have a fast version
463 # Optimize not public() to _notpublic() because we have a fast version
464 if x[1][:3] == ('func', ('symbol', 'public'), None):
464 if x[1][:3] == ('func', ('symbol', 'public'), None):
465 order = x[1][3]
465 order = x[1][3]
466 newsym = ('func', ('symbol', '_notpublic'), None, order)
466 newsym = ('func', ('symbol', '_notpublic'), None, order)
467 o = _optimize(newsym, not small)
467 o = _optimize(newsym, not small)
468 return o[0], o[1]
468 return o[0], o[1]
469 else:
469 else:
470 o = _optimize(x[1], not small)
470 o = _optimize(x[1], not small)
471 order = x[2]
471 order = x[2]
472 return o[0], (op, o[1], order)
472 return o[0], (op, o[1], order)
473 elif op == 'rangeall':
473 elif op == 'rangeall':
474 return smallbonus, x
474 return smallbonus, x
475 elif op in ('rangepre', 'rangepost', 'parentpost'):
475 elif op in ('rangepre', 'rangepost', 'parentpost'):
476 o = _optimize(x[1], small)
476 o = _optimize(x[1], small)
477 order = x[2]
477 order = x[2]
478 return o[0], (op, o[1], order)
478 return o[0], (op, o[1], order)
479 elif op in ('dagrange', 'range', 'parent', 'ancestor'):
479 elif op in ('dagrange', 'range', 'parent', 'ancestor'):
480 wa, ta = _optimize(x[1], small)
480 wa, ta = _optimize(x[1], small)
481 wb, tb = _optimize(x[2], small)
481 wb, tb = _optimize(x[2], small)
482 order = x[3]
482 order = x[3]
483 return wa + wb, (op, ta, tb, order)
483 return wa + wb, (op, ta, tb, order)
484 elif op == 'list':
484 elif op == 'list':
485 ws, ts = zip(*(_optimize(y, small) for y in x[1:]))
485 ws, ts = zip(*(_optimize(y, small) for y in x[1:]))
486 return sum(ws), (op,) + ts
486 return sum(ws), (op,) + ts
487 elif op == 'keyvalue':
487 elif op == 'keyvalue':
488 w, t = _optimize(x[2], small)
488 w, t = _optimize(x[2], small)
489 return w, (op, x[1], t)
489 return w, (op, x[1], t)
490 elif op == 'func':
490 elif op == 'func':
491 f = getsymbol(x[1])
491 f = getsymbol(x[1])
492 wa, ta = _optimize(x[2], small)
492 wa, ta = _optimize(x[2], small)
493 if f in ('author', 'branch', 'closed', 'date', 'desc', 'file', 'grep',
493 if f in ('author', 'branch', 'closed', 'date', 'desc', 'file', 'grep',
494 'keyword', 'outgoing', 'user', 'destination'):
494 'keyword', 'outgoing', 'user', 'destination'):
495 w = 10 # slow
495 w = 10 # slow
496 elif f in ('modifies', 'adds', 'removes'):
496 elif f in ('modifies', 'adds', 'removes'):
497 w = 30 # slower
497 w = 30 # slower
498 elif f == "contains":
498 elif f == "contains":
499 w = 100 # very slow
499 w = 100 # very slow
500 elif f == "ancestor":
500 elif f == "ancestor":
501 w = 1 * smallbonus
501 w = 1 * smallbonus
502 elif f in ('reverse', 'limit', 'first', 'wdir', '_intlist'):
502 elif f in ('reverse', 'limit', 'first', 'wdir', '_intlist'):
503 w = 0
503 w = 0
504 elif f == "sort":
504 elif f == "sort":
505 w = 10 # assume most sorts look at changelog
505 w = 10 # assume most sorts look at changelog
506 else:
506 else:
507 w = 1
507 w = 1
508 order = x[3]
508 order = x[3]
509 return w + wa, (op, x[1], ta, order)
509 return w + wa, (op, x[1], ta, order)
510 raise ValueError('invalid operator %r' % op)
510 raise ValueError('invalid operator %r' % op)
511
511
512 def optimize(tree):
512 def optimize(tree):
513 """Optimize evaluatable tree
513 """Optimize evaluatable tree
514
514
515 All pseudo operations should be transformed beforehand.
515 All pseudo operations should be transformed beforehand.
516 """
516 """
517 _weight, newtree = _optimize(tree, small=True)
517 _weight, newtree = _optimize(tree, small=True)
518 return newtree
518 return newtree
519
519
520 # the set of valid characters for the initial letter of symbols in
520 # the set of valid characters for the initial letter of symbols in
521 # alias declarations and definitions
521 # alias declarations and definitions
522 _aliassyminitletters = _syminitletters | set(pycompat.sysstr('$'))
522 _aliassyminitletters = _syminitletters | set(pycompat.sysstr('$'))
523
523
524 def _parsewith(spec, lookup=None, syminitletters=None):
524 def _parsewith(spec, lookup=None, syminitletters=None):
525 """Generate a parse tree of given spec with given tokenizing options
525 """Generate a parse tree of given spec with given tokenizing options
526
526
527 >>> _parsewith('foo($1)', syminitletters=_aliassyminitletters)
527 >>> _parsewith('foo($1)', syminitletters=_aliassyminitletters)
528 ('func', ('symbol', 'foo'), ('symbol', '$1'))
528 ('func', ('symbol', 'foo'), ('symbol', '$1'))
529 >>> _parsewith('$1')
529 >>> _parsewith('$1')
530 Traceback (most recent call last):
530 Traceback (most recent call last):
531 ...
531 ...
532 ParseError: ("syntax error in revset '$1'", 0)
532 ParseError: ("syntax error in revset '$1'", 0)
533 >>> _parsewith('foo bar')
533 >>> _parsewith('foo bar')
534 Traceback (most recent call last):
534 Traceback (most recent call last):
535 ...
535 ...
536 ParseError: ('invalid token', 4)
536 ParseError: ('invalid token', 4)
537 """
537 """
538 p = parser.parser(elements)
538 p = parser.parser(elements)
539 tree, pos = p.parse(tokenize(spec, lookup=lookup,
539 tree, pos = p.parse(tokenize(spec, lookup=lookup,
540 syminitletters=syminitletters))
540 syminitletters=syminitletters))
541 if pos != len(spec):
541 if pos != len(spec):
542 raise error.ParseError(_('invalid token'), pos)
542 raise error.ParseError(_('invalid token'), pos)
543 return _fixops(parser.simplifyinfixops(tree, ('list', 'or')))
543 return _fixops(parser.simplifyinfixops(tree, ('list', 'or')))
544
544
545 class _aliasrules(parser.basealiasrules):
545 class _aliasrules(parser.basealiasrules):
546 """Parsing and expansion rule set of revset aliases"""
546 """Parsing and expansion rule set of revset aliases"""
547 _section = _('revset alias')
547 _section = _('revset alias')
548
548
549 @staticmethod
549 @staticmethod
550 def _parse(spec):
550 def _parse(spec):
551 """Parse alias declaration/definition ``spec``
551 """Parse alias declaration/definition ``spec``
552
552
553 This allows symbol names to use also ``$`` as an initial letter
553 This allows symbol names to use also ``$`` as an initial letter
554 (for backward compatibility), and callers of this function should
554 (for backward compatibility), and callers of this function should
555 examine whether ``$`` is used also for unexpected symbols or not.
555 examine whether ``$`` is used also for unexpected symbols or not.
556 """
556 """
557 return _parsewith(spec, syminitletters=_aliassyminitletters)
557 return _parsewith(spec, syminitletters=_aliassyminitletters)
558
558
559 @staticmethod
559 @staticmethod
560 def _trygetfunc(tree):
560 def _trygetfunc(tree):
561 if tree[0] == 'func' and tree[1][0] == 'symbol':
561 if tree[0] == 'func' and tree[1][0] == 'symbol':
562 return tree[1][1], getlist(tree[2])
562 return tree[1][1], getlist(tree[2])
563
563
564 def expandaliases(ui, tree):
564 def expandaliases(tree, aliases, warn=None):
565 aliases = _aliasrules.buildmap(ui.configitems('revsetalias'))
565 """Expand aliases in a tree, aliases is a list of (name, value) tuples"""
566 aliases = _aliasrules.buildmap(aliases)
566 tree = _aliasrules.expand(aliases, tree)
567 tree = _aliasrules.expand(aliases, tree)
567 # warn about problematic (but not referred) aliases
568 # warn about problematic (but not referred) aliases
569 if warn is not None:
568 for name, alias in sorted(aliases.iteritems()):
570 for name, alias in sorted(aliases.iteritems()):
569 if alias.error and not alias.warned:
571 if alias.error and not alias.warned:
570 ui.warn(_('warning: %s\n') % (alias.error))
572 warn(_('warning: %s\n') % (alias.error))
571 alias.warned = True
573 alias.warned = True
572 return tree
574 return tree
573
575
574 def foldconcat(tree):
576 def foldconcat(tree):
575 """Fold elements to be concatenated by `##`
577 """Fold elements to be concatenated by `##`
576 """
578 """
577 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
579 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
578 return tree
580 return tree
579 if tree[0] == '_concat':
581 if tree[0] == '_concat':
580 pending = [tree]
582 pending = [tree]
581 l = []
583 l = []
582 while pending:
584 while pending:
583 e = pending.pop()
585 e = pending.pop()
584 if e[0] == '_concat':
586 if e[0] == '_concat':
585 pending.extend(reversed(e[1:]))
587 pending.extend(reversed(e[1:]))
586 elif e[0] in ('string', 'symbol'):
588 elif e[0] in ('string', 'symbol'):
587 l.append(e[1])
589 l.append(e[1])
588 else:
590 else:
589 msg = _("\"##\" can't concatenate \"%s\" element") % (e[0])
591 msg = _("\"##\" can't concatenate \"%s\" element") % (e[0])
590 raise error.ParseError(msg)
592 raise error.ParseError(msg)
591 return ('string', ''.join(l))
593 return ('string', ''.join(l))
592 else:
594 else:
593 return tuple(foldconcat(t) for t in tree)
595 return tuple(foldconcat(t) for t in tree)
594
596
595 def parse(spec, lookup=None):
597 def parse(spec, lookup=None):
596 return _parsewith(spec, lookup=lookup)
598 return _parsewith(spec, lookup=lookup)
597
599
598 def _quote(s):
600 def _quote(s):
599 r"""Quote a value in order to make it safe for the revset engine.
601 r"""Quote a value in order to make it safe for the revset engine.
600
602
601 >>> _quote('asdf')
603 >>> _quote('asdf')
602 "'asdf'"
604 "'asdf'"
603 >>> _quote("asdf'\"")
605 >>> _quote("asdf'\"")
604 '\'asdf\\\'"\''
606 '\'asdf\\\'"\''
605 >>> _quote('asdf\'')
607 >>> _quote('asdf\'')
606 "'asdf\\''"
608 "'asdf\\''"
607 >>> _quote(1)
609 >>> _quote(1)
608 "'1'"
610 "'1'"
609 """
611 """
610 return "'%s'" % util.escapestr(pycompat.bytestr(s))
612 return "'%s'" % util.escapestr(pycompat.bytestr(s))
611
613
612 def formatspec(expr, *args):
614 def formatspec(expr, *args):
613 '''
615 '''
614 This is a convenience function for using revsets internally, and
616 This is a convenience function for using revsets internally, and
615 escapes arguments appropriately. Aliases are intentionally ignored
617 escapes arguments appropriately. Aliases are intentionally ignored
616 so that intended expression behavior isn't accidentally subverted.
618 so that intended expression behavior isn't accidentally subverted.
617
619
618 Supported arguments:
620 Supported arguments:
619
621
620 %r = revset expression, parenthesized
622 %r = revset expression, parenthesized
621 %d = int(arg), no quoting
623 %d = int(arg), no quoting
622 %s = string(arg), escaped and single-quoted
624 %s = string(arg), escaped and single-quoted
623 %b = arg.branch(), escaped and single-quoted
625 %b = arg.branch(), escaped and single-quoted
624 %n = hex(arg), single-quoted
626 %n = hex(arg), single-quoted
625 %% = a literal '%'
627 %% = a literal '%'
626
628
627 Prefixing the type with 'l' specifies a parenthesized list of that type.
629 Prefixing the type with 'l' specifies a parenthesized list of that type.
628
630
629 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
631 >>> formatspec('%r:: and %lr', '10 or 11', ("this()", "that()"))
630 '(10 or 11):: and ((this()) or (that()))'
632 '(10 or 11):: and ((this()) or (that()))'
631 >>> formatspec('%d:: and not %d::', 10, 20)
633 >>> formatspec('%d:: and not %d::', 10, 20)
632 '10:: and not 20::'
634 '10:: and not 20::'
633 >>> formatspec('%ld or %ld', [], [1])
635 >>> formatspec('%ld or %ld', [], [1])
634 "_list('') or 1"
636 "_list('') or 1"
635 >>> formatspec('keyword(%s)', 'foo\\xe9')
637 >>> formatspec('keyword(%s)', 'foo\\xe9')
636 "keyword('foo\\\\xe9')"
638 "keyword('foo\\\\xe9')"
637 >>> b = lambda: 'default'
639 >>> b = lambda: 'default'
638 >>> b.branch = b
640 >>> b.branch = b
639 >>> formatspec('branch(%b)', b)
641 >>> formatspec('branch(%b)', b)
640 "branch('default')"
642 "branch('default')"
641 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
643 >>> formatspec('root(%ls)', ['a', 'b', 'c', 'd'])
642 "root(_list('a\\x00b\\x00c\\x00d'))"
644 "root(_list('a\\x00b\\x00c\\x00d'))"
643 '''
645 '''
644
646
645 def argtype(c, arg):
647 def argtype(c, arg):
646 if c == 'd':
648 if c == 'd':
647 return '%d' % int(arg)
649 return '%d' % int(arg)
648 elif c == 's':
650 elif c == 's':
649 return _quote(arg)
651 return _quote(arg)
650 elif c == 'r':
652 elif c == 'r':
651 parse(arg) # make sure syntax errors are confined
653 parse(arg) # make sure syntax errors are confined
652 return '(%s)' % arg
654 return '(%s)' % arg
653 elif c == 'n':
655 elif c == 'n':
654 return _quote(node.hex(arg))
656 return _quote(node.hex(arg))
655 elif c == 'b':
657 elif c == 'b':
656 return _quote(arg.branch())
658 return _quote(arg.branch())
657
659
658 def listexp(s, t):
660 def listexp(s, t):
659 l = len(s)
661 l = len(s)
660 if l == 0:
662 if l == 0:
661 return "_list('')"
663 return "_list('')"
662 elif l == 1:
664 elif l == 1:
663 return argtype(t, s[0])
665 return argtype(t, s[0])
664 elif t == 'd':
666 elif t == 'd':
665 return "_intlist('%s')" % "\0".join('%d' % int(a) for a in s)
667 return "_intlist('%s')" % "\0".join('%d' % int(a) for a in s)
666 elif t == 's':
668 elif t == 's':
667 return "_list('%s')" % "\0".join(s)
669 return "_list('%s')" % "\0".join(s)
668 elif t == 'n':
670 elif t == 'n':
669 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
671 return "_hexlist('%s')" % "\0".join(node.hex(a) for a in s)
670 elif t == 'b':
672 elif t == 'b':
671 return "_list('%s')" % "\0".join(a.branch() for a in s)
673 return "_list('%s')" % "\0".join(a.branch() for a in s)
672
674
673 m = l // 2
675 m = l // 2
674 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
676 return '(%s or %s)' % (listexp(s[:m], t), listexp(s[m:], t))
675
677
676 expr = pycompat.bytestr(expr)
678 expr = pycompat.bytestr(expr)
677 ret = ''
679 ret = ''
678 pos = 0
680 pos = 0
679 arg = 0
681 arg = 0
680 while pos < len(expr):
682 while pos < len(expr):
681 c = expr[pos]
683 c = expr[pos]
682 if c == '%':
684 if c == '%':
683 pos += 1
685 pos += 1
684 d = expr[pos]
686 d = expr[pos]
685 if d == '%':
687 if d == '%':
686 ret += d
688 ret += d
687 elif d in 'dsnbr':
689 elif d in 'dsnbr':
688 ret += argtype(d, args[arg])
690 ret += argtype(d, args[arg])
689 arg += 1
691 arg += 1
690 elif d == 'l':
692 elif d == 'l':
691 # a list of some type
693 # a list of some type
692 pos += 1
694 pos += 1
693 d = expr[pos]
695 d = expr[pos]
694 ret += listexp(list(args[arg]), d)
696 ret += listexp(list(args[arg]), d)
695 arg += 1
697 arg += 1
696 else:
698 else:
697 raise error.Abort(_('unexpected revspec format character %s')
699 raise error.Abort(_('unexpected revspec format character %s')
698 % d)
700 % d)
699 else:
701 else:
700 ret += c
702 ret += c
701 pos += 1
703 pos += 1
702
704
703 return ret
705 return ret
704
706
705 def prettyformat(tree):
707 def prettyformat(tree):
706 return parser.prettyformat(tree, ('string', 'symbol'))
708 return parser.prettyformat(tree, ('string', 'symbol'))
707
709
708 def depth(tree):
710 def depth(tree):
709 if isinstance(tree, tuple):
711 if isinstance(tree, tuple):
710 return max(map(depth, tree)) + 1
712 return max(map(depth, tree)) + 1
711 else:
713 else:
712 return 0
714 return 0
713
715
714 def funcsused(tree):
716 def funcsused(tree):
715 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
717 if not isinstance(tree, tuple) or tree[0] in ('string', 'symbol'):
716 return set()
718 return set()
717 else:
719 else:
718 funcs = set()
720 funcs = set()
719 for s in tree[1:]:
721 for s in tree[1:]:
720 funcs |= funcsused(s)
722 funcs |= funcsused(s)
721 if tree[0] == 'func':
723 if tree[0] == 'func':
722 funcs.add(tree[1][1])
724 funcs.add(tree[1][1])
723 return funcs
725 return funcs
@@ -1,4262 +1,4285 b''
1 $ HGENCODING=utf-8
1 $ HGENCODING=utf-8
2 $ export HGENCODING
2 $ export HGENCODING
3 $ cat > testrevset.py << EOF
3 $ cat > testrevset.py << EOF
4 > import mercurial.revset
4 > import mercurial.revset
5 >
5 >
6 > baseset = mercurial.revset.baseset
6 > baseset = mercurial.revset.baseset
7 >
7 >
8 > def r3232(repo, subset, x):
8 > def r3232(repo, subset, x):
9 > """"simple revset that return [3,2,3,2]
9 > """"simple revset that return [3,2,3,2]
10 >
10 >
11 > revisions duplicated on purpose.
11 > revisions duplicated on purpose.
12 > """
12 > """
13 > if 3 not in subset:
13 > if 3 not in subset:
14 > if 2 in subset:
14 > if 2 in subset:
15 > return baseset([2,2])
15 > return baseset([2,2])
16 > return baseset()
16 > return baseset()
17 > return baseset([3,3,2,2])
17 > return baseset([3,3,2,2])
18 >
18 >
19 > mercurial.revset.symbols['r3232'] = r3232
19 > mercurial.revset.symbols['r3232'] = r3232
20 > EOF
20 > EOF
21 $ cat >> $HGRCPATH << EOF
21 $ cat >> $HGRCPATH << EOF
22 > [extensions]
22 > [extensions]
23 > testrevset=$TESTTMP/testrevset.py
23 > testrevset=$TESTTMP/testrevset.py
24 > EOF
24 > EOF
25
25
26 $ try() {
26 $ try() {
27 > hg debugrevspec --debug "$@"
27 > hg debugrevspec --debug "$@"
28 > }
28 > }
29
29
30 $ log() {
30 $ log() {
31 > hg log --template '{rev}\n' -r "$1"
31 > hg log --template '{rev}\n' -r "$1"
32 > }
32 > }
33
33
34 extension to build '_intlist()' and '_hexlist()', which is necessary because
34 extension to build '_intlist()' and '_hexlist()', which is necessary because
35 these predicates use '\0' as a separator:
35 these predicates use '\0' as a separator:
36
36
37 $ cat <<EOF > debugrevlistspec.py
37 $ cat <<EOF > debugrevlistspec.py
38 > from __future__ import absolute_import
38 > from __future__ import absolute_import
39 > from mercurial import (
39 > from mercurial import (
40 > node as nodemod,
40 > node as nodemod,
41 > registrar,
41 > registrar,
42 > revset,
42 > revset,
43 > revsetlang,
43 > revsetlang,
44 > smartset,
44 > smartset,
45 > )
45 > )
46 > cmdtable = {}
46 > cmdtable = {}
47 > command = registrar.command(cmdtable)
47 > command = registrar.command(cmdtable)
48 > @command(b'debugrevlistspec',
48 > @command(b'debugrevlistspec',
49 > [('', 'optimize', None, 'print parsed tree after optimizing'),
49 > [('', 'optimize', None, 'print parsed tree after optimizing'),
50 > ('', 'bin', None, 'unhexlify arguments')])
50 > ('', 'bin', None, 'unhexlify arguments')])
51 > def debugrevlistspec(ui, repo, fmt, *args, **opts):
51 > def debugrevlistspec(ui, repo, fmt, *args, **opts):
52 > if opts['bin']:
52 > if opts['bin']:
53 > args = map(nodemod.bin, args)
53 > args = map(nodemod.bin, args)
54 > expr = revsetlang.formatspec(fmt, list(args))
54 > expr = revsetlang.formatspec(fmt, list(args))
55 > if ui.verbose:
55 > if ui.verbose:
56 > tree = revsetlang.parse(expr, lookup=repo.__contains__)
56 > tree = revsetlang.parse(expr, lookup=repo.__contains__)
57 > ui.note(revsetlang.prettyformat(tree), "\n")
57 > ui.note(revsetlang.prettyformat(tree), "\n")
58 > if opts["optimize"]:
58 > if opts["optimize"]:
59 > opttree = revsetlang.optimize(revsetlang.analyze(tree))
59 > opttree = revsetlang.optimize(revsetlang.analyze(tree))
60 > ui.note("* optimized:\n", revsetlang.prettyformat(opttree),
60 > ui.note("* optimized:\n", revsetlang.prettyformat(opttree),
61 > "\n")
61 > "\n")
62 > func = revset.match(ui, expr, repo)
62 > func = revset.match(ui, expr, repo)
63 > revs = func(repo)
63 > revs = func(repo)
64 > if ui.verbose:
64 > if ui.verbose:
65 > ui.note("* set:\n", smartset.prettyformat(revs), "\n")
65 > ui.note("* set:\n", smartset.prettyformat(revs), "\n")
66 > for c in revs:
66 > for c in revs:
67 > ui.write("%s\n" % c)
67 > ui.write("%s\n" % c)
68 > EOF
68 > EOF
69 $ cat <<EOF >> $HGRCPATH
69 $ cat <<EOF >> $HGRCPATH
70 > [extensions]
70 > [extensions]
71 > debugrevlistspec = $TESTTMP/debugrevlistspec.py
71 > debugrevlistspec = $TESTTMP/debugrevlistspec.py
72 > EOF
72 > EOF
73 $ trylist() {
73 $ trylist() {
74 > hg debugrevlistspec --debug "$@"
74 > hg debugrevlistspec --debug "$@"
75 > }
75 > }
76
76
77 $ hg init repo
77 $ hg init repo
78 $ cd repo
78 $ cd repo
79
79
80 $ echo a > a
80 $ echo a > a
81 $ hg branch a
81 $ hg branch a
82 marked working directory as branch a
82 marked working directory as branch a
83 (branches are permanent and global, did you want a bookmark?)
83 (branches are permanent and global, did you want a bookmark?)
84 $ hg ci -Aqm0
84 $ hg ci -Aqm0
85
85
86 $ echo b > b
86 $ echo b > b
87 $ hg branch b
87 $ hg branch b
88 marked working directory as branch b
88 marked working directory as branch b
89 $ hg ci -Aqm1
89 $ hg ci -Aqm1
90
90
91 $ rm a
91 $ rm a
92 $ hg branch a-b-c-
92 $ hg branch a-b-c-
93 marked working directory as branch a-b-c-
93 marked working directory as branch a-b-c-
94 $ hg ci -Aqm2 -u Bob
94 $ hg ci -Aqm2 -u Bob
95
95
96 $ hg log -r "extra('branch', 'a-b-c-')" --template '{rev}\n'
96 $ hg log -r "extra('branch', 'a-b-c-')" --template '{rev}\n'
97 2
97 2
98 $ hg log -r "extra('branch')" --template '{rev}\n'
98 $ hg log -r "extra('branch')" --template '{rev}\n'
99 0
99 0
100 1
100 1
101 2
101 2
102 $ hg log -r "extra('branch', 're:a')" --template '{rev} {branch}\n'
102 $ hg log -r "extra('branch', 're:a')" --template '{rev} {branch}\n'
103 0 a
103 0 a
104 2 a-b-c-
104 2 a-b-c-
105
105
106 $ hg co 1
106 $ hg co 1
107 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
107 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
108 $ hg branch +a+b+c+
108 $ hg branch +a+b+c+
109 marked working directory as branch +a+b+c+
109 marked working directory as branch +a+b+c+
110 $ hg ci -Aqm3
110 $ hg ci -Aqm3
111
111
112 $ hg co 2 # interleave
112 $ hg co 2 # interleave
113 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
113 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
114 $ echo bb > b
114 $ echo bb > b
115 $ hg branch -- -a-b-c-
115 $ hg branch -- -a-b-c-
116 marked working directory as branch -a-b-c-
116 marked working directory as branch -a-b-c-
117 $ hg ci -Aqm4 -d "May 12 2005"
117 $ hg ci -Aqm4 -d "May 12 2005"
118
118
119 $ hg co 3
119 $ hg co 3
120 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
120 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
121 $ hg branch !a/b/c/
121 $ hg branch !a/b/c/
122 marked working directory as branch !a/b/c/
122 marked working directory as branch !a/b/c/
123 $ hg ci -Aqm"5 bug"
123 $ hg ci -Aqm"5 bug"
124
124
125 $ hg merge 4
125 $ hg merge 4
126 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
126 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
127 (branch merge, don't forget to commit)
127 (branch merge, don't forget to commit)
128 $ hg branch _a_b_c_
128 $ hg branch _a_b_c_
129 marked working directory as branch _a_b_c_
129 marked working directory as branch _a_b_c_
130 $ hg ci -Aqm"6 issue619"
130 $ hg ci -Aqm"6 issue619"
131
131
132 $ hg branch .a.b.c.
132 $ hg branch .a.b.c.
133 marked working directory as branch .a.b.c.
133 marked working directory as branch .a.b.c.
134 $ hg ci -Aqm7
134 $ hg ci -Aqm7
135
135
136 $ hg branch all
136 $ hg branch all
137 marked working directory as branch all
137 marked working directory as branch all
138
138
139 $ hg co 4
139 $ hg co 4
140 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
140 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
141 $ hg branch Γ©
141 $ hg branch Γ©
142 marked working directory as branch \xc3\xa9 (esc)
142 marked working directory as branch \xc3\xa9 (esc)
143 $ hg ci -Aqm9
143 $ hg ci -Aqm9
144
144
145 $ hg tag -r6 1.0
145 $ hg tag -r6 1.0
146 $ hg bookmark -r6 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
146 $ hg bookmark -r6 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
147
147
148 $ hg clone --quiet -U -r 7 . ../remote1
148 $ hg clone --quiet -U -r 7 . ../remote1
149 $ hg clone --quiet -U -r 8 . ../remote2
149 $ hg clone --quiet -U -r 8 . ../remote2
150 $ echo "[paths]" >> .hg/hgrc
150 $ echo "[paths]" >> .hg/hgrc
151 $ echo "default = ../remote1" >> .hg/hgrc
151 $ echo "default = ../remote1" >> .hg/hgrc
152
152
153 trivial
153 trivial
154
154
155 $ try 0:1
155 $ try 0:1
156 (range
156 (range
157 ('symbol', '0')
157 ('symbol', '0')
158 ('symbol', '1'))
158 ('symbol', '1'))
159 * set:
159 * set:
160 <spanset+ 0:2>
160 <spanset+ 0:2>
161 0
161 0
162 1
162 1
163 $ try --optimize :
163 $ try --optimize :
164 (rangeall
164 (rangeall
165 None)
165 None)
166 * optimized:
166 * optimized:
167 (rangeall
167 (rangeall
168 None
168 None
169 define)
169 define)
170 * set:
170 * set:
171 <spanset+ 0:10>
171 <spanset+ 0:10>
172 0
172 0
173 1
173 1
174 2
174 2
175 3
175 3
176 4
176 4
177 5
177 5
178 6
178 6
179 7
179 7
180 8
180 8
181 9
181 9
182 $ try 3::6
182 $ try 3::6
183 (dagrange
183 (dagrange
184 ('symbol', '3')
184 ('symbol', '3')
185 ('symbol', '6'))
185 ('symbol', '6'))
186 * set:
186 * set:
187 <baseset+ [3, 5, 6]>
187 <baseset+ [3, 5, 6]>
188 3
188 3
189 5
189 5
190 6
190 6
191 $ try '0|1|2'
191 $ try '0|1|2'
192 (or
192 (or
193 (list
193 (list
194 ('symbol', '0')
194 ('symbol', '0')
195 ('symbol', '1')
195 ('symbol', '1')
196 ('symbol', '2')))
196 ('symbol', '2')))
197 * set:
197 * set:
198 <baseset [0, 1, 2]>
198 <baseset [0, 1, 2]>
199 0
199 0
200 1
200 1
201 2
201 2
202
202
203 names that should work without quoting
203 names that should work without quoting
204
204
205 $ try a
205 $ try a
206 ('symbol', 'a')
206 ('symbol', 'a')
207 * set:
207 * set:
208 <baseset [0]>
208 <baseset [0]>
209 0
209 0
210 $ try b-a
210 $ try b-a
211 (minus
211 (minus
212 ('symbol', 'b')
212 ('symbol', 'b')
213 ('symbol', 'a'))
213 ('symbol', 'a'))
214 * set:
214 * set:
215 <filteredset
215 <filteredset
216 <baseset [1]>,
216 <baseset [1]>,
217 <not
217 <not
218 <baseset [0]>>>
218 <baseset [0]>>>
219 1
219 1
220 $ try _a_b_c_
220 $ try _a_b_c_
221 ('symbol', '_a_b_c_')
221 ('symbol', '_a_b_c_')
222 * set:
222 * set:
223 <baseset [6]>
223 <baseset [6]>
224 6
224 6
225 $ try _a_b_c_-a
225 $ try _a_b_c_-a
226 (minus
226 (minus
227 ('symbol', '_a_b_c_')
227 ('symbol', '_a_b_c_')
228 ('symbol', 'a'))
228 ('symbol', 'a'))
229 * set:
229 * set:
230 <filteredset
230 <filteredset
231 <baseset [6]>,
231 <baseset [6]>,
232 <not
232 <not
233 <baseset [0]>>>
233 <baseset [0]>>>
234 6
234 6
235 $ try .a.b.c.
235 $ try .a.b.c.
236 ('symbol', '.a.b.c.')
236 ('symbol', '.a.b.c.')
237 * set:
237 * set:
238 <baseset [7]>
238 <baseset [7]>
239 7
239 7
240 $ try .a.b.c.-a
240 $ try .a.b.c.-a
241 (minus
241 (minus
242 ('symbol', '.a.b.c.')
242 ('symbol', '.a.b.c.')
243 ('symbol', 'a'))
243 ('symbol', 'a'))
244 * set:
244 * set:
245 <filteredset
245 <filteredset
246 <baseset [7]>,
246 <baseset [7]>,
247 <not
247 <not
248 <baseset [0]>>>
248 <baseset [0]>>>
249 7
249 7
250
250
251 names that should be caught by fallback mechanism
251 names that should be caught by fallback mechanism
252
252
253 $ try -- '-a-b-c-'
253 $ try -- '-a-b-c-'
254 ('symbol', '-a-b-c-')
254 ('symbol', '-a-b-c-')
255 * set:
255 * set:
256 <baseset [4]>
256 <baseset [4]>
257 4
257 4
258 $ log -a-b-c-
258 $ log -a-b-c-
259 4
259 4
260 $ try '+a+b+c+'
260 $ try '+a+b+c+'
261 ('symbol', '+a+b+c+')
261 ('symbol', '+a+b+c+')
262 * set:
262 * set:
263 <baseset [3]>
263 <baseset [3]>
264 3
264 3
265 $ try '+a+b+c+:'
265 $ try '+a+b+c+:'
266 (rangepost
266 (rangepost
267 ('symbol', '+a+b+c+'))
267 ('symbol', '+a+b+c+'))
268 * set:
268 * set:
269 <spanset+ 3:10>
269 <spanset+ 3:10>
270 3
270 3
271 4
271 4
272 5
272 5
273 6
273 6
274 7
274 7
275 8
275 8
276 9
276 9
277 $ try ':+a+b+c+'
277 $ try ':+a+b+c+'
278 (rangepre
278 (rangepre
279 ('symbol', '+a+b+c+'))
279 ('symbol', '+a+b+c+'))
280 * set:
280 * set:
281 <spanset+ 0:4>
281 <spanset+ 0:4>
282 0
282 0
283 1
283 1
284 2
284 2
285 3
285 3
286 $ try -- '-a-b-c-:+a+b+c+'
286 $ try -- '-a-b-c-:+a+b+c+'
287 (range
287 (range
288 ('symbol', '-a-b-c-')
288 ('symbol', '-a-b-c-')
289 ('symbol', '+a+b+c+'))
289 ('symbol', '+a+b+c+'))
290 * set:
290 * set:
291 <spanset- 3:5>
291 <spanset- 3:5>
292 4
292 4
293 3
293 3
294 $ log '-a-b-c-:+a+b+c+'
294 $ log '-a-b-c-:+a+b+c+'
295 4
295 4
296 3
296 3
297
297
298 $ try -- -a-b-c--a # complains
298 $ try -- -a-b-c--a # complains
299 (minus
299 (minus
300 (minus
300 (minus
301 (minus
301 (minus
302 (negate
302 (negate
303 ('symbol', 'a'))
303 ('symbol', 'a'))
304 ('symbol', 'b'))
304 ('symbol', 'b'))
305 ('symbol', 'c'))
305 ('symbol', 'c'))
306 (negate
306 (negate
307 ('symbol', 'a')))
307 ('symbol', 'a')))
308 abort: unknown revision '-a'!
308 abort: unknown revision '-a'!
309 [255]
309 [255]
310 $ try Γ©
310 $ try Γ©
311 ('symbol', '\xc3\xa9')
311 ('symbol', '\xc3\xa9')
312 * set:
312 * set:
313 <baseset [9]>
313 <baseset [9]>
314 9
314 9
315
315
316 no quoting needed
316 no quoting needed
317
317
318 $ log ::a-b-c-
318 $ log ::a-b-c-
319 0
319 0
320 1
320 1
321 2
321 2
322
322
323 quoting needed
323 quoting needed
324
324
325 $ try '"-a-b-c-"-a'
325 $ try '"-a-b-c-"-a'
326 (minus
326 (minus
327 ('string', '-a-b-c-')
327 ('string', '-a-b-c-')
328 ('symbol', 'a'))
328 ('symbol', 'a'))
329 * set:
329 * set:
330 <filteredset
330 <filteredset
331 <baseset [4]>,
331 <baseset [4]>,
332 <not
332 <not
333 <baseset [0]>>>
333 <baseset [0]>>>
334 4
334 4
335
335
336 $ log '1 or 2'
336 $ log '1 or 2'
337 1
337 1
338 2
338 2
339 $ log '1|2'
339 $ log '1|2'
340 1
340 1
341 2
341 2
342 $ log '1 and 2'
342 $ log '1 and 2'
343 $ log '1&2'
343 $ log '1&2'
344 $ try '1&2|3' # precedence - and is higher
344 $ try '1&2|3' # precedence - and is higher
345 (or
345 (or
346 (list
346 (list
347 (and
347 (and
348 ('symbol', '1')
348 ('symbol', '1')
349 ('symbol', '2'))
349 ('symbol', '2'))
350 ('symbol', '3')))
350 ('symbol', '3')))
351 * set:
351 * set:
352 <addset
352 <addset
353 <baseset []>,
353 <baseset []>,
354 <baseset [3]>>
354 <baseset [3]>>
355 3
355 3
356 $ try '1|2&3'
356 $ try '1|2&3'
357 (or
357 (or
358 (list
358 (list
359 ('symbol', '1')
359 ('symbol', '1')
360 (and
360 (and
361 ('symbol', '2')
361 ('symbol', '2')
362 ('symbol', '3'))))
362 ('symbol', '3'))))
363 * set:
363 * set:
364 <addset
364 <addset
365 <baseset [1]>,
365 <baseset [1]>,
366 <baseset []>>
366 <baseset []>>
367 1
367 1
368 $ try '1&2&3' # associativity
368 $ try '1&2&3' # associativity
369 (and
369 (and
370 (and
370 (and
371 ('symbol', '1')
371 ('symbol', '1')
372 ('symbol', '2'))
372 ('symbol', '2'))
373 ('symbol', '3'))
373 ('symbol', '3'))
374 * set:
374 * set:
375 <baseset []>
375 <baseset []>
376 $ try '1|(2|3)'
376 $ try '1|(2|3)'
377 (or
377 (or
378 (list
378 (list
379 ('symbol', '1')
379 ('symbol', '1')
380 (group
380 (group
381 (or
381 (or
382 (list
382 (list
383 ('symbol', '2')
383 ('symbol', '2')
384 ('symbol', '3'))))))
384 ('symbol', '3'))))))
385 * set:
385 * set:
386 <addset
386 <addset
387 <baseset [1]>,
387 <baseset [1]>,
388 <baseset [2, 3]>>
388 <baseset [2, 3]>>
389 1
389 1
390 2
390 2
391 3
391 3
392 $ log '1.0' # tag
392 $ log '1.0' # tag
393 6
393 6
394 $ log 'a' # branch
394 $ log 'a' # branch
395 0
395 0
396 $ log '2785f51ee'
396 $ log '2785f51ee'
397 0
397 0
398 $ log 'date(2005)'
398 $ log 'date(2005)'
399 4
399 4
400 $ log 'date(this is a test)'
400 $ log 'date(this is a test)'
401 hg: parse error at 10: unexpected token: symbol
401 hg: parse error at 10: unexpected token: symbol
402 [255]
402 [255]
403 $ log 'date()'
403 $ log 'date()'
404 hg: parse error: date requires a string
404 hg: parse error: date requires a string
405 [255]
405 [255]
406 $ log 'date'
406 $ log 'date'
407 abort: unknown revision 'date'!
407 abort: unknown revision 'date'!
408 [255]
408 [255]
409 $ log 'date('
409 $ log 'date('
410 hg: parse error at 5: not a prefix: end
410 hg: parse error at 5: not a prefix: end
411 [255]
411 [255]
412 $ log 'date("\xy")'
412 $ log 'date("\xy")'
413 hg: parse error: invalid \x escape
413 hg: parse error: invalid \x escape
414 [255]
414 [255]
415 $ log 'date(tip)'
415 $ log 'date(tip)'
416 hg: parse error: invalid date: 'tip'
416 hg: parse error: invalid date: 'tip'
417 [255]
417 [255]
418 $ log '0:date'
418 $ log '0:date'
419 abort: unknown revision 'date'!
419 abort: unknown revision 'date'!
420 [255]
420 [255]
421 $ log '::"date"'
421 $ log '::"date"'
422 abort: unknown revision 'date'!
422 abort: unknown revision 'date'!
423 [255]
423 [255]
424 $ hg book date -r 4
424 $ hg book date -r 4
425 $ log '0:date'
425 $ log '0:date'
426 0
426 0
427 1
427 1
428 2
428 2
429 3
429 3
430 4
430 4
431 $ log '::date'
431 $ log '::date'
432 0
432 0
433 1
433 1
434 2
434 2
435 4
435 4
436 $ log '::"date"'
436 $ log '::"date"'
437 0
437 0
438 1
438 1
439 2
439 2
440 4
440 4
441 $ log 'date(2005) and 1::'
441 $ log 'date(2005) and 1::'
442 4
442 4
443 $ hg book -d date
443 $ hg book -d date
444
444
445 function name should be a symbol
445 function name should be a symbol
446
446
447 $ log '"date"(2005)'
447 $ log '"date"(2005)'
448 hg: parse error: not a symbol
448 hg: parse error: not a symbol
449 [255]
449 [255]
450
450
451 keyword arguments
451 keyword arguments
452
452
453 $ log 'extra(branch, value=a)'
453 $ log 'extra(branch, value=a)'
454 0
454 0
455
455
456 $ log 'extra(branch, a, b)'
456 $ log 'extra(branch, a, b)'
457 hg: parse error: extra takes at most 2 positional arguments
457 hg: parse error: extra takes at most 2 positional arguments
458 [255]
458 [255]
459 $ log 'extra(a, label=b)'
459 $ log 'extra(a, label=b)'
460 hg: parse error: extra got multiple values for keyword argument 'label'
460 hg: parse error: extra got multiple values for keyword argument 'label'
461 [255]
461 [255]
462 $ log 'extra(label=branch, default)'
462 $ log 'extra(label=branch, default)'
463 hg: parse error: extra got an invalid argument
463 hg: parse error: extra got an invalid argument
464 [255]
464 [255]
465 $ log 'extra(branch, foo+bar=baz)'
465 $ log 'extra(branch, foo+bar=baz)'
466 hg: parse error: extra got an invalid argument
466 hg: parse error: extra got an invalid argument
467 [255]
467 [255]
468 $ log 'extra(unknown=branch)'
468 $ log 'extra(unknown=branch)'
469 hg: parse error: extra got an unexpected keyword argument 'unknown'
469 hg: parse error: extra got an unexpected keyword argument 'unknown'
470 [255]
470 [255]
471
471
472 $ try 'foo=bar|baz'
472 $ try 'foo=bar|baz'
473 (keyvalue
473 (keyvalue
474 ('symbol', 'foo')
474 ('symbol', 'foo')
475 (or
475 (or
476 (list
476 (list
477 ('symbol', 'bar')
477 ('symbol', 'bar')
478 ('symbol', 'baz'))))
478 ('symbol', 'baz'))))
479 hg: parse error: can't use a key-value pair in this context
479 hg: parse error: can't use a key-value pair in this context
480 [255]
480 [255]
481
481
482 right-hand side should be optimized recursively
482 right-hand side should be optimized recursively
483
483
484 $ try --optimize 'foo=(not public())'
484 $ try --optimize 'foo=(not public())'
485 (keyvalue
485 (keyvalue
486 ('symbol', 'foo')
486 ('symbol', 'foo')
487 (group
487 (group
488 (not
488 (not
489 (func
489 (func
490 ('symbol', 'public')
490 ('symbol', 'public')
491 None))))
491 None))))
492 * optimized:
492 * optimized:
493 (keyvalue
493 (keyvalue
494 ('symbol', 'foo')
494 ('symbol', 'foo')
495 (func
495 (func
496 ('symbol', '_notpublic')
496 ('symbol', '_notpublic')
497 None
497 None
498 any))
498 any))
499 hg: parse error: can't use a key-value pair in this context
499 hg: parse error: can't use a key-value pair in this context
500 [255]
500 [255]
501
501
502 parsed tree at stages:
502 parsed tree at stages:
503
503
504 $ hg debugrevspec -p all '()'
504 $ hg debugrevspec -p all '()'
505 * parsed:
505 * parsed:
506 (group
506 (group
507 None)
507 None)
508 * expanded:
508 * expanded:
509 (group
509 (group
510 None)
510 None)
511 * concatenated:
511 * concatenated:
512 (group
512 (group
513 None)
513 None)
514 * analyzed:
514 * analyzed:
515 None
515 None
516 * optimized:
516 * optimized:
517 None
517 None
518 hg: parse error: missing argument
518 hg: parse error: missing argument
519 [255]
519 [255]
520
520
521 $ hg debugrevspec --no-optimized -p all '()'
521 $ hg debugrevspec --no-optimized -p all '()'
522 * parsed:
522 * parsed:
523 (group
523 (group
524 None)
524 None)
525 * expanded:
525 * expanded:
526 (group
526 (group
527 None)
527 None)
528 * concatenated:
528 * concatenated:
529 (group
529 (group
530 None)
530 None)
531 * analyzed:
531 * analyzed:
532 None
532 None
533 hg: parse error: missing argument
533 hg: parse error: missing argument
534 [255]
534 [255]
535
535
536 $ hg debugrevspec -p parsed -p analyzed -p optimized '(0|1)-1'
536 $ hg debugrevspec -p parsed -p analyzed -p optimized '(0|1)-1'
537 * parsed:
537 * parsed:
538 (minus
538 (minus
539 (group
539 (group
540 (or
540 (or
541 (list
541 (list
542 ('symbol', '0')
542 ('symbol', '0')
543 ('symbol', '1'))))
543 ('symbol', '1'))))
544 ('symbol', '1'))
544 ('symbol', '1'))
545 * analyzed:
545 * analyzed:
546 (and
546 (and
547 (or
547 (or
548 (list
548 (list
549 ('symbol', '0')
549 ('symbol', '0')
550 ('symbol', '1'))
550 ('symbol', '1'))
551 define)
551 define)
552 (not
552 (not
553 ('symbol', '1')
553 ('symbol', '1')
554 follow)
554 follow)
555 define)
555 define)
556 * optimized:
556 * optimized:
557 (difference
557 (difference
558 (func
558 (func
559 ('symbol', '_list')
559 ('symbol', '_list')
560 ('string', '0\x001')
560 ('string', '0\x001')
561 define)
561 define)
562 ('symbol', '1')
562 ('symbol', '1')
563 define)
563 define)
564 0
564 0
565
565
566 $ hg debugrevspec -p unknown '0'
566 $ hg debugrevspec -p unknown '0'
567 abort: invalid stage name: unknown
567 abort: invalid stage name: unknown
568 [255]
568 [255]
569
569
570 $ hg debugrevspec -p all --optimize '0'
570 $ hg debugrevspec -p all --optimize '0'
571 abort: cannot use --optimize with --show-stage
571 abort: cannot use --optimize with --show-stage
572 [255]
572 [255]
573
573
574 verify optimized tree:
574 verify optimized tree:
575
575
576 $ hg debugrevspec --verify '0|1'
576 $ hg debugrevspec --verify '0|1'
577
577
578 $ hg debugrevspec --verify -v -p analyzed -p optimized 'r3232() & 2'
578 $ hg debugrevspec --verify -v -p analyzed -p optimized 'r3232() & 2'
579 * analyzed:
579 * analyzed:
580 (and
580 (and
581 (func
581 (func
582 ('symbol', 'r3232')
582 ('symbol', 'r3232')
583 None
583 None
584 define)
584 define)
585 ('symbol', '2')
585 ('symbol', '2')
586 define)
586 define)
587 * optimized:
587 * optimized:
588 (and
588 (and
589 ('symbol', '2')
589 ('symbol', '2')
590 (func
590 (func
591 ('symbol', 'r3232')
591 ('symbol', 'r3232')
592 None
592 None
593 define)
593 define)
594 define)
594 define)
595 * analyzed set:
595 * analyzed set:
596 <baseset [2]>
596 <baseset [2]>
597 * optimized set:
597 * optimized set:
598 <baseset [2, 2]>
598 <baseset [2, 2]>
599 --- analyzed
599 --- analyzed
600 +++ optimized
600 +++ optimized
601 2
601 2
602 +2
602 +2
603 [1]
603 [1]
604
604
605 $ hg debugrevspec --no-optimized --verify-optimized '0'
605 $ hg debugrevspec --no-optimized --verify-optimized '0'
606 abort: cannot use --verify-optimized with --no-optimized
606 abort: cannot use --verify-optimized with --no-optimized
607 [255]
607 [255]
608
608
609 Test that symbols only get parsed as functions if there's an opening
609 Test that symbols only get parsed as functions if there's an opening
610 parenthesis.
610 parenthesis.
611
611
612 $ hg book only -r 9
612 $ hg book only -r 9
613 $ log 'only(only)' # Outer "only" is a function, inner "only" is the bookmark
613 $ log 'only(only)' # Outer "only" is a function, inner "only" is the bookmark
614 8
614 8
615 9
615 9
616
616
617 ':y' behaves like '0:y', but can't be rewritten as such since the revision '0'
617 ':y' behaves like '0:y', but can't be rewritten as such since the revision '0'
618 may be hidden (issue5385)
618 may be hidden (issue5385)
619
619
620 $ try -p parsed -p analyzed ':'
620 $ try -p parsed -p analyzed ':'
621 * parsed:
621 * parsed:
622 (rangeall
622 (rangeall
623 None)
623 None)
624 * analyzed:
624 * analyzed:
625 (rangeall
625 (rangeall
626 None
626 None
627 define)
627 define)
628 * set:
628 * set:
629 <spanset+ 0:10>
629 <spanset+ 0:10>
630 0
630 0
631 1
631 1
632 2
632 2
633 3
633 3
634 4
634 4
635 5
635 5
636 6
636 6
637 7
637 7
638 8
638 8
639 9
639 9
640 $ try -p analyzed ':1'
640 $ try -p analyzed ':1'
641 * analyzed:
641 * analyzed:
642 (rangepre
642 (rangepre
643 ('symbol', '1')
643 ('symbol', '1')
644 define)
644 define)
645 * set:
645 * set:
646 <spanset+ 0:2>
646 <spanset+ 0:2>
647 0
647 0
648 1
648 1
649 $ try -p analyzed ':(1|2)'
649 $ try -p analyzed ':(1|2)'
650 * analyzed:
650 * analyzed:
651 (rangepre
651 (rangepre
652 (or
652 (or
653 (list
653 (list
654 ('symbol', '1')
654 ('symbol', '1')
655 ('symbol', '2'))
655 ('symbol', '2'))
656 define)
656 define)
657 define)
657 define)
658 * set:
658 * set:
659 <spanset+ 0:3>
659 <spanset+ 0:3>
660 0
660 0
661 1
661 1
662 2
662 2
663 $ try -p analyzed ':(1&2)'
663 $ try -p analyzed ':(1&2)'
664 * analyzed:
664 * analyzed:
665 (rangepre
665 (rangepre
666 (and
666 (and
667 ('symbol', '1')
667 ('symbol', '1')
668 ('symbol', '2')
668 ('symbol', '2')
669 define)
669 define)
670 define)
670 define)
671 * set:
671 * set:
672 <baseset []>
672 <baseset []>
673
673
674 infix/suffix resolution of ^ operator (issue2884):
674 infix/suffix resolution of ^ operator (issue2884):
675
675
676 x^:y means (x^):y
676 x^:y means (x^):y
677
677
678 $ try '1^:2'
678 $ try '1^:2'
679 (range
679 (range
680 (parentpost
680 (parentpost
681 ('symbol', '1'))
681 ('symbol', '1'))
682 ('symbol', '2'))
682 ('symbol', '2'))
683 * set:
683 * set:
684 <spanset+ 0:3>
684 <spanset+ 0:3>
685 0
685 0
686 1
686 1
687 2
687 2
688
688
689 $ try '1^::2'
689 $ try '1^::2'
690 (dagrange
690 (dagrange
691 (parentpost
691 (parentpost
692 ('symbol', '1'))
692 ('symbol', '1'))
693 ('symbol', '2'))
693 ('symbol', '2'))
694 * set:
694 * set:
695 <baseset+ [0, 1, 2]>
695 <baseset+ [0, 1, 2]>
696 0
696 0
697 1
697 1
698 2
698 2
699
699
700 $ try '9^:'
700 $ try '9^:'
701 (rangepost
701 (rangepost
702 (parentpost
702 (parentpost
703 ('symbol', '9')))
703 ('symbol', '9')))
704 * set:
704 * set:
705 <spanset+ 8:10>
705 <spanset+ 8:10>
706 8
706 8
707 9
707 9
708
708
709 x^:y should be resolved before omitting group operators
709 x^:y should be resolved before omitting group operators
710
710
711 $ try '1^(:2)'
711 $ try '1^(:2)'
712 (parent
712 (parent
713 ('symbol', '1')
713 ('symbol', '1')
714 (group
714 (group
715 (rangepre
715 (rangepre
716 ('symbol', '2'))))
716 ('symbol', '2'))))
717 hg: parse error: ^ expects a number 0, 1, or 2
717 hg: parse error: ^ expects a number 0, 1, or 2
718 [255]
718 [255]
719
719
720 x^:y should be resolved recursively
720 x^:y should be resolved recursively
721
721
722 $ try 'sort(1^:2)'
722 $ try 'sort(1^:2)'
723 (func
723 (func
724 ('symbol', 'sort')
724 ('symbol', 'sort')
725 (range
725 (range
726 (parentpost
726 (parentpost
727 ('symbol', '1'))
727 ('symbol', '1'))
728 ('symbol', '2')))
728 ('symbol', '2')))
729 * set:
729 * set:
730 <spanset+ 0:3>
730 <spanset+ 0:3>
731 0
731 0
732 1
732 1
733 2
733 2
734
734
735 $ try '(3^:4)^:2'
735 $ try '(3^:4)^:2'
736 (range
736 (range
737 (parentpost
737 (parentpost
738 (group
738 (group
739 (range
739 (range
740 (parentpost
740 (parentpost
741 ('symbol', '3'))
741 ('symbol', '3'))
742 ('symbol', '4'))))
742 ('symbol', '4'))))
743 ('symbol', '2'))
743 ('symbol', '2'))
744 * set:
744 * set:
745 <spanset+ 0:3>
745 <spanset+ 0:3>
746 0
746 0
747 1
747 1
748 2
748 2
749
749
750 $ try '(3^::4)^::2'
750 $ try '(3^::4)^::2'
751 (dagrange
751 (dagrange
752 (parentpost
752 (parentpost
753 (group
753 (group
754 (dagrange
754 (dagrange
755 (parentpost
755 (parentpost
756 ('symbol', '3'))
756 ('symbol', '3'))
757 ('symbol', '4'))))
757 ('symbol', '4'))))
758 ('symbol', '2'))
758 ('symbol', '2'))
759 * set:
759 * set:
760 <baseset+ [0, 1, 2]>
760 <baseset+ [0, 1, 2]>
761 0
761 0
762 1
762 1
763 2
763 2
764
764
765 $ try '(9^:)^:'
765 $ try '(9^:)^:'
766 (rangepost
766 (rangepost
767 (parentpost
767 (parentpost
768 (group
768 (group
769 (rangepost
769 (rangepost
770 (parentpost
770 (parentpost
771 ('symbol', '9'))))))
771 ('symbol', '9'))))))
772 * set:
772 * set:
773 <spanset+ 4:10>
773 <spanset+ 4:10>
774 4
774 4
775 5
775 5
776 6
776 6
777 7
777 7
778 8
778 8
779 9
779 9
780
780
781 x^ in alias should also be resolved
781 x^ in alias should also be resolved
782
782
783 $ try 'A' --config 'revsetalias.A=1^:2'
783 $ try 'A' --config 'revsetalias.A=1^:2'
784 ('symbol', 'A')
784 ('symbol', 'A')
785 * expanded:
785 * expanded:
786 (range
786 (range
787 (parentpost
787 (parentpost
788 ('symbol', '1'))
788 ('symbol', '1'))
789 ('symbol', '2'))
789 ('symbol', '2'))
790 * set:
790 * set:
791 <spanset+ 0:3>
791 <spanset+ 0:3>
792 0
792 0
793 1
793 1
794 2
794 2
795
795
796 $ try 'A:2' --config 'revsetalias.A=1^'
796 $ try 'A:2' --config 'revsetalias.A=1^'
797 (range
797 (range
798 ('symbol', 'A')
798 ('symbol', 'A')
799 ('symbol', '2'))
799 ('symbol', '2'))
800 * expanded:
800 * expanded:
801 (range
801 (range
802 (parentpost
802 (parentpost
803 ('symbol', '1'))
803 ('symbol', '1'))
804 ('symbol', '2'))
804 ('symbol', '2'))
805 * set:
805 * set:
806 <spanset+ 0:3>
806 <spanset+ 0:3>
807 0
807 0
808 1
808 1
809 2
809 2
810
810
811 but not beyond the boundary of alias expansion, because the resolution should
811 but not beyond the boundary of alias expansion, because the resolution should
812 be made at the parsing stage
812 be made at the parsing stage
813
813
814 $ try '1^A' --config 'revsetalias.A=:2'
814 $ try '1^A' --config 'revsetalias.A=:2'
815 (parent
815 (parent
816 ('symbol', '1')
816 ('symbol', '1')
817 ('symbol', 'A'))
817 ('symbol', 'A'))
818 * expanded:
818 * expanded:
819 (parent
819 (parent
820 ('symbol', '1')
820 ('symbol', '1')
821 (rangepre
821 (rangepre
822 ('symbol', '2')))
822 ('symbol', '2')))
823 hg: parse error: ^ expects a number 0, 1, or 2
823 hg: parse error: ^ expects a number 0, 1, or 2
824 [255]
824 [255]
825
825
826 ancestor can accept 0 or more arguments
826 ancestor can accept 0 or more arguments
827
827
828 $ log 'ancestor()'
828 $ log 'ancestor()'
829 $ log 'ancestor(1)'
829 $ log 'ancestor(1)'
830 1
830 1
831 $ log 'ancestor(4,5)'
831 $ log 'ancestor(4,5)'
832 1
832 1
833 $ log 'ancestor(4,5) and 4'
833 $ log 'ancestor(4,5) and 4'
834 $ log 'ancestor(0,0,1,3)'
834 $ log 'ancestor(0,0,1,3)'
835 0
835 0
836 $ log 'ancestor(3,1,5,3,5,1)'
836 $ log 'ancestor(3,1,5,3,5,1)'
837 1
837 1
838 $ log 'ancestor(0,1,3,5)'
838 $ log 'ancestor(0,1,3,5)'
839 0
839 0
840 $ log 'ancestor(1,2,3,4,5)'
840 $ log 'ancestor(1,2,3,4,5)'
841 1
841 1
842
842
843 test ancestors
843 test ancestors
844
844
845 $ hg log -G -T '{rev}\n' --config experimental.graphshorten=True
845 $ hg log -G -T '{rev}\n' --config experimental.graphshorten=True
846 @ 9
846 @ 9
847 o 8
847 o 8
848 | o 7
848 | o 7
849 | o 6
849 | o 6
850 |/|
850 |/|
851 | o 5
851 | o 5
852 o | 4
852 o | 4
853 | o 3
853 | o 3
854 o | 2
854 o | 2
855 |/
855 |/
856 o 1
856 o 1
857 o 0
857 o 0
858
858
859 $ log 'ancestors(5)'
859 $ log 'ancestors(5)'
860 0
860 0
861 1
861 1
862 3
862 3
863 5
863 5
864 $ log 'ancestor(ancestors(5))'
864 $ log 'ancestor(ancestors(5))'
865 0
865 0
866 $ log '::r3232()'
866 $ log '::r3232()'
867 0
867 0
868 1
868 1
869 2
869 2
870 3
870 3
871
871
872 test ancestors with depth limit
872 test ancestors with depth limit
873
873
874 (depth=0 selects the node itself)
874 (depth=0 selects the node itself)
875
875
876 $ log 'reverse(ancestors(9, depth=0))'
876 $ log 'reverse(ancestors(9, depth=0))'
877 9
877 9
878
878
879 (interleaved: '4' would be missing if heap queue were higher depth first)
879 (interleaved: '4' would be missing if heap queue were higher depth first)
880
880
881 $ log 'reverse(ancestors(8:9, depth=1))'
881 $ log 'reverse(ancestors(8:9, depth=1))'
882 9
882 9
883 8
883 8
884 4
884 4
885
885
886 (interleaved: '2' would be missing if heap queue were higher depth first)
886 (interleaved: '2' would be missing if heap queue were higher depth first)
887
887
888 $ log 'reverse(ancestors(7+8, depth=2))'
888 $ log 'reverse(ancestors(7+8, depth=2))'
889 8
889 8
890 7
890 7
891 6
891 6
892 5
892 5
893 4
893 4
894 2
894 2
895
895
896 (walk example above by separate queries)
896 (walk example above by separate queries)
897
897
898 $ log 'reverse(ancestors(8, depth=2)) + reverse(ancestors(7, depth=2))'
898 $ log 'reverse(ancestors(8, depth=2)) + reverse(ancestors(7, depth=2))'
899 8
899 8
900 4
900 4
901 2
901 2
902 7
902 7
903 6
903 6
904 5
904 5
905
905
906 (walk 2nd and 3rd ancestors)
906 (walk 2nd and 3rd ancestors)
907
907
908 $ log 'reverse(ancestors(7, depth=3, startdepth=2))'
908 $ log 'reverse(ancestors(7, depth=3, startdepth=2))'
909 5
909 5
910 4
910 4
911 3
911 3
912 2
912 2
913
913
914 (interleaved: '4' would be missing if higher-depth ancestors weren't scanned)
914 (interleaved: '4' would be missing if higher-depth ancestors weren't scanned)
915
915
916 $ log 'reverse(ancestors(7+8, depth=2, startdepth=2))'
916 $ log 'reverse(ancestors(7+8, depth=2, startdepth=2))'
917 5
917 5
918 4
918 4
919 2
919 2
920
920
921 (note that 'ancestors(x, depth=y, startdepth=z)' does not identical to
921 (note that 'ancestors(x, depth=y, startdepth=z)' does not identical to
922 'ancestors(x, depth=y) - ancestors(x, depth=z-1)' because a node may have
922 'ancestors(x, depth=y) - ancestors(x, depth=z-1)' because a node may have
923 multiple depths)
923 multiple depths)
924
924
925 $ log 'reverse(ancestors(7+8, depth=2) - ancestors(7+8, depth=1))'
925 $ log 'reverse(ancestors(7+8, depth=2) - ancestors(7+8, depth=1))'
926 5
926 5
927 2
927 2
928
928
929 test bad arguments passed to ancestors()
929 test bad arguments passed to ancestors()
930
930
931 $ log 'ancestors(., depth=-1)'
931 $ log 'ancestors(., depth=-1)'
932 hg: parse error: negative depth
932 hg: parse error: negative depth
933 [255]
933 [255]
934 $ log 'ancestors(., depth=foo)'
934 $ log 'ancestors(., depth=foo)'
935 hg: parse error: ancestors expects an integer depth
935 hg: parse error: ancestors expects an integer depth
936 [255]
936 [255]
937
937
938 test descendants
938 test descendants
939
939
940 $ hg log -G -T '{rev}\n' --config experimental.graphshorten=True
940 $ hg log -G -T '{rev}\n' --config experimental.graphshorten=True
941 @ 9
941 @ 9
942 o 8
942 o 8
943 | o 7
943 | o 7
944 | o 6
944 | o 6
945 |/|
945 |/|
946 | o 5
946 | o 5
947 o | 4
947 o | 4
948 | o 3
948 | o 3
949 o | 2
949 o | 2
950 |/
950 |/
951 o 1
951 o 1
952 o 0
952 o 0
953
953
954 (null is ultimate root and has optimized path)
954 (null is ultimate root and has optimized path)
955
955
956 $ log 'null:4 & descendants(null)'
956 $ log 'null:4 & descendants(null)'
957 -1
957 -1
958 0
958 0
959 1
959 1
960 2
960 2
961 3
961 3
962 4
962 4
963
963
964 (including merge)
964 (including merge)
965
965
966 $ log ':8 & descendants(2)'
966 $ log ':8 & descendants(2)'
967 2
967 2
968 4
968 4
969 6
969 6
970 7
970 7
971 8
971 8
972
972
973 (multiple roots)
973 (multiple roots)
974
974
975 $ log ':8 & descendants(2+5)'
975 $ log ':8 & descendants(2+5)'
976 2
976 2
977 4
977 4
978 5
978 5
979 6
979 6
980 7
980 7
981 8
981 8
982
982
983 test descendants with depth limit
983 test descendants with depth limit
984
984
985 (depth=0 selects the node itself)
985 (depth=0 selects the node itself)
986
986
987 $ log 'descendants(0, depth=0)'
987 $ log 'descendants(0, depth=0)'
988 0
988 0
989 $ log 'null: & descendants(null, depth=0)'
989 $ log 'null: & descendants(null, depth=0)'
990 -1
990 -1
991
991
992 (p2 = null should be ignored)
992 (p2 = null should be ignored)
993
993
994 $ log 'null: & descendants(null, depth=2)'
994 $ log 'null: & descendants(null, depth=2)'
995 -1
995 -1
996 0
996 0
997 1
997 1
998
998
999 (multiple paths: depth(6) = (2, 3))
999 (multiple paths: depth(6) = (2, 3))
1000
1000
1001 $ log 'descendants(1+3, depth=2)'
1001 $ log 'descendants(1+3, depth=2)'
1002 1
1002 1
1003 2
1003 2
1004 3
1004 3
1005 4
1005 4
1006 5
1006 5
1007 6
1007 6
1008
1008
1009 (multiple paths: depth(5) = (1, 2), depth(6) = (2, 3))
1009 (multiple paths: depth(5) = (1, 2), depth(6) = (2, 3))
1010
1010
1011 $ log 'descendants(3+1, depth=2, startdepth=2)'
1011 $ log 'descendants(3+1, depth=2, startdepth=2)'
1012 4
1012 4
1013 5
1013 5
1014 6
1014 6
1015
1015
1016 (multiple depths: depth(6) = (0, 2, 4), search for depth=2)
1016 (multiple depths: depth(6) = (0, 2, 4), search for depth=2)
1017
1017
1018 $ log 'descendants(0+3+6, depth=3, startdepth=1)'
1018 $ log 'descendants(0+3+6, depth=3, startdepth=1)'
1019 1
1019 1
1020 2
1020 2
1021 3
1021 3
1022 4
1022 4
1023 5
1023 5
1024 6
1024 6
1025 7
1025 7
1026
1026
1027 (multiple depths: depth(6) = (0, 4), no match)
1027 (multiple depths: depth(6) = (0, 4), no match)
1028
1028
1029 $ log 'descendants(0+6, depth=3, startdepth=1)'
1029 $ log 'descendants(0+6, depth=3, startdepth=1)'
1030 1
1030 1
1031 2
1031 2
1032 3
1032 3
1033 4
1033 4
1034 5
1034 5
1035 7
1035 7
1036
1036
1037 test author
1037 test author
1038
1038
1039 $ log 'author(bob)'
1039 $ log 'author(bob)'
1040 2
1040 2
1041 $ log 'author("re:bob|test")'
1041 $ log 'author("re:bob|test")'
1042 0
1042 0
1043 1
1043 1
1044 2
1044 2
1045 3
1045 3
1046 4
1046 4
1047 5
1047 5
1048 6
1048 6
1049 7
1049 7
1050 8
1050 8
1051 9
1051 9
1052 $ log 'author(r"re:\S")'
1052 $ log 'author(r"re:\S")'
1053 0
1053 0
1054 1
1054 1
1055 2
1055 2
1056 3
1056 3
1057 4
1057 4
1058 5
1058 5
1059 6
1059 6
1060 7
1060 7
1061 8
1061 8
1062 9
1062 9
1063 $ log 'branch(Γ©)'
1063 $ log 'branch(Γ©)'
1064 8
1064 8
1065 9
1065 9
1066 $ log 'branch(a)'
1066 $ log 'branch(a)'
1067 0
1067 0
1068 $ hg log -r 'branch("re:a")' --template '{rev} {branch}\n'
1068 $ hg log -r 'branch("re:a")' --template '{rev} {branch}\n'
1069 0 a
1069 0 a
1070 2 a-b-c-
1070 2 a-b-c-
1071 3 +a+b+c+
1071 3 +a+b+c+
1072 4 -a-b-c-
1072 4 -a-b-c-
1073 5 !a/b/c/
1073 5 !a/b/c/
1074 6 _a_b_c_
1074 6 _a_b_c_
1075 7 .a.b.c.
1075 7 .a.b.c.
1076 $ log 'children(ancestor(4,5))'
1076 $ log 'children(ancestor(4,5))'
1077 2
1077 2
1078 3
1078 3
1079
1079
1080 $ log 'children(4)'
1080 $ log 'children(4)'
1081 6
1081 6
1082 8
1082 8
1083 $ log 'children(null)'
1083 $ log 'children(null)'
1084 0
1084 0
1085
1085
1086 $ log 'closed()'
1086 $ log 'closed()'
1087 $ log 'contains(a)'
1087 $ log 'contains(a)'
1088 0
1088 0
1089 1
1089 1
1090 3
1090 3
1091 5
1091 5
1092 $ log 'contains("../repo/a")'
1092 $ log 'contains("../repo/a")'
1093 0
1093 0
1094 1
1094 1
1095 3
1095 3
1096 5
1096 5
1097 $ log 'desc(B)'
1097 $ log 'desc(B)'
1098 5
1098 5
1099 $ hg log -r 'desc(r"re:S?u")' --template "{rev} {desc|firstline}\n"
1099 $ hg log -r 'desc(r"re:S?u")' --template "{rev} {desc|firstline}\n"
1100 5 5 bug
1100 5 5 bug
1101 6 6 issue619
1101 6 6 issue619
1102 $ log 'descendants(2 or 3)'
1102 $ log 'descendants(2 or 3)'
1103 2
1103 2
1104 3
1104 3
1105 4
1105 4
1106 5
1106 5
1107 6
1107 6
1108 7
1108 7
1109 8
1109 8
1110 9
1110 9
1111 $ log 'file("b*")'
1111 $ log 'file("b*")'
1112 1
1112 1
1113 4
1113 4
1114 $ log 'filelog("b")'
1114 $ log 'filelog("b")'
1115 1
1115 1
1116 4
1116 4
1117 $ log 'filelog("../repo/b")'
1117 $ log 'filelog("../repo/b")'
1118 1
1118 1
1119 4
1119 4
1120 $ log 'follow()'
1120 $ log 'follow()'
1121 0
1121 0
1122 1
1122 1
1123 2
1123 2
1124 4
1124 4
1125 8
1125 8
1126 9
1126 9
1127 $ log 'grep("issue\d+")'
1127 $ log 'grep("issue\d+")'
1128 6
1128 6
1129 $ try 'grep("(")' # invalid regular expression
1129 $ try 'grep("(")' # invalid regular expression
1130 (func
1130 (func
1131 ('symbol', 'grep')
1131 ('symbol', 'grep')
1132 ('string', '('))
1132 ('string', '('))
1133 hg: parse error: invalid match pattern: unbalanced parenthesis
1133 hg: parse error: invalid match pattern: unbalanced parenthesis
1134 [255]
1134 [255]
1135 $ try 'grep("\bissue\d+")'
1135 $ try 'grep("\bissue\d+")'
1136 (func
1136 (func
1137 ('symbol', 'grep')
1137 ('symbol', 'grep')
1138 ('string', '\x08issue\\d+'))
1138 ('string', '\x08issue\\d+'))
1139 * set:
1139 * set:
1140 <filteredset
1140 <filteredset
1141 <fullreposet+ 0:10>,
1141 <fullreposet+ 0:10>,
1142 <grep '\x08issue\\d+'>>
1142 <grep '\x08issue\\d+'>>
1143 $ try 'grep(r"\bissue\d+")'
1143 $ try 'grep(r"\bissue\d+")'
1144 (func
1144 (func
1145 ('symbol', 'grep')
1145 ('symbol', 'grep')
1146 ('string', '\\bissue\\d+'))
1146 ('string', '\\bissue\\d+'))
1147 * set:
1147 * set:
1148 <filteredset
1148 <filteredset
1149 <fullreposet+ 0:10>,
1149 <fullreposet+ 0:10>,
1150 <grep '\\bissue\\d+'>>
1150 <grep '\\bissue\\d+'>>
1151 6
1151 6
1152 $ try 'grep(r"\")'
1152 $ try 'grep(r"\")'
1153 hg: parse error at 7: unterminated string
1153 hg: parse error at 7: unterminated string
1154 [255]
1154 [255]
1155 $ log 'head()'
1155 $ log 'head()'
1156 0
1156 0
1157 1
1157 1
1158 2
1158 2
1159 3
1159 3
1160 4
1160 4
1161 5
1161 5
1162 6
1162 6
1163 7
1163 7
1164 9
1164 9
1165 $ log 'heads(6::)'
1165 $ log 'heads(6::)'
1166 7
1166 7
1167 $ log 'keyword(issue)'
1167 $ log 'keyword(issue)'
1168 6
1168 6
1169 $ log 'keyword("test a")'
1169 $ log 'keyword("test a")'
1170
1170
1171 Test first (=limit) and last
1171 Test first (=limit) and last
1172
1172
1173 $ log 'limit(head(), 1)'
1173 $ log 'limit(head(), 1)'
1174 0
1174 0
1175 $ log 'limit(author("re:bob|test"), 3, 5)'
1175 $ log 'limit(author("re:bob|test"), 3, 5)'
1176 5
1176 5
1177 6
1177 6
1178 7
1178 7
1179 $ log 'limit(author("re:bob|test"), offset=6)'
1179 $ log 'limit(author("re:bob|test"), offset=6)'
1180 6
1180 6
1181 $ log 'limit(author("re:bob|test"), offset=10)'
1181 $ log 'limit(author("re:bob|test"), offset=10)'
1182 $ log 'limit(all(), 1, -1)'
1182 $ log 'limit(all(), 1, -1)'
1183 hg: parse error: negative offset
1183 hg: parse error: negative offset
1184 [255]
1184 [255]
1185 $ log 'limit(all(), -1)'
1185 $ log 'limit(all(), -1)'
1186 hg: parse error: negative number to select
1186 hg: parse error: negative number to select
1187 [255]
1187 [255]
1188 $ log 'limit(all(), 0)'
1188 $ log 'limit(all(), 0)'
1189
1189
1190 $ log 'last(all(), -1)'
1190 $ log 'last(all(), -1)'
1191 hg: parse error: negative number to select
1191 hg: parse error: negative number to select
1192 [255]
1192 [255]
1193 $ log 'last(all(), 0)'
1193 $ log 'last(all(), 0)'
1194 $ log 'last(all(), 1)'
1194 $ log 'last(all(), 1)'
1195 9
1195 9
1196 $ log 'last(all(), 2)'
1196 $ log 'last(all(), 2)'
1197 8
1197 8
1198 9
1198 9
1199
1199
1200 Test smartset.slice() by first/last()
1200 Test smartset.slice() by first/last()
1201
1201
1202 (using unoptimized set, filteredset as example)
1202 (using unoptimized set, filteredset as example)
1203
1203
1204 $ hg debugrevspec --no-show-revs -s '0:7 & branch("re:")'
1204 $ hg debugrevspec --no-show-revs -s '0:7 & branch("re:")'
1205 * set:
1205 * set:
1206 <filteredset
1206 <filteredset
1207 <spanset+ 0:8>,
1207 <spanset+ 0:8>,
1208 <branch 're:'>>
1208 <branch 're:'>>
1209 $ log 'limit(0:7 & branch("re:"), 3, 4)'
1209 $ log 'limit(0:7 & branch("re:"), 3, 4)'
1210 4
1210 4
1211 5
1211 5
1212 6
1212 6
1213 $ log 'limit(7:0 & branch("re:"), 3, 4)'
1213 $ log 'limit(7:0 & branch("re:"), 3, 4)'
1214 3
1214 3
1215 2
1215 2
1216 1
1216 1
1217 $ log 'last(0:7 & branch("re:"), 2)'
1217 $ log 'last(0:7 & branch("re:"), 2)'
1218 6
1218 6
1219 7
1219 7
1220
1220
1221 (using baseset)
1221 (using baseset)
1222
1222
1223 $ hg debugrevspec --no-show-revs -s 0+1+2+3+4+5+6+7
1223 $ hg debugrevspec --no-show-revs -s 0+1+2+3+4+5+6+7
1224 * set:
1224 * set:
1225 <baseset [0, 1, 2, 3, 4, 5, 6, 7]>
1225 <baseset [0, 1, 2, 3, 4, 5, 6, 7]>
1226 $ hg debugrevspec --no-show-revs -s 0::7
1226 $ hg debugrevspec --no-show-revs -s 0::7
1227 * set:
1227 * set:
1228 <baseset+ [0, 1, 2, 3, 4, 5, 6, 7]>
1228 <baseset+ [0, 1, 2, 3, 4, 5, 6, 7]>
1229 $ log 'limit(0+1+2+3+4+5+6+7, 3, 4)'
1229 $ log 'limit(0+1+2+3+4+5+6+7, 3, 4)'
1230 4
1230 4
1231 5
1231 5
1232 6
1232 6
1233 $ log 'limit(sort(0::7, rev), 3, 4)'
1233 $ log 'limit(sort(0::7, rev), 3, 4)'
1234 4
1234 4
1235 5
1235 5
1236 6
1236 6
1237 $ log 'limit(sort(0::7, -rev), 3, 4)'
1237 $ log 'limit(sort(0::7, -rev), 3, 4)'
1238 3
1238 3
1239 2
1239 2
1240 1
1240 1
1241 $ log 'last(sort(0::7, rev), 2)'
1241 $ log 'last(sort(0::7, rev), 2)'
1242 6
1242 6
1243 7
1243 7
1244 $ hg debugrevspec -s 'limit(sort(0::7, rev), 3, 6)'
1244 $ hg debugrevspec -s 'limit(sort(0::7, rev), 3, 6)'
1245 * set:
1245 * set:
1246 <baseset+ [6, 7]>
1246 <baseset+ [6, 7]>
1247 6
1247 6
1248 7
1248 7
1249 $ hg debugrevspec -s 'limit(sort(0::7, rev), 3, 9)'
1249 $ hg debugrevspec -s 'limit(sort(0::7, rev), 3, 9)'
1250 * set:
1250 * set:
1251 <baseset+ []>
1251 <baseset+ []>
1252 $ hg debugrevspec -s 'limit(sort(0::7, -rev), 3, 6)'
1252 $ hg debugrevspec -s 'limit(sort(0::7, -rev), 3, 6)'
1253 * set:
1253 * set:
1254 <baseset- [0, 1]>
1254 <baseset- [0, 1]>
1255 1
1255 1
1256 0
1256 0
1257 $ hg debugrevspec -s 'limit(sort(0::7, -rev), 3, 9)'
1257 $ hg debugrevspec -s 'limit(sort(0::7, -rev), 3, 9)'
1258 * set:
1258 * set:
1259 <baseset- []>
1259 <baseset- []>
1260 $ hg debugrevspec -s 'limit(0::7, 0)'
1260 $ hg debugrevspec -s 'limit(0::7, 0)'
1261 * set:
1261 * set:
1262 <baseset+ []>
1262 <baseset+ []>
1263
1263
1264 (using spanset)
1264 (using spanset)
1265
1265
1266 $ hg debugrevspec --no-show-revs -s 0:7
1266 $ hg debugrevspec --no-show-revs -s 0:7
1267 * set:
1267 * set:
1268 <spanset+ 0:8>
1268 <spanset+ 0:8>
1269 $ log 'limit(0:7, 3, 4)'
1269 $ log 'limit(0:7, 3, 4)'
1270 4
1270 4
1271 5
1271 5
1272 6
1272 6
1273 $ log 'limit(7:0, 3, 4)'
1273 $ log 'limit(7:0, 3, 4)'
1274 3
1274 3
1275 2
1275 2
1276 1
1276 1
1277 $ log 'limit(0:7, 3, 6)'
1277 $ log 'limit(0:7, 3, 6)'
1278 6
1278 6
1279 7
1279 7
1280 $ log 'limit(7:0, 3, 6)'
1280 $ log 'limit(7:0, 3, 6)'
1281 1
1281 1
1282 0
1282 0
1283 $ log 'last(0:7, 2)'
1283 $ log 'last(0:7, 2)'
1284 6
1284 6
1285 7
1285 7
1286 $ hg debugrevspec -s 'limit(0:7, 3, 6)'
1286 $ hg debugrevspec -s 'limit(0:7, 3, 6)'
1287 * set:
1287 * set:
1288 <spanset+ 6:8>
1288 <spanset+ 6:8>
1289 6
1289 6
1290 7
1290 7
1291 $ hg debugrevspec -s 'limit(0:7, 3, 9)'
1291 $ hg debugrevspec -s 'limit(0:7, 3, 9)'
1292 * set:
1292 * set:
1293 <spanset+ 8:8>
1293 <spanset+ 8:8>
1294 $ hg debugrevspec -s 'limit(7:0, 3, 6)'
1294 $ hg debugrevspec -s 'limit(7:0, 3, 6)'
1295 * set:
1295 * set:
1296 <spanset- 0:2>
1296 <spanset- 0:2>
1297 1
1297 1
1298 0
1298 0
1299 $ hg debugrevspec -s 'limit(7:0, 3, 9)'
1299 $ hg debugrevspec -s 'limit(7:0, 3, 9)'
1300 * set:
1300 * set:
1301 <spanset- 0:0>
1301 <spanset- 0:0>
1302 $ hg debugrevspec -s 'limit(0:7, 0)'
1302 $ hg debugrevspec -s 'limit(0:7, 0)'
1303 * set:
1303 * set:
1304 <spanset+ 0:0>
1304 <spanset+ 0:0>
1305
1305
1306 Test order of first/last revisions
1306 Test order of first/last revisions
1307
1307
1308 $ hg debugrevspec -s 'first(4:0, 3) & 3:'
1308 $ hg debugrevspec -s 'first(4:0, 3) & 3:'
1309 * set:
1309 * set:
1310 <filteredset
1310 <filteredset
1311 <spanset- 2:5>,
1311 <spanset- 2:5>,
1312 <spanset+ 3:10>>
1312 <spanset+ 3:10>>
1313 4
1313 4
1314 3
1314 3
1315
1315
1316 $ hg debugrevspec -s '3: & first(4:0, 3)'
1316 $ hg debugrevspec -s '3: & first(4:0, 3)'
1317 * set:
1317 * set:
1318 <filteredset
1318 <filteredset
1319 <spanset+ 3:10>,
1319 <spanset+ 3:10>,
1320 <spanset- 2:5>>
1320 <spanset- 2:5>>
1321 3
1321 3
1322 4
1322 4
1323
1323
1324 $ hg debugrevspec -s 'last(4:0, 3) & :1'
1324 $ hg debugrevspec -s 'last(4:0, 3) & :1'
1325 * set:
1325 * set:
1326 <filteredset
1326 <filteredset
1327 <spanset- 0:3>,
1327 <spanset- 0:3>,
1328 <spanset+ 0:2>>
1328 <spanset+ 0:2>>
1329 1
1329 1
1330 0
1330 0
1331
1331
1332 $ hg debugrevspec -s ':1 & last(4:0, 3)'
1332 $ hg debugrevspec -s ':1 & last(4:0, 3)'
1333 * set:
1333 * set:
1334 <filteredset
1334 <filteredset
1335 <spanset+ 0:2>,
1335 <spanset+ 0:2>,
1336 <spanset+ 0:3>>
1336 <spanset+ 0:3>>
1337 0
1337 0
1338 1
1338 1
1339
1339
1340 Test scmutil.revsingle() should return the last revision
1340 Test scmutil.revsingle() should return the last revision
1341
1341
1342 $ hg debugrevspec -s 'last(0::)'
1342 $ hg debugrevspec -s 'last(0::)'
1343 * set:
1343 * set:
1344 <baseset slice=0:1
1344 <baseset slice=0:1
1345 <generatorset->>
1345 <generatorset->>
1346 9
1346 9
1347 $ hg identify -r '0::' --num
1347 $ hg identify -r '0::' --num
1348 9
1348 9
1349
1349
1350 Test matching
1350 Test matching
1351
1351
1352 $ log 'matching(6)'
1352 $ log 'matching(6)'
1353 6
1353 6
1354 $ log 'matching(6:7, "phase parents user date branch summary files description substate")'
1354 $ log 'matching(6:7, "phase parents user date branch summary files description substate")'
1355 6
1355 6
1356 7
1356 7
1357
1357
1358 Testing min and max
1358 Testing min and max
1359
1359
1360 max: simple
1360 max: simple
1361
1361
1362 $ log 'max(contains(a))'
1362 $ log 'max(contains(a))'
1363 5
1363 5
1364
1364
1365 max: simple on unordered set)
1365 max: simple on unordered set)
1366
1366
1367 $ log 'max((4+0+2+5+7) and contains(a))'
1367 $ log 'max((4+0+2+5+7) and contains(a))'
1368 5
1368 5
1369
1369
1370 max: no result
1370 max: no result
1371
1371
1372 $ log 'max(contains(stringthatdoesnotappearanywhere))'
1372 $ log 'max(contains(stringthatdoesnotappearanywhere))'
1373
1373
1374 max: no result on unordered set
1374 max: no result on unordered set
1375
1375
1376 $ log 'max((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
1376 $ log 'max((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
1377
1377
1378 min: simple
1378 min: simple
1379
1379
1380 $ log 'min(contains(a))'
1380 $ log 'min(contains(a))'
1381 0
1381 0
1382
1382
1383 min: simple on unordered set
1383 min: simple on unordered set
1384
1384
1385 $ log 'min((4+0+2+5+7) and contains(a))'
1385 $ log 'min((4+0+2+5+7) and contains(a))'
1386 0
1386 0
1387
1387
1388 min: empty
1388 min: empty
1389
1389
1390 $ log 'min(contains(stringthatdoesnotappearanywhere))'
1390 $ log 'min(contains(stringthatdoesnotappearanywhere))'
1391
1391
1392 min: empty on unordered set
1392 min: empty on unordered set
1393
1393
1394 $ log 'min((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
1394 $ log 'min((4+0+2+5+7) and contains(stringthatdoesnotappearanywhere))'
1395
1395
1396
1396
1397 $ log 'merge()'
1397 $ log 'merge()'
1398 6
1398 6
1399 $ log 'branchpoint()'
1399 $ log 'branchpoint()'
1400 1
1400 1
1401 4
1401 4
1402 $ log 'modifies(b)'
1402 $ log 'modifies(b)'
1403 4
1403 4
1404 $ log 'modifies("path:b")'
1404 $ log 'modifies("path:b")'
1405 4
1405 4
1406 $ log 'modifies("*")'
1406 $ log 'modifies("*")'
1407 4
1407 4
1408 6
1408 6
1409 $ log 'modifies("set:modified()")'
1409 $ log 'modifies("set:modified()")'
1410 4
1410 4
1411 $ log 'id(5)'
1411 $ log 'id(5)'
1412 2
1412 2
1413 $ log 'only(9)'
1413 $ log 'only(9)'
1414 8
1414 8
1415 9
1415 9
1416 $ log 'only(8)'
1416 $ log 'only(8)'
1417 8
1417 8
1418 $ log 'only(9, 5)'
1418 $ log 'only(9, 5)'
1419 2
1419 2
1420 4
1420 4
1421 8
1421 8
1422 9
1422 9
1423 $ log 'only(7 + 9, 5 + 2)'
1423 $ log 'only(7 + 9, 5 + 2)'
1424 4
1424 4
1425 6
1425 6
1426 7
1426 7
1427 8
1427 8
1428 9
1428 9
1429
1429
1430 Test empty set input
1430 Test empty set input
1431 $ log 'only(p2())'
1431 $ log 'only(p2())'
1432 $ log 'only(p1(), p2())'
1432 $ log 'only(p1(), p2())'
1433 0
1433 0
1434 1
1434 1
1435 2
1435 2
1436 4
1436 4
1437 8
1437 8
1438 9
1438 9
1439
1439
1440 Test '%' operator
1440 Test '%' operator
1441
1441
1442 $ log '9%'
1442 $ log '9%'
1443 8
1443 8
1444 9
1444 9
1445 $ log '9%5'
1445 $ log '9%5'
1446 2
1446 2
1447 4
1447 4
1448 8
1448 8
1449 9
1449 9
1450 $ log '(7 + 9)%(5 + 2)'
1450 $ log '(7 + 9)%(5 + 2)'
1451 4
1451 4
1452 6
1452 6
1453 7
1453 7
1454 8
1454 8
1455 9
1455 9
1456
1456
1457 Test operand of '%' is optimized recursively (issue4670)
1457 Test operand of '%' is optimized recursively (issue4670)
1458
1458
1459 $ try --optimize '8:9-8%'
1459 $ try --optimize '8:9-8%'
1460 (onlypost
1460 (onlypost
1461 (minus
1461 (minus
1462 (range
1462 (range
1463 ('symbol', '8')
1463 ('symbol', '8')
1464 ('symbol', '9'))
1464 ('symbol', '9'))
1465 ('symbol', '8')))
1465 ('symbol', '8')))
1466 * optimized:
1466 * optimized:
1467 (func
1467 (func
1468 ('symbol', 'only')
1468 ('symbol', 'only')
1469 (difference
1469 (difference
1470 (range
1470 (range
1471 ('symbol', '8')
1471 ('symbol', '8')
1472 ('symbol', '9')
1472 ('symbol', '9')
1473 define)
1473 define)
1474 ('symbol', '8')
1474 ('symbol', '8')
1475 define)
1475 define)
1476 define)
1476 define)
1477 * set:
1477 * set:
1478 <baseset+ [8, 9]>
1478 <baseset+ [8, 9]>
1479 8
1479 8
1480 9
1480 9
1481 $ try --optimize '(9)%(5)'
1481 $ try --optimize '(9)%(5)'
1482 (only
1482 (only
1483 (group
1483 (group
1484 ('symbol', '9'))
1484 ('symbol', '9'))
1485 (group
1485 (group
1486 ('symbol', '5')))
1486 ('symbol', '5')))
1487 * optimized:
1487 * optimized:
1488 (func
1488 (func
1489 ('symbol', 'only')
1489 ('symbol', 'only')
1490 (list
1490 (list
1491 ('symbol', '9')
1491 ('symbol', '9')
1492 ('symbol', '5'))
1492 ('symbol', '5'))
1493 define)
1493 define)
1494 * set:
1494 * set:
1495 <baseset+ [2, 4, 8, 9]>
1495 <baseset+ [2, 4, 8, 9]>
1496 2
1496 2
1497 4
1497 4
1498 8
1498 8
1499 9
1499 9
1500
1500
1501 Test the order of operations
1501 Test the order of operations
1502
1502
1503 $ log '7 + 9%5 + 2'
1503 $ log '7 + 9%5 + 2'
1504 7
1504 7
1505 2
1505 2
1506 4
1506 4
1507 8
1507 8
1508 9
1508 9
1509
1509
1510 Test explicit numeric revision
1510 Test explicit numeric revision
1511 $ log 'rev(-2)'
1511 $ log 'rev(-2)'
1512 $ log 'rev(-1)'
1512 $ log 'rev(-1)'
1513 -1
1513 -1
1514 $ log 'rev(0)'
1514 $ log 'rev(0)'
1515 0
1515 0
1516 $ log 'rev(9)'
1516 $ log 'rev(9)'
1517 9
1517 9
1518 $ log 'rev(10)'
1518 $ log 'rev(10)'
1519 $ log 'rev(tip)'
1519 $ log 'rev(tip)'
1520 hg: parse error: rev expects a number
1520 hg: parse error: rev expects a number
1521 [255]
1521 [255]
1522
1522
1523 Test hexadecimal revision
1523 Test hexadecimal revision
1524 $ log 'id(2)'
1524 $ log 'id(2)'
1525 abort: 00changelog.i@2: ambiguous identifier!
1525 abort: 00changelog.i@2: ambiguous identifier!
1526 [255]
1526 [255]
1527 $ log 'id(23268)'
1527 $ log 'id(23268)'
1528 4
1528 4
1529 $ log 'id(2785f51eece)'
1529 $ log 'id(2785f51eece)'
1530 0
1530 0
1531 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532c)'
1531 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532c)'
1532 8
1532 8
1533 $ log 'id(d5d0dcbdc4a)'
1533 $ log 'id(d5d0dcbdc4a)'
1534 $ log 'id(d5d0dcbdc4w)'
1534 $ log 'id(d5d0dcbdc4w)'
1535 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532d)'
1535 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532d)'
1536 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532q)'
1536 $ log 'id(d5d0dcbdc4d9ff5dbb2d336f32f0bb561c1a532q)'
1537 $ log 'id(1.0)'
1537 $ log 'id(1.0)'
1538 $ log 'id(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)'
1538 $ log 'id(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)'
1539
1539
1540 Test null revision
1540 Test null revision
1541 $ log '(null)'
1541 $ log '(null)'
1542 -1
1542 -1
1543 $ log '(null:0)'
1543 $ log '(null:0)'
1544 -1
1544 -1
1545 0
1545 0
1546 $ log '(0:null)'
1546 $ log '(0:null)'
1547 0
1547 0
1548 -1
1548 -1
1549 $ log 'null::0'
1549 $ log 'null::0'
1550 -1
1550 -1
1551 0
1551 0
1552 $ log 'null:tip - 0:'
1552 $ log 'null:tip - 0:'
1553 -1
1553 -1
1554 $ log 'null: and null::' | head -1
1554 $ log 'null: and null::' | head -1
1555 -1
1555 -1
1556 $ log 'null: or 0:' | head -2
1556 $ log 'null: or 0:' | head -2
1557 -1
1557 -1
1558 0
1558 0
1559 $ log 'ancestors(null)'
1559 $ log 'ancestors(null)'
1560 -1
1560 -1
1561 $ log 'reverse(null:)' | tail -2
1561 $ log 'reverse(null:)' | tail -2
1562 0
1562 0
1563 -1
1563 -1
1564 $ log 'first(null:)'
1564 $ log 'first(null:)'
1565 -1
1565 -1
1566 $ log 'min(null:)'
1566 $ log 'min(null:)'
1567 BROKEN: should be '-1'
1567 BROKEN: should be '-1'
1568 $ log 'tip:null and all()' | tail -2
1568 $ log 'tip:null and all()' | tail -2
1569 1
1569 1
1570 0
1570 0
1571
1571
1572 Test working-directory revision
1572 Test working-directory revision
1573 $ hg debugrevspec 'wdir()'
1573 $ hg debugrevspec 'wdir()'
1574 2147483647
1574 2147483647
1575 $ hg debugrevspec 'wdir()^'
1575 $ hg debugrevspec 'wdir()^'
1576 9
1576 9
1577 $ hg up 7
1577 $ hg up 7
1578 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
1578 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
1579 $ hg debugrevspec 'wdir()^'
1579 $ hg debugrevspec 'wdir()^'
1580 7
1580 7
1581 $ hg debugrevspec 'wdir()^0'
1581 $ hg debugrevspec 'wdir()^0'
1582 2147483647
1582 2147483647
1583 $ hg debugrevspec 'wdir()~3'
1583 $ hg debugrevspec 'wdir()~3'
1584 5
1584 5
1585 $ hg debugrevspec 'ancestors(wdir())'
1585 $ hg debugrevspec 'ancestors(wdir())'
1586 0
1586 0
1587 1
1587 1
1588 2
1588 2
1589 3
1589 3
1590 4
1590 4
1591 5
1591 5
1592 6
1592 6
1593 7
1593 7
1594 2147483647
1594 2147483647
1595 $ hg debugrevspec 'wdir()~0'
1595 $ hg debugrevspec 'wdir()~0'
1596 2147483647
1596 2147483647
1597 $ hg debugrevspec 'p1(wdir())'
1597 $ hg debugrevspec 'p1(wdir())'
1598 7
1598 7
1599 $ hg debugrevspec 'p2(wdir())'
1599 $ hg debugrevspec 'p2(wdir())'
1600 $ hg debugrevspec 'parents(wdir())'
1600 $ hg debugrevspec 'parents(wdir())'
1601 7
1601 7
1602 $ hg debugrevspec 'wdir()^1'
1602 $ hg debugrevspec 'wdir()^1'
1603 7
1603 7
1604 $ hg debugrevspec 'wdir()^2'
1604 $ hg debugrevspec 'wdir()^2'
1605 $ hg debugrevspec 'wdir()^3'
1605 $ hg debugrevspec 'wdir()^3'
1606 hg: parse error: ^ expects a number 0, 1, or 2
1606 hg: parse error: ^ expects a number 0, 1, or 2
1607 [255]
1607 [255]
1608 For tests consistency
1608 For tests consistency
1609 $ hg up 9
1609 $ hg up 9
1610 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
1610 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
1611 $ hg debugrevspec 'tip or wdir()'
1611 $ hg debugrevspec 'tip or wdir()'
1612 9
1612 9
1613 2147483647
1613 2147483647
1614 $ hg debugrevspec '0:tip and wdir()'
1614 $ hg debugrevspec '0:tip and wdir()'
1615 $ log '0:wdir()' | tail -3
1615 $ log '0:wdir()' | tail -3
1616 8
1616 8
1617 9
1617 9
1618 2147483647
1618 2147483647
1619 $ log 'wdir():0' | head -3
1619 $ log 'wdir():0' | head -3
1620 2147483647
1620 2147483647
1621 9
1621 9
1622 8
1622 8
1623 $ log 'wdir():wdir()'
1623 $ log 'wdir():wdir()'
1624 2147483647
1624 2147483647
1625 $ log '(all() + wdir()) & min(. + wdir())'
1625 $ log '(all() + wdir()) & min(. + wdir())'
1626 9
1626 9
1627 $ log '(all() + wdir()) & max(. + wdir())'
1627 $ log '(all() + wdir()) & max(. + wdir())'
1628 2147483647
1628 2147483647
1629 $ log 'first(wdir() + .)'
1629 $ log 'first(wdir() + .)'
1630 2147483647
1630 2147483647
1631 $ log 'last(. + wdir())'
1631 $ log 'last(. + wdir())'
1632 2147483647
1632 2147483647
1633
1633
1634 Test working-directory integer revision and node id
1634 Test working-directory integer revision and node id
1635 (BUG: '0:wdir()' is still needed to populate wdir revision)
1635 (BUG: '0:wdir()' is still needed to populate wdir revision)
1636
1636
1637 $ hg debugrevspec '0:wdir() & 2147483647'
1637 $ hg debugrevspec '0:wdir() & 2147483647'
1638 2147483647
1638 2147483647
1639 $ hg debugrevspec '0:wdir() & rev(2147483647)'
1639 $ hg debugrevspec '0:wdir() & rev(2147483647)'
1640 2147483647
1640 2147483647
1641 $ hg debugrevspec '0:wdir() & ffffffffffffffffffffffffffffffffffffffff'
1641 $ hg debugrevspec '0:wdir() & ffffffffffffffffffffffffffffffffffffffff'
1642 2147483647
1642 2147483647
1643 $ hg debugrevspec '0:wdir() & ffffffffffff'
1643 $ hg debugrevspec '0:wdir() & ffffffffffff'
1644 2147483647
1644 2147483647
1645 $ hg debugrevspec '0:wdir() & id(ffffffffffffffffffffffffffffffffffffffff)'
1645 $ hg debugrevspec '0:wdir() & id(ffffffffffffffffffffffffffffffffffffffff)'
1646 2147483647
1646 2147483647
1647 $ hg debugrevspec '0:wdir() & id(ffffffffffff)'
1647 $ hg debugrevspec '0:wdir() & id(ffffffffffff)'
1648 2147483647
1648 2147483647
1649
1649
1650 $ cd ..
1650 $ cd ..
1651
1651
1652 Test short 'ff...' hash collision
1652 Test short 'ff...' hash collision
1653 (BUG: '0:wdir()' is still needed to populate wdir revision)
1653 (BUG: '0:wdir()' is still needed to populate wdir revision)
1654
1654
1655 $ hg init wdir-hashcollision
1655 $ hg init wdir-hashcollision
1656 $ cd wdir-hashcollision
1656 $ cd wdir-hashcollision
1657 $ cat <<EOF >> .hg/hgrc
1657 $ cat <<EOF >> .hg/hgrc
1658 > [experimental]
1658 > [experimental]
1659 > evolution = createmarkers
1659 > evolution = createmarkers
1660 > EOF
1660 > EOF
1661 $ echo 0 > a
1661 $ echo 0 > a
1662 $ hg ci -qAm 0
1662 $ hg ci -qAm 0
1663 $ for i in 2463 2961 6726 78127; do
1663 $ for i in 2463 2961 6726 78127; do
1664 > hg up -q 0
1664 > hg up -q 0
1665 > echo $i > a
1665 > echo $i > a
1666 > hg ci -qm $i
1666 > hg ci -qm $i
1667 > done
1667 > done
1668 $ hg up -q null
1668 $ hg up -q null
1669 $ hg log -r '0:wdir()' -T '{rev}:{node} {shortest(node, 3)}\n'
1669 $ hg log -r '0:wdir()' -T '{rev}:{node} {shortest(node, 3)}\n'
1670 0:b4e73ffab476aa0ee32ed81ca51e07169844bc6a b4e
1670 0:b4e73ffab476aa0ee32ed81ca51e07169844bc6a b4e
1671 1:fffbae3886c8fbb2114296380d276fd37715d571 fffba
1671 1:fffbae3886c8fbb2114296380d276fd37715d571 fffba
1672 2:fffb6093b00943f91034b9bdad069402c834e572 fffb6
1672 2:fffb6093b00943f91034b9bdad069402c834e572 fffb6
1673 3:fff48a9b9de34a4d64120c29548214c67980ade3 fff4
1673 3:fff48a9b9de34a4d64120c29548214c67980ade3 fff4
1674 4:ffff85cff0ff78504fcdc3c0bc10de0c65379249 ffff8
1674 4:ffff85cff0ff78504fcdc3c0bc10de0c65379249 ffff8
1675 2147483647:ffffffffffffffffffffffffffffffffffffffff fffff
1675 2147483647:ffffffffffffffffffffffffffffffffffffffff fffff
1676 $ hg debugobsolete fffbae3886c8fbb2114296380d276fd37715d571
1676 $ hg debugobsolete fffbae3886c8fbb2114296380d276fd37715d571
1677
1677
1678 $ hg debugrevspec '0:wdir() & fff'
1678 $ hg debugrevspec '0:wdir() & fff'
1679 abort: 00changelog.i@fff: ambiguous identifier!
1679 abort: 00changelog.i@fff: ambiguous identifier!
1680 [255]
1680 [255]
1681 $ hg debugrevspec '0:wdir() & ffff'
1681 $ hg debugrevspec '0:wdir() & ffff'
1682 abort: 00changelog.i@ffff: ambiguous identifier!
1682 abort: 00changelog.i@ffff: ambiguous identifier!
1683 [255]
1683 [255]
1684 $ hg debugrevspec '0:wdir() & fffb'
1684 $ hg debugrevspec '0:wdir() & fffb'
1685 abort: 00changelog.i@fffb: ambiguous identifier!
1685 abort: 00changelog.i@fffb: ambiguous identifier!
1686 [255]
1686 [255]
1687 BROKEN should be '2' (node lookup uses unfiltered repo since dc25ed84bee8)
1687 BROKEN should be '2' (node lookup uses unfiltered repo since dc25ed84bee8)
1688 $ hg debugrevspec '0:wdir() & id(fffb)'
1688 $ hg debugrevspec '0:wdir() & id(fffb)'
1689 2
1689 2
1690 $ hg debugrevspec '0:wdir() & ffff8'
1690 $ hg debugrevspec '0:wdir() & ffff8'
1691 4
1691 4
1692 $ hg debugrevspec '0:wdir() & fffff'
1692 $ hg debugrevspec '0:wdir() & fffff'
1693 2147483647
1693 2147483647
1694
1694
1695 $ cd ..
1695 $ cd ..
1696
1696
1697 Test branch() with wdir()
1697 Test branch() with wdir()
1698
1698
1699 $ cd repo
1699 $ cd repo
1700
1700
1701 $ log '0:wdir() & branch("literal:Γ©")'
1701 $ log '0:wdir() & branch("literal:Γ©")'
1702 8
1702 8
1703 9
1703 9
1704 2147483647
1704 2147483647
1705 $ log '0:wdir() & branch("re:Γ©")'
1705 $ log '0:wdir() & branch("re:Γ©")'
1706 8
1706 8
1707 9
1707 9
1708 2147483647
1708 2147483647
1709 $ log '0:wdir() & branch("re:^a")'
1709 $ log '0:wdir() & branch("re:^a")'
1710 0
1710 0
1711 2
1711 2
1712 $ log '0:wdir() & branch(8)'
1712 $ log '0:wdir() & branch(8)'
1713 8
1713 8
1714 9
1714 9
1715 2147483647
1715 2147483647
1716
1716
1717 branch(wdir()) returns all revisions belonging to the working branch. The wdir
1717 branch(wdir()) returns all revisions belonging to the working branch. The wdir
1718 itself isn't returned unless it is explicitly populated.
1718 itself isn't returned unless it is explicitly populated.
1719
1719
1720 $ log 'branch(wdir())'
1720 $ log 'branch(wdir())'
1721 8
1721 8
1722 9
1722 9
1723 $ log '0:wdir() & branch(wdir())'
1723 $ log '0:wdir() & branch(wdir())'
1724 8
1724 8
1725 9
1725 9
1726 2147483647
1726 2147483647
1727
1727
1728 $ log 'outgoing()'
1728 $ log 'outgoing()'
1729 8
1729 8
1730 9
1730 9
1731 $ log 'outgoing("../remote1")'
1731 $ log 'outgoing("../remote1")'
1732 8
1732 8
1733 9
1733 9
1734 $ log 'outgoing("../remote2")'
1734 $ log 'outgoing("../remote2")'
1735 3
1735 3
1736 5
1736 5
1737 6
1737 6
1738 7
1738 7
1739 9
1739 9
1740 $ log 'p1(merge())'
1740 $ log 'p1(merge())'
1741 5
1741 5
1742 $ log 'p2(merge())'
1742 $ log 'p2(merge())'
1743 4
1743 4
1744 $ log 'parents(merge())'
1744 $ log 'parents(merge())'
1745 4
1745 4
1746 5
1746 5
1747 $ log 'p1(branchpoint())'
1747 $ log 'p1(branchpoint())'
1748 0
1748 0
1749 2
1749 2
1750 $ log 'p2(branchpoint())'
1750 $ log 'p2(branchpoint())'
1751 $ log 'parents(branchpoint())'
1751 $ log 'parents(branchpoint())'
1752 0
1752 0
1753 2
1753 2
1754 $ log 'removes(a)'
1754 $ log 'removes(a)'
1755 2
1755 2
1756 6
1756 6
1757 $ log 'roots(all())'
1757 $ log 'roots(all())'
1758 0
1758 0
1759 $ log 'reverse(2 or 3 or 4 or 5)'
1759 $ log 'reverse(2 or 3 or 4 or 5)'
1760 5
1760 5
1761 4
1761 4
1762 3
1762 3
1763 2
1763 2
1764 $ log 'reverse(all())'
1764 $ log 'reverse(all())'
1765 9
1765 9
1766 8
1766 8
1767 7
1767 7
1768 6
1768 6
1769 5
1769 5
1770 4
1770 4
1771 3
1771 3
1772 2
1772 2
1773 1
1773 1
1774 0
1774 0
1775 $ log 'reverse(all()) & filelog(b)'
1775 $ log 'reverse(all()) & filelog(b)'
1776 4
1776 4
1777 1
1777 1
1778 $ log 'rev(5)'
1778 $ log 'rev(5)'
1779 5
1779 5
1780 $ log 'sort(limit(reverse(all()), 3))'
1780 $ log 'sort(limit(reverse(all()), 3))'
1781 7
1781 7
1782 8
1782 8
1783 9
1783 9
1784 $ log 'sort(2 or 3 or 4 or 5, date)'
1784 $ log 'sort(2 or 3 or 4 or 5, date)'
1785 2
1785 2
1786 3
1786 3
1787 5
1787 5
1788 4
1788 4
1789 $ log 'tagged()'
1789 $ log 'tagged()'
1790 6
1790 6
1791 $ log 'tag()'
1791 $ log 'tag()'
1792 6
1792 6
1793 $ log 'tag(1.0)'
1793 $ log 'tag(1.0)'
1794 6
1794 6
1795 $ log 'tag(tip)'
1795 $ log 'tag(tip)'
1796 9
1796 9
1797
1797
1798 Test order of revisions in compound expression
1798 Test order of revisions in compound expression
1799 ----------------------------------------------
1799 ----------------------------------------------
1800
1800
1801 The general rule is that only the outermost (= leftmost) predicate can
1801 The general rule is that only the outermost (= leftmost) predicate can
1802 enforce its ordering requirement. The other predicates should take the
1802 enforce its ordering requirement. The other predicates should take the
1803 ordering defined by it.
1803 ordering defined by it.
1804
1804
1805 'A & B' should follow the order of 'A':
1805 'A & B' should follow the order of 'A':
1806
1806
1807 $ log '2:0 & 0::2'
1807 $ log '2:0 & 0::2'
1808 2
1808 2
1809 1
1809 1
1810 0
1810 0
1811
1811
1812 'head()' combines sets in right order:
1812 'head()' combines sets in right order:
1813
1813
1814 $ log '2:0 & head()'
1814 $ log '2:0 & head()'
1815 2
1815 2
1816 1
1816 1
1817 0
1817 0
1818
1818
1819 'x:y' takes ordering parameter into account:
1819 'x:y' takes ordering parameter into account:
1820
1820
1821 $ try -p optimized '3:0 & 0:3 & not 2:1'
1821 $ try -p optimized '3:0 & 0:3 & not 2:1'
1822 * optimized:
1822 * optimized:
1823 (difference
1823 (difference
1824 (and
1824 (and
1825 (range
1825 (range
1826 ('symbol', '3')
1826 ('symbol', '3')
1827 ('symbol', '0')
1827 ('symbol', '0')
1828 define)
1828 define)
1829 (range
1829 (range
1830 ('symbol', '0')
1830 ('symbol', '0')
1831 ('symbol', '3')
1831 ('symbol', '3')
1832 follow)
1832 follow)
1833 define)
1833 define)
1834 (range
1834 (range
1835 ('symbol', '2')
1835 ('symbol', '2')
1836 ('symbol', '1')
1836 ('symbol', '1')
1837 any)
1837 any)
1838 define)
1838 define)
1839 * set:
1839 * set:
1840 <filteredset
1840 <filteredset
1841 <filteredset
1841 <filteredset
1842 <spanset- 0:4>,
1842 <spanset- 0:4>,
1843 <spanset+ 0:4>>,
1843 <spanset+ 0:4>>,
1844 <not
1844 <not
1845 <spanset+ 1:3>>>
1845 <spanset+ 1:3>>>
1846 3
1846 3
1847 0
1847 0
1848
1848
1849 'a + b', which is optimized to '_list(a b)', should take the ordering of
1849 'a + b', which is optimized to '_list(a b)', should take the ordering of
1850 the left expression:
1850 the left expression:
1851
1851
1852 $ try --optimize '2:0 & (0 + 1 + 2)'
1852 $ try --optimize '2:0 & (0 + 1 + 2)'
1853 (and
1853 (and
1854 (range
1854 (range
1855 ('symbol', '2')
1855 ('symbol', '2')
1856 ('symbol', '0'))
1856 ('symbol', '0'))
1857 (group
1857 (group
1858 (or
1858 (or
1859 (list
1859 (list
1860 ('symbol', '0')
1860 ('symbol', '0')
1861 ('symbol', '1')
1861 ('symbol', '1')
1862 ('symbol', '2')))))
1862 ('symbol', '2')))))
1863 * optimized:
1863 * optimized:
1864 (and
1864 (and
1865 (range
1865 (range
1866 ('symbol', '2')
1866 ('symbol', '2')
1867 ('symbol', '0')
1867 ('symbol', '0')
1868 define)
1868 define)
1869 (func
1869 (func
1870 ('symbol', '_list')
1870 ('symbol', '_list')
1871 ('string', '0\x001\x002')
1871 ('string', '0\x001\x002')
1872 follow)
1872 follow)
1873 define)
1873 define)
1874 * set:
1874 * set:
1875 <filteredset
1875 <filteredset
1876 <spanset- 0:3>,
1876 <spanset- 0:3>,
1877 <baseset [0, 1, 2]>>
1877 <baseset [0, 1, 2]>>
1878 2
1878 2
1879 1
1879 1
1880 0
1880 0
1881
1881
1882 'A + B' should take the ordering of the left expression:
1882 'A + B' should take the ordering of the left expression:
1883
1883
1884 $ try --optimize '2:0 & (0:1 + 2)'
1884 $ try --optimize '2:0 & (0:1 + 2)'
1885 (and
1885 (and
1886 (range
1886 (range
1887 ('symbol', '2')
1887 ('symbol', '2')
1888 ('symbol', '0'))
1888 ('symbol', '0'))
1889 (group
1889 (group
1890 (or
1890 (or
1891 (list
1891 (list
1892 (range
1892 (range
1893 ('symbol', '0')
1893 ('symbol', '0')
1894 ('symbol', '1'))
1894 ('symbol', '1'))
1895 ('symbol', '2')))))
1895 ('symbol', '2')))))
1896 * optimized:
1896 * optimized:
1897 (and
1897 (and
1898 (range
1898 (range
1899 ('symbol', '2')
1899 ('symbol', '2')
1900 ('symbol', '0')
1900 ('symbol', '0')
1901 define)
1901 define)
1902 (or
1902 (or
1903 (list
1903 (list
1904 ('symbol', '2')
1904 ('symbol', '2')
1905 (range
1905 (range
1906 ('symbol', '0')
1906 ('symbol', '0')
1907 ('symbol', '1')
1907 ('symbol', '1')
1908 follow))
1908 follow))
1909 follow)
1909 follow)
1910 define)
1910 define)
1911 * set:
1911 * set:
1912 <filteredset
1912 <filteredset
1913 <spanset- 0:3>,
1913 <spanset- 0:3>,
1914 <addset
1914 <addset
1915 <baseset [2]>,
1915 <baseset [2]>,
1916 <spanset+ 0:2>>>
1916 <spanset+ 0:2>>>
1917 2
1917 2
1918 1
1918 1
1919 0
1919 0
1920
1920
1921 '_intlist(a b)' should behave like 'a + b':
1921 '_intlist(a b)' should behave like 'a + b':
1922
1922
1923 $ trylist --optimize '2:0 & %ld' 0 1 2
1923 $ trylist --optimize '2:0 & %ld' 0 1 2
1924 (and
1924 (and
1925 (range
1925 (range
1926 ('symbol', '2')
1926 ('symbol', '2')
1927 ('symbol', '0'))
1927 ('symbol', '0'))
1928 (func
1928 (func
1929 ('symbol', '_intlist')
1929 ('symbol', '_intlist')
1930 ('string', '0\x001\x002')))
1930 ('string', '0\x001\x002')))
1931 * optimized:
1931 * optimized:
1932 (and
1932 (and
1933 (func
1933 (func
1934 ('symbol', '_intlist')
1934 ('symbol', '_intlist')
1935 ('string', '0\x001\x002')
1935 ('string', '0\x001\x002')
1936 follow)
1936 follow)
1937 (range
1937 (range
1938 ('symbol', '2')
1938 ('symbol', '2')
1939 ('symbol', '0')
1939 ('symbol', '0')
1940 define)
1940 define)
1941 define)
1941 define)
1942 * set:
1942 * set:
1943 <filteredset
1943 <filteredset
1944 <spanset- 0:3>,
1944 <spanset- 0:3>,
1945 <baseset+ [0, 1, 2]>>
1945 <baseset+ [0, 1, 2]>>
1946 2
1946 2
1947 1
1947 1
1948 0
1948 0
1949
1949
1950 $ trylist --optimize '%ld & 2:0' 0 2 1
1950 $ trylist --optimize '%ld & 2:0' 0 2 1
1951 (and
1951 (and
1952 (func
1952 (func
1953 ('symbol', '_intlist')
1953 ('symbol', '_intlist')
1954 ('string', '0\x002\x001'))
1954 ('string', '0\x002\x001'))
1955 (range
1955 (range
1956 ('symbol', '2')
1956 ('symbol', '2')
1957 ('symbol', '0')))
1957 ('symbol', '0')))
1958 * optimized:
1958 * optimized:
1959 (and
1959 (and
1960 (func
1960 (func
1961 ('symbol', '_intlist')
1961 ('symbol', '_intlist')
1962 ('string', '0\x002\x001')
1962 ('string', '0\x002\x001')
1963 define)
1963 define)
1964 (range
1964 (range
1965 ('symbol', '2')
1965 ('symbol', '2')
1966 ('symbol', '0')
1966 ('symbol', '0')
1967 follow)
1967 follow)
1968 define)
1968 define)
1969 * set:
1969 * set:
1970 <filteredset
1970 <filteredset
1971 <baseset [0, 2, 1]>,
1971 <baseset [0, 2, 1]>,
1972 <spanset- 0:3>>
1972 <spanset- 0:3>>
1973 0
1973 0
1974 2
1974 2
1975 1
1975 1
1976
1976
1977 '_hexlist(a b)' should behave like 'a + b':
1977 '_hexlist(a b)' should behave like 'a + b':
1978
1978
1979 $ trylist --optimize --bin '2:0 & %ln' `hg log -T '{node} ' -r0:2`
1979 $ trylist --optimize --bin '2:0 & %ln' `hg log -T '{node} ' -r0:2`
1980 (and
1980 (and
1981 (range
1981 (range
1982 ('symbol', '2')
1982 ('symbol', '2')
1983 ('symbol', '0'))
1983 ('symbol', '0'))
1984 (func
1984 (func
1985 ('symbol', '_hexlist')
1985 ('symbol', '_hexlist')
1986 ('string', '*'))) (glob)
1986 ('string', '*'))) (glob)
1987 * optimized:
1987 * optimized:
1988 (and
1988 (and
1989 (range
1989 (range
1990 ('symbol', '2')
1990 ('symbol', '2')
1991 ('symbol', '0')
1991 ('symbol', '0')
1992 define)
1992 define)
1993 (func
1993 (func
1994 ('symbol', '_hexlist')
1994 ('symbol', '_hexlist')
1995 ('string', '*') (glob)
1995 ('string', '*') (glob)
1996 follow)
1996 follow)
1997 define)
1997 define)
1998 * set:
1998 * set:
1999 <filteredset
1999 <filteredset
2000 <spanset- 0:3>,
2000 <spanset- 0:3>,
2001 <baseset [0, 1, 2]>>
2001 <baseset [0, 1, 2]>>
2002 2
2002 2
2003 1
2003 1
2004 0
2004 0
2005
2005
2006 $ trylist --optimize --bin '%ln & 2:0' `hg log -T '{node} ' -r0+2+1`
2006 $ trylist --optimize --bin '%ln & 2:0' `hg log -T '{node} ' -r0+2+1`
2007 (and
2007 (and
2008 (func
2008 (func
2009 ('symbol', '_hexlist')
2009 ('symbol', '_hexlist')
2010 ('string', '*')) (glob)
2010 ('string', '*')) (glob)
2011 (range
2011 (range
2012 ('symbol', '2')
2012 ('symbol', '2')
2013 ('symbol', '0')))
2013 ('symbol', '0')))
2014 * optimized:
2014 * optimized:
2015 (and
2015 (and
2016 (range
2016 (range
2017 ('symbol', '2')
2017 ('symbol', '2')
2018 ('symbol', '0')
2018 ('symbol', '0')
2019 follow)
2019 follow)
2020 (func
2020 (func
2021 ('symbol', '_hexlist')
2021 ('symbol', '_hexlist')
2022 ('string', '*') (glob)
2022 ('string', '*') (glob)
2023 define)
2023 define)
2024 define)
2024 define)
2025 * set:
2025 * set:
2026 <baseset [0, 2, 1]>
2026 <baseset [0, 2, 1]>
2027 0
2027 0
2028 2
2028 2
2029 1
2029 1
2030
2030
2031 '_list' should not go through the slow follow-order path if order doesn't
2031 '_list' should not go through the slow follow-order path if order doesn't
2032 matter:
2032 matter:
2033
2033
2034 $ try -p optimized '2:0 & not (0 + 1)'
2034 $ try -p optimized '2:0 & not (0 + 1)'
2035 * optimized:
2035 * optimized:
2036 (difference
2036 (difference
2037 (range
2037 (range
2038 ('symbol', '2')
2038 ('symbol', '2')
2039 ('symbol', '0')
2039 ('symbol', '0')
2040 define)
2040 define)
2041 (func
2041 (func
2042 ('symbol', '_list')
2042 ('symbol', '_list')
2043 ('string', '0\x001')
2043 ('string', '0\x001')
2044 any)
2044 any)
2045 define)
2045 define)
2046 * set:
2046 * set:
2047 <filteredset
2047 <filteredset
2048 <spanset- 0:3>,
2048 <spanset- 0:3>,
2049 <not
2049 <not
2050 <baseset [0, 1]>>>
2050 <baseset [0, 1]>>>
2051 2
2051 2
2052
2052
2053 $ try -p optimized '2:0 & not (0:2 & (0 + 1))'
2053 $ try -p optimized '2:0 & not (0:2 & (0 + 1))'
2054 * optimized:
2054 * optimized:
2055 (difference
2055 (difference
2056 (range
2056 (range
2057 ('symbol', '2')
2057 ('symbol', '2')
2058 ('symbol', '0')
2058 ('symbol', '0')
2059 define)
2059 define)
2060 (and
2060 (and
2061 (range
2061 (range
2062 ('symbol', '0')
2062 ('symbol', '0')
2063 ('symbol', '2')
2063 ('symbol', '2')
2064 any)
2064 any)
2065 (func
2065 (func
2066 ('symbol', '_list')
2066 ('symbol', '_list')
2067 ('string', '0\x001')
2067 ('string', '0\x001')
2068 any)
2068 any)
2069 any)
2069 any)
2070 define)
2070 define)
2071 * set:
2071 * set:
2072 <filteredset
2072 <filteredset
2073 <spanset- 0:3>,
2073 <spanset- 0:3>,
2074 <not
2074 <not
2075 <baseset [0, 1]>>>
2075 <baseset [0, 1]>>>
2076 2
2076 2
2077
2077
2078 because 'present()' does nothing other than suppressing an error, the
2078 because 'present()' does nothing other than suppressing an error, the
2079 ordering requirement should be forwarded to the nested expression
2079 ordering requirement should be forwarded to the nested expression
2080
2080
2081 $ try -p optimized 'present(2 + 0 + 1)'
2081 $ try -p optimized 'present(2 + 0 + 1)'
2082 * optimized:
2082 * optimized:
2083 (func
2083 (func
2084 ('symbol', 'present')
2084 ('symbol', 'present')
2085 (func
2085 (func
2086 ('symbol', '_list')
2086 ('symbol', '_list')
2087 ('string', '2\x000\x001')
2087 ('string', '2\x000\x001')
2088 define)
2088 define)
2089 define)
2089 define)
2090 * set:
2090 * set:
2091 <baseset [2, 0, 1]>
2091 <baseset [2, 0, 1]>
2092 2
2092 2
2093 0
2093 0
2094 1
2094 1
2095
2095
2096 $ try --optimize '2:0 & present(0 + 1 + 2)'
2096 $ try --optimize '2:0 & present(0 + 1 + 2)'
2097 (and
2097 (and
2098 (range
2098 (range
2099 ('symbol', '2')
2099 ('symbol', '2')
2100 ('symbol', '0'))
2100 ('symbol', '0'))
2101 (func
2101 (func
2102 ('symbol', 'present')
2102 ('symbol', 'present')
2103 (or
2103 (or
2104 (list
2104 (list
2105 ('symbol', '0')
2105 ('symbol', '0')
2106 ('symbol', '1')
2106 ('symbol', '1')
2107 ('symbol', '2')))))
2107 ('symbol', '2')))))
2108 * optimized:
2108 * optimized:
2109 (and
2109 (and
2110 (range
2110 (range
2111 ('symbol', '2')
2111 ('symbol', '2')
2112 ('symbol', '0')
2112 ('symbol', '0')
2113 define)
2113 define)
2114 (func
2114 (func
2115 ('symbol', 'present')
2115 ('symbol', 'present')
2116 (func
2116 (func
2117 ('symbol', '_list')
2117 ('symbol', '_list')
2118 ('string', '0\x001\x002')
2118 ('string', '0\x001\x002')
2119 follow)
2119 follow)
2120 follow)
2120 follow)
2121 define)
2121 define)
2122 * set:
2122 * set:
2123 <filteredset
2123 <filteredset
2124 <spanset- 0:3>,
2124 <spanset- 0:3>,
2125 <baseset [0, 1, 2]>>
2125 <baseset [0, 1, 2]>>
2126 2
2126 2
2127 1
2127 1
2128 0
2128 0
2129
2129
2130 'reverse()' should take effect only if it is the outermost expression:
2130 'reverse()' should take effect only if it is the outermost expression:
2131
2131
2132 $ try --optimize '0:2 & reverse(all())'
2132 $ try --optimize '0:2 & reverse(all())'
2133 (and
2133 (and
2134 (range
2134 (range
2135 ('symbol', '0')
2135 ('symbol', '0')
2136 ('symbol', '2'))
2136 ('symbol', '2'))
2137 (func
2137 (func
2138 ('symbol', 'reverse')
2138 ('symbol', 'reverse')
2139 (func
2139 (func
2140 ('symbol', 'all')
2140 ('symbol', 'all')
2141 None)))
2141 None)))
2142 * optimized:
2142 * optimized:
2143 (and
2143 (and
2144 (range
2144 (range
2145 ('symbol', '0')
2145 ('symbol', '0')
2146 ('symbol', '2')
2146 ('symbol', '2')
2147 define)
2147 define)
2148 (func
2148 (func
2149 ('symbol', 'reverse')
2149 ('symbol', 'reverse')
2150 (func
2150 (func
2151 ('symbol', 'all')
2151 ('symbol', 'all')
2152 None
2152 None
2153 define)
2153 define)
2154 follow)
2154 follow)
2155 define)
2155 define)
2156 * set:
2156 * set:
2157 <filteredset
2157 <filteredset
2158 <spanset+ 0:3>,
2158 <spanset+ 0:3>,
2159 <spanset+ 0:10>>
2159 <spanset+ 0:10>>
2160 0
2160 0
2161 1
2161 1
2162 2
2162 2
2163
2163
2164 'sort()' should take effect only if it is the outermost expression:
2164 'sort()' should take effect only if it is the outermost expression:
2165
2165
2166 $ try --optimize '0:2 & sort(all(), -rev)'
2166 $ try --optimize '0:2 & sort(all(), -rev)'
2167 (and
2167 (and
2168 (range
2168 (range
2169 ('symbol', '0')
2169 ('symbol', '0')
2170 ('symbol', '2'))
2170 ('symbol', '2'))
2171 (func
2171 (func
2172 ('symbol', 'sort')
2172 ('symbol', 'sort')
2173 (list
2173 (list
2174 (func
2174 (func
2175 ('symbol', 'all')
2175 ('symbol', 'all')
2176 None)
2176 None)
2177 (negate
2177 (negate
2178 ('symbol', 'rev')))))
2178 ('symbol', 'rev')))))
2179 * optimized:
2179 * optimized:
2180 (and
2180 (and
2181 (range
2181 (range
2182 ('symbol', '0')
2182 ('symbol', '0')
2183 ('symbol', '2')
2183 ('symbol', '2')
2184 define)
2184 define)
2185 (func
2185 (func
2186 ('symbol', 'sort')
2186 ('symbol', 'sort')
2187 (list
2187 (list
2188 (func
2188 (func
2189 ('symbol', 'all')
2189 ('symbol', 'all')
2190 None
2190 None
2191 define)
2191 define)
2192 ('string', '-rev'))
2192 ('string', '-rev'))
2193 follow)
2193 follow)
2194 define)
2194 define)
2195 * set:
2195 * set:
2196 <filteredset
2196 <filteredset
2197 <spanset+ 0:3>,
2197 <spanset+ 0:3>,
2198 <spanset+ 0:10>>
2198 <spanset+ 0:10>>
2199 0
2199 0
2200 1
2200 1
2201 2
2201 2
2202
2202
2203 invalid argument passed to noop sort():
2203 invalid argument passed to noop sort():
2204
2204
2205 $ log '0:2 & sort()'
2205 $ log '0:2 & sort()'
2206 hg: parse error: sort requires one or two arguments
2206 hg: parse error: sort requires one or two arguments
2207 [255]
2207 [255]
2208 $ log '0:2 & sort(all(), -invalid)'
2208 $ log '0:2 & sort(all(), -invalid)'
2209 hg: parse error: unknown sort key '-invalid'
2209 hg: parse error: unknown sort key '-invalid'
2210 [255]
2210 [255]
2211
2211
2212 for 'A & f(B)', 'B' should not be affected by the order of 'A':
2212 for 'A & f(B)', 'B' should not be affected by the order of 'A':
2213
2213
2214 $ try --optimize '2:0 & first(1 + 0 + 2)'
2214 $ try --optimize '2:0 & first(1 + 0 + 2)'
2215 (and
2215 (and
2216 (range
2216 (range
2217 ('symbol', '2')
2217 ('symbol', '2')
2218 ('symbol', '0'))
2218 ('symbol', '0'))
2219 (func
2219 (func
2220 ('symbol', 'first')
2220 ('symbol', 'first')
2221 (or
2221 (or
2222 (list
2222 (list
2223 ('symbol', '1')
2223 ('symbol', '1')
2224 ('symbol', '0')
2224 ('symbol', '0')
2225 ('symbol', '2')))))
2225 ('symbol', '2')))))
2226 * optimized:
2226 * optimized:
2227 (and
2227 (and
2228 (range
2228 (range
2229 ('symbol', '2')
2229 ('symbol', '2')
2230 ('symbol', '0')
2230 ('symbol', '0')
2231 define)
2231 define)
2232 (func
2232 (func
2233 ('symbol', 'first')
2233 ('symbol', 'first')
2234 (func
2234 (func
2235 ('symbol', '_list')
2235 ('symbol', '_list')
2236 ('string', '1\x000\x002')
2236 ('string', '1\x000\x002')
2237 define)
2237 define)
2238 follow)
2238 follow)
2239 define)
2239 define)
2240 * set:
2240 * set:
2241 <filteredset
2241 <filteredset
2242 <baseset [1]>,
2242 <baseset [1]>,
2243 <spanset- 0:3>>
2243 <spanset- 0:3>>
2244 1
2244 1
2245
2245
2246 $ try --optimize '2:0 & not last(0 + 2 + 1)'
2246 $ try --optimize '2:0 & not last(0 + 2 + 1)'
2247 (and
2247 (and
2248 (range
2248 (range
2249 ('symbol', '2')
2249 ('symbol', '2')
2250 ('symbol', '0'))
2250 ('symbol', '0'))
2251 (not
2251 (not
2252 (func
2252 (func
2253 ('symbol', 'last')
2253 ('symbol', 'last')
2254 (or
2254 (or
2255 (list
2255 (list
2256 ('symbol', '0')
2256 ('symbol', '0')
2257 ('symbol', '2')
2257 ('symbol', '2')
2258 ('symbol', '1'))))))
2258 ('symbol', '1'))))))
2259 * optimized:
2259 * optimized:
2260 (difference
2260 (difference
2261 (range
2261 (range
2262 ('symbol', '2')
2262 ('symbol', '2')
2263 ('symbol', '0')
2263 ('symbol', '0')
2264 define)
2264 define)
2265 (func
2265 (func
2266 ('symbol', 'last')
2266 ('symbol', 'last')
2267 (func
2267 (func
2268 ('symbol', '_list')
2268 ('symbol', '_list')
2269 ('string', '0\x002\x001')
2269 ('string', '0\x002\x001')
2270 define)
2270 define)
2271 any)
2271 any)
2272 define)
2272 define)
2273 * set:
2273 * set:
2274 <filteredset
2274 <filteredset
2275 <spanset- 0:3>,
2275 <spanset- 0:3>,
2276 <not
2276 <not
2277 <baseset [1]>>>
2277 <baseset [1]>>>
2278 2
2278 2
2279 0
2279 0
2280
2280
2281 for 'A & (op)(B)', 'B' should not be affected by the order of 'A':
2281 for 'A & (op)(B)', 'B' should not be affected by the order of 'A':
2282
2282
2283 $ try --optimize '2:0 & (1 + 0 + 2):(0 + 2 + 1)'
2283 $ try --optimize '2:0 & (1 + 0 + 2):(0 + 2 + 1)'
2284 (and
2284 (and
2285 (range
2285 (range
2286 ('symbol', '2')
2286 ('symbol', '2')
2287 ('symbol', '0'))
2287 ('symbol', '0'))
2288 (range
2288 (range
2289 (group
2289 (group
2290 (or
2290 (or
2291 (list
2291 (list
2292 ('symbol', '1')
2292 ('symbol', '1')
2293 ('symbol', '0')
2293 ('symbol', '0')
2294 ('symbol', '2'))))
2294 ('symbol', '2'))))
2295 (group
2295 (group
2296 (or
2296 (or
2297 (list
2297 (list
2298 ('symbol', '0')
2298 ('symbol', '0')
2299 ('symbol', '2')
2299 ('symbol', '2')
2300 ('symbol', '1'))))))
2300 ('symbol', '1'))))))
2301 * optimized:
2301 * optimized:
2302 (and
2302 (and
2303 (range
2303 (range
2304 ('symbol', '2')
2304 ('symbol', '2')
2305 ('symbol', '0')
2305 ('symbol', '0')
2306 define)
2306 define)
2307 (range
2307 (range
2308 (func
2308 (func
2309 ('symbol', '_list')
2309 ('symbol', '_list')
2310 ('string', '1\x000\x002')
2310 ('string', '1\x000\x002')
2311 define)
2311 define)
2312 (func
2312 (func
2313 ('symbol', '_list')
2313 ('symbol', '_list')
2314 ('string', '0\x002\x001')
2314 ('string', '0\x002\x001')
2315 define)
2315 define)
2316 follow)
2316 follow)
2317 define)
2317 define)
2318 * set:
2318 * set:
2319 <filteredset
2319 <filteredset
2320 <spanset- 0:3>,
2320 <spanset- 0:3>,
2321 <baseset [1]>>
2321 <baseset [1]>>
2322 1
2322 1
2323
2323
2324 'A & B' can be rewritten as 'B & A' by weight, but that's fine as long as
2324 'A & B' can be rewritten as 'B & A' by weight, but that's fine as long as
2325 the ordering rule is determined before the rewrite; in this example,
2325 the ordering rule is determined before the rewrite; in this example,
2326 'B' follows the order of the initial set, which is the same order as 'A'
2326 'B' follows the order of the initial set, which is the same order as 'A'
2327 since 'A' also follows the order:
2327 since 'A' also follows the order:
2328
2328
2329 $ try --optimize 'contains("glob:*") & (2 + 0 + 1)'
2329 $ try --optimize 'contains("glob:*") & (2 + 0 + 1)'
2330 (and
2330 (and
2331 (func
2331 (func
2332 ('symbol', 'contains')
2332 ('symbol', 'contains')
2333 ('string', 'glob:*'))
2333 ('string', 'glob:*'))
2334 (group
2334 (group
2335 (or
2335 (or
2336 (list
2336 (list
2337 ('symbol', '2')
2337 ('symbol', '2')
2338 ('symbol', '0')
2338 ('symbol', '0')
2339 ('symbol', '1')))))
2339 ('symbol', '1')))))
2340 * optimized:
2340 * optimized:
2341 (and
2341 (and
2342 (func
2342 (func
2343 ('symbol', '_list')
2343 ('symbol', '_list')
2344 ('string', '2\x000\x001')
2344 ('string', '2\x000\x001')
2345 follow)
2345 follow)
2346 (func
2346 (func
2347 ('symbol', 'contains')
2347 ('symbol', 'contains')
2348 ('string', 'glob:*')
2348 ('string', 'glob:*')
2349 define)
2349 define)
2350 define)
2350 define)
2351 * set:
2351 * set:
2352 <filteredset
2352 <filteredset
2353 <baseset+ [0, 1, 2]>,
2353 <baseset+ [0, 1, 2]>,
2354 <contains 'glob:*'>>
2354 <contains 'glob:*'>>
2355 0
2355 0
2356 1
2356 1
2357 2
2357 2
2358
2358
2359 and in this example, 'A & B' is rewritten as 'B & A', but 'A' overrides
2359 and in this example, 'A & B' is rewritten as 'B & A', but 'A' overrides
2360 the order appropriately:
2360 the order appropriately:
2361
2361
2362 $ try --optimize 'reverse(contains("glob:*")) & (0 + 2 + 1)'
2362 $ try --optimize 'reverse(contains("glob:*")) & (0 + 2 + 1)'
2363 (and
2363 (and
2364 (func
2364 (func
2365 ('symbol', 'reverse')
2365 ('symbol', 'reverse')
2366 (func
2366 (func
2367 ('symbol', 'contains')
2367 ('symbol', 'contains')
2368 ('string', 'glob:*')))
2368 ('string', 'glob:*')))
2369 (group
2369 (group
2370 (or
2370 (or
2371 (list
2371 (list
2372 ('symbol', '0')
2372 ('symbol', '0')
2373 ('symbol', '2')
2373 ('symbol', '2')
2374 ('symbol', '1')))))
2374 ('symbol', '1')))))
2375 * optimized:
2375 * optimized:
2376 (and
2376 (and
2377 (func
2377 (func
2378 ('symbol', '_list')
2378 ('symbol', '_list')
2379 ('string', '0\x002\x001')
2379 ('string', '0\x002\x001')
2380 follow)
2380 follow)
2381 (func
2381 (func
2382 ('symbol', 'reverse')
2382 ('symbol', 'reverse')
2383 (func
2383 (func
2384 ('symbol', 'contains')
2384 ('symbol', 'contains')
2385 ('string', 'glob:*')
2385 ('string', 'glob:*')
2386 define)
2386 define)
2387 define)
2387 define)
2388 define)
2388 define)
2389 * set:
2389 * set:
2390 <filteredset
2390 <filteredset
2391 <baseset- [0, 1, 2]>,
2391 <baseset- [0, 1, 2]>,
2392 <contains 'glob:*'>>
2392 <contains 'glob:*'>>
2393 2
2393 2
2394 1
2394 1
2395 0
2395 0
2396
2396
2397 'A + B' can be rewritten to 'B + A' by weight only when the order doesn't
2397 'A + B' can be rewritten to 'B + A' by weight only when the order doesn't
2398 matter (e.g. 'X & (A + B)' can be 'X & (B + A)', but '(A + B) & X' can't):
2398 matter (e.g. 'X & (A + B)' can be 'X & (B + A)', but '(A + B) & X' can't):
2399
2399
2400 $ try -p optimized '0:2 & (reverse(contains("a")) + 2)'
2400 $ try -p optimized '0:2 & (reverse(contains("a")) + 2)'
2401 * optimized:
2401 * optimized:
2402 (and
2402 (and
2403 (range
2403 (range
2404 ('symbol', '0')
2404 ('symbol', '0')
2405 ('symbol', '2')
2405 ('symbol', '2')
2406 define)
2406 define)
2407 (or
2407 (or
2408 (list
2408 (list
2409 ('symbol', '2')
2409 ('symbol', '2')
2410 (func
2410 (func
2411 ('symbol', 'reverse')
2411 ('symbol', 'reverse')
2412 (func
2412 (func
2413 ('symbol', 'contains')
2413 ('symbol', 'contains')
2414 ('string', 'a')
2414 ('string', 'a')
2415 define)
2415 define)
2416 follow))
2416 follow))
2417 follow)
2417 follow)
2418 define)
2418 define)
2419 * set:
2419 * set:
2420 <filteredset
2420 <filteredset
2421 <spanset+ 0:3>,
2421 <spanset+ 0:3>,
2422 <addset
2422 <addset
2423 <baseset [2]>,
2423 <baseset [2]>,
2424 <filteredset
2424 <filteredset
2425 <fullreposet+ 0:10>,
2425 <fullreposet+ 0:10>,
2426 <contains 'a'>>>>
2426 <contains 'a'>>>>
2427 0
2427 0
2428 1
2428 1
2429 2
2429 2
2430
2430
2431 $ try -p optimized '(reverse(contains("a")) + 2) & 0:2'
2431 $ try -p optimized '(reverse(contains("a")) + 2) & 0:2'
2432 * optimized:
2432 * optimized:
2433 (and
2433 (and
2434 (range
2434 (range
2435 ('symbol', '0')
2435 ('symbol', '0')
2436 ('symbol', '2')
2436 ('symbol', '2')
2437 follow)
2437 follow)
2438 (or
2438 (or
2439 (list
2439 (list
2440 (func
2440 (func
2441 ('symbol', 'reverse')
2441 ('symbol', 'reverse')
2442 (func
2442 (func
2443 ('symbol', 'contains')
2443 ('symbol', 'contains')
2444 ('string', 'a')
2444 ('string', 'a')
2445 define)
2445 define)
2446 define)
2446 define)
2447 ('symbol', '2'))
2447 ('symbol', '2'))
2448 define)
2448 define)
2449 define)
2449 define)
2450 * set:
2450 * set:
2451 <addset
2451 <addset
2452 <filteredset
2452 <filteredset
2453 <spanset- 0:3>,
2453 <spanset- 0:3>,
2454 <contains 'a'>>,
2454 <contains 'a'>>,
2455 <baseset [2]>>
2455 <baseset [2]>>
2456 1
2456 1
2457 0
2457 0
2458 2
2458 2
2459
2459
2460 test sort revset
2460 test sort revset
2461 --------------------------------------------
2461 --------------------------------------------
2462
2462
2463 test when adding two unordered revsets
2463 test when adding two unordered revsets
2464
2464
2465 $ log 'sort(keyword(issue) or modifies(b))'
2465 $ log 'sort(keyword(issue) or modifies(b))'
2466 4
2466 4
2467 6
2467 6
2468
2468
2469 test when sorting a reversed collection in the same way it is
2469 test when sorting a reversed collection in the same way it is
2470
2470
2471 $ log 'sort(reverse(all()), -rev)'
2471 $ log 'sort(reverse(all()), -rev)'
2472 9
2472 9
2473 8
2473 8
2474 7
2474 7
2475 6
2475 6
2476 5
2476 5
2477 4
2477 4
2478 3
2478 3
2479 2
2479 2
2480 1
2480 1
2481 0
2481 0
2482
2482
2483 test when sorting a reversed collection
2483 test when sorting a reversed collection
2484
2484
2485 $ log 'sort(reverse(all()), rev)'
2485 $ log 'sort(reverse(all()), rev)'
2486 0
2486 0
2487 1
2487 1
2488 2
2488 2
2489 3
2489 3
2490 4
2490 4
2491 5
2491 5
2492 6
2492 6
2493 7
2493 7
2494 8
2494 8
2495 9
2495 9
2496
2496
2497
2497
2498 test sorting two sorted collections in different orders
2498 test sorting two sorted collections in different orders
2499
2499
2500 $ log 'sort(outgoing() or reverse(removes(a)), rev)'
2500 $ log 'sort(outgoing() or reverse(removes(a)), rev)'
2501 2
2501 2
2502 6
2502 6
2503 8
2503 8
2504 9
2504 9
2505
2505
2506 test sorting two sorted collections in different orders backwards
2506 test sorting two sorted collections in different orders backwards
2507
2507
2508 $ log 'sort(outgoing() or reverse(removes(a)), -rev)'
2508 $ log 'sort(outgoing() or reverse(removes(a)), -rev)'
2509 9
2509 9
2510 8
2510 8
2511 6
2511 6
2512 2
2512 2
2513
2513
2514 test empty sort key which is noop
2514 test empty sort key which is noop
2515
2515
2516 $ log 'sort(0 + 2 + 1, "")'
2516 $ log 'sort(0 + 2 + 1, "")'
2517 0
2517 0
2518 2
2518 2
2519 1
2519 1
2520
2520
2521 test invalid sort keys
2521 test invalid sort keys
2522
2522
2523 $ log 'sort(all(), -invalid)'
2523 $ log 'sort(all(), -invalid)'
2524 hg: parse error: unknown sort key '-invalid'
2524 hg: parse error: unknown sort key '-invalid'
2525 [255]
2525 [255]
2526
2526
2527 $ cd ..
2527 $ cd ..
2528
2528
2529 test sorting by multiple keys including variable-length strings
2529 test sorting by multiple keys including variable-length strings
2530
2530
2531 $ hg init sorting
2531 $ hg init sorting
2532 $ cd sorting
2532 $ cd sorting
2533 $ cat <<EOF >> .hg/hgrc
2533 $ cat <<EOF >> .hg/hgrc
2534 > [ui]
2534 > [ui]
2535 > logtemplate = '{rev} {branch|p5}{desc|p5}{author|p5}{date|hgdate}\n'
2535 > logtemplate = '{rev} {branch|p5}{desc|p5}{author|p5}{date|hgdate}\n'
2536 > [templatealias]
2536 > [templatealias]
2537 > p5(s) = pad(s, 5)
2537 > p5(s) = pad(s, 5)
2538 > EOF
2538 > EOF
2539 $ hg branch -qf b12
2539 $ hg branch -qf b12
2540 $ hg ci -m m111 -u u112 -d '111 10800'
2540 $ hg ci -m m111 -u u112 -d '111 10800'
2541 $ hg branch -qf b11
2541 $ hg branch -qf b11
2542 $ hg ci -m m12 -u u111 -d '112 7200'
2542 $ hg ci -m m12 -u u111 -d '112 7200'
2543 $ hg branch -qf b111
2543 $ hg branch -qf b111
2544 $ hg ci -m m11 -u u12 -d '111 3600'
2544 $ hg ci -m m11 -u u12 -d '111 3600'
2545 $ hg branch -qf b112
2545 $ hg branch -qf b112
2546 $ hg ci -m m111 -u u11 -d '120 0'
2546 $ hg ci -m m111 -u u11 -d '120 0'
2547 $ hg branch -qf b111
2547 $ hg branch -qf b111
2548 $ hg ci -m m112 -u u111 -d '110 14400'
2548 $ hg ci -m m112 -u u111 -d '110 14400'
2549 created new head
2549 created new head
2550
2550
2551 compare revisions (has fast path):
2551 compare revisions (has fast path):
2552
2552
2553 $ hg log -r 'sort(all(), rev)'
2553 $ hg log -r 'sort(all(), rev)'
2554 0 b12 m111 u112 111 10800
2554 0 b12 m111 u112 111 10800
2555 1 b11 m12 u111 112 7200
2555 1 b11 m12 u111 112 7200
2556 2 b111 m11 u12 111 3600
2556 2 b111 m11 u12 111 3600
2557 3 b112 m111 u11 120 0
2557 3 b112 m111 u11 120 0
2558 4 b111 m112 u111 110 14400
2558 4 b111 m112 u111 110 14400
2559
2559
2560 $ hg log -r 'sort(all(), -rev)'
2560 $ hg log -r 'sort(all(), -rev)'
2561 4 b111 m112 u111 110 14400
2561 4 b111 m112 u111 110 14400
2562 3 b112 m111 u11 120 0
2562 3 b112 m111 u11 120 0
2563 2 b111 m11 u12 111 3600
2563 2 b111 m11 u12 111 3600
2564 1 b11 m12 u111 112 7200
2564 1 b11 m12 u111 112 7200
2565 0 b12 m111 u112 111 10800
2565 0 b12 m111 u112 111 10800
2566
2566
2567 compare variable-length strings (issue5218):
2567 compare variable-length strings (issue5218):
2568
2568
2569 $ hg log -r 'sort(all(), branch)'
2569 $ hg log -r 'sort(all(), branch)'
2570 1 b11 m12 u111 112 7200
2570 1 b11 m12 u111 112 7200
2571 2 b111 m11 u12 111 3600
2571 2 b111 m11 u12 111 3600
2572 4 b111 m112 u111 110 14400
2572 4 b111 m112 u111 110 14400
2573 3 b112 m111 u11 120 0
2573 3 b112 m111 u11 120 0
2574 0 b12 m111 u112 111 10800
2574 0 b12 m111 u112 111 10800
2575
2575
2576 $ hg log -r 'sort(all(), -branch)'
2576 $ hg log -r 'sort(all(), -branch)'
2577 0 b12 m111 u112 111 10800
2577 0 b12 m111 u112 111 10800
2578 3 b112 m111 u11 120 0
2578 3 b112 m111 u11 120 0
2579 2 b111 m11 u12 111 3600
2579 2 b111 m11 u12 111 3600
2580 4 b111 m112 u111 110 14400
2580 4 b111 m112 u111 110 14400
2581 1 b11 m12 u111 112 7200
2581 1 b11 m12 u111 112 7200
2582
2582
2583 $ hg log -r 'sort(all(), desc)'
2583 $ hg log -r 'sort(all(), desc)'
2584 2 b111 m11 u12 111 3600
2584 2 b111 m11 u12 111 3600
2585 0 b12 m111 u112 111 10800
2585 0 b12 m111 u112 111 10800
2586 3 b112 m111 u11 120 0
2586 3 b112 m111 u11 120 0
2587 4 b111 m112 u111 110 14400
2587 4 b111 m112 u111 110 14400
2588 1 b11 m12 u111 112 7200
2588 1 b11 m12 u111 112 7200
2589
2589
2590 $ hg log -r 'sort(all(), -desc)'
2590 $ hg log -r 'sort(all(), -desc)'
2591 1 b11 m12 u111 112 7200
2591 1 b11 m12 u111 112 7200
2592 4 b111 m112 u111 110 14400
2592 4 b111 m112 u111 110 14400
2593 0 b12 m111 u112 111 10800
2593 0 b12 m111 u112 111 10800
2594 3 b112 m111 u11 120 0
2594 3 b112 m111 u11 120 0
2595 2 b111 m11 u12 111 3600
2595 2 b111 m11 u12 111 3600
2596
2596
2597 $ hg log -r 'sort(all(), user)'
2597 $ hg log -r 'sort(all(), user)'
2598 3 b112 m111 u11 120 0
2598 3 b112 m111 u11 120 0
2599 1 b11 m12 u111 112 7200
2599 1 b11 m12 u111 112 7200
2600 4 b111 m112 u111 110 14400
2600 4 b111 m112 u111 110 14400
2601 0 b12 m111 u112 111 10800
2601 0 b12 m111 u112 111 10800
2602 2 b111 m11 u12 111 3600
2602 2 b111 m11 u12 111 3600
2603
2603
2604 $ hg log -r 'sort(all(), -user)'
2604 $ hg log -r 'sort(all(), -user)'
2605 2 b111 m11 u12 111 3600
2605 2 b111 m11 u12 111 3600
2606 0 b12 m111 u112 111 10800
2606 0 b12 m111 u112 111 10800
2607 1 b11 m12 u111 112 7200
2607 1 b11 m12 u111 112 7200
2608 4 b111 m112 u111 110 14400
2608 4 b111 m112 u111 110 14400
2609 3 b112 m111 u11 120 0
2609 3 b112 m111 u11 120 0
2610
2610
2611 compare dates (tz offset should have no effect):
2611 compare dates (tz offset should have no effect):
2612
2612
2613 $ hg log -r 'sort(all(), date)'
2613 $ hg log -r 'sort(all(), date)'
2614 4 b111 m112 u111 110 14400
2614 4 b111 m112 u111 110 14400
2615 0 b12 m111 u112 111 10800
2615 0 b12 m111 u112 111 10800
2616 2 b111 m11 u12 111 3600
2616 2 b111 m11 u12 111 3600
2617 1 b11 m12 u111 112 7200
2617 1 b11 m12 u111 112 7200
2618 3 b112 m111 u11 120 0
2618 3 b112 m111 u11 120 0
2619
2619
2620 $ hg log -r 'sort(all(), -date)'
2620 $ hg log -r 'sort(all(), -date)'
2621 3 b112 m111 u11 120 0
2621 3 b112 m111 u11 120 0
2622 1 b11 m12 u111 112 7200
2622 1 b11 m12 u111 112 7200
2623 0 b12 m111 u112 111 10800
2623 0 b12 m111 u112 111 10800
2624 2 b111 m11 u12 111 3600
2624 2 b111 m11 u12 111 3600
2625 4 b111 m112 u111 110 14400
2625 4 b111 m112 u111 110 14400
2626
2626
2627 be aware that 'sort(x, -k)' is not exactly the same as 'reverse(sort(x, k))'
2627 be aware that 'sort(x, -k)' is not exactly the same as 'reverse(sort(x, k))'
2628 because '-k' reverses the comparison, not the list itself:
2628 because '-k' reverses the comparison, not the list itself:
2629
2629
2630 $ hg log -r 'sort(0 + 2, date)'
2630 $ hg log -r 'sort(0 + 2, date)'
2631 0 b12 m111 u112 111 10800
2631 0 b12 m111 u112 111 10800
2632 2 b111 m11 u12 111 3600
2632 2 b111 m11 u12 111 3600
2633
2633
2634 $ hg log -r 'sort(0 + 2, -date)'
2634 $ hg log -r 'sort(0 + 2, -date)'
2635 0 b12 m111 u112 111 10800
2635 0 b12 m111 u112 111 10800
2636 2 b111 m11 u12 111 3600
2636 2 b111 m11 u12 111 3600
2637
2637
2638 $ hg log -r 'reverse(sort(0 + 2, date))'
2638 $ hg log -r 'reverse(sort(0 + 2, date))'
2639 2 b111 m11 u12 111 3600
2639 2 b111 m11 u12 111 3600
2640 0 b12 m111 u112 111 10800
2640 0 b12 m111 u112 111 10800
2641
2641
2642 sort by multiple keys:
2642 sort by multiple keys:
2643
2643
2644 $ hg log -r 'sort(all(), "branch -rev")'
2644 $ hg log -r 'sort(all(), "branch -rev")'
2645 1 b11 m12 u111 112 7200
2645 1 b11 m12 u111 112 7200
2646 4 b111 m112 u111 110 14400
2646 4 b111 m112 u111 110 14400
2647 2 b111 m11 u12 111 3600
2647 2 b111 m11 u12 111 3600
2648 3 b112 m111 u11 120 0
2648 3 b112 m111 u11 120 0
2649 0 b12 m111 u112 111 10800
2649 0 b12 m111 u112 111 10800
2650
2650
2651 $ hg log -r 'sort(all(), "-desc -date")'
2651 $ hg log -r 'sort(all(), "-desc -date")'
2652 1 b11 m12 u111 112 7200
2652 1 b11 m12 u111 112 7200
2653 4 b111 m112 u111 110 14400
2653 4 b111 m112 u111 110 14400
2654 3 b112 m111 u11 120 0
2654 3 b112 m111 u11 120 0
2655 0 b12 m111 u112 111 10800
2655 0 b12 m111 u112 111 10800
2656 2 b111 m11 u12 111 3600
2656 2 b111 m11 u12 111 3600
2657
2657
2658 $ hg log -r 'sort(all(), "user -branch date rev")'
2658 $ hg log -r 'sort(all(), "user -branch date rev")'
2659 3 b112 m111 u11 120 0
2659 3 b112 m111 u11 120 0
2660 4 b111 m112 u111 110 14400
2660 4 b111 m112 u111 110 14400
2661 1 b11 m12 u111 112 7200
2661 1 b11 m12 u111 112 7200
2662 0 b12 m111 u112 111 10800
2662 0 b12 m111 u112 111 10800
2663 2 b111 m11 u12 111 3600
2663 2 b111 m11 u12 111 3600
2664
2664
2665 toposort prioritises graph branches
2665 toposort prioritises graph branches
2666
2666
2667 $ hg up 2
2667 $ hg up 2
2668 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
2668 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
2669 $ touch a
2669 $ touch a
2670 $ hg addremove
2670 $ hg addremove
2671 adding a
2671 adding a
2672 $ hg ci -m 't1' -u 'tu' -d '130 0'
2672 $ hg ci -m 't1' -u 'tu' -d '130 0'
2673 created new head
2673 created new head
2674 $ echo 'a' >> a
2674 $ echo 'a' >> a
2675 $ hg ci -m 't2' -u 'tu' -d '130 0'
2675 $ hg ci -m 't2' -u 'tu' -d '130 0'
2676 $ hg book book1
2676 $ hg book book1
2677 $ hg up 4
2677 $ hg up 4
2678 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
2678 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
2679 (leaving bookmark book1)
2679 (leaving bookmark book1)
2680 $ touch a
2680 $ touch a
2681 $ hg addremove
2681 $ hg addremove
2682 adding a
2682 adding a
2683 $ hg ci -m 't3' -u 'tu' -d '130 0'
2683 $ hg ci -m 't3' -u 'tu' -d '130 0'
2684
2684
2685 $ hg log -r 'sort(all(), topo)'
2685 $ hg log -r 'sort(all(), topo)'
2686 7 b111 t3 tu 130 0
2686 7 b111 t3 tu 130 0
2687 4 b111 m112 u111 110 14400
2687 4 b111 m112 u111 110 14400
2688 3 b112 m111 u11 120 0
2688 3 b112 m111 u11 120 0
2689 6 b111 t2 tu 130 0
2689 6 b111 t2 tu 130 0
2690 5 b111 t1 tu 130 0
2690 5 b111 t1 tu 130 0
2691 2 b111 m11 u12 111 3600
2691 2 b111 m11 u12 111 3600
2692 1 b11 m12 u111 112 7200
2692 1 b11 m12 u111 112 7200
2693 0 b12 m111 u112 111 10800
2693 0 b12 m111 u112 111 10800
2694
2694
2695 $ hg log -r 'sort(all(), -topo)'
2695 $ hg log -r 'sort(all(), -topo)'
2696 0 b12 m111 u112 111 10800
2696 0 b12 m111 u112 111 10800
2697 1 b11 m12 u111 112 7200
2697 1 b11 m12 u111 112 7200
2698 2 b111 m11 u12 111 3600
2698 2 b111 m11 u12 111 3600
2699 5 b111 t1 tu 130 0
2699 5 b111 t1 tu 130 0
2700 6 b111 t2 tu 130 0
2700 6 b111 t2 tu 130 0
2701 3 b112 m111 u11 120 0
2701 3 b112 m111 u11 120 0
2702 4 b111 m112 u111 110 14400
2702 4 b111 m112 u111 110 14400
2703 7 b111 t3 tu 130 0
2703 7 b111 t3 tu 130 0
2704
2704
2705 $ hg log -r 'sort(all(), topo, topo.firstbranch=book1)'
2705 $ hg log -r 'sort(all(), topo, topo.firstbranch=book1)'
2706 6 b111 t2 tu 130 0
2706 6 b111 t2 tu 130 0
2707 5 b111 t1 tu 130 0
2707 5 b111 t1 tu 130 0
2708 7 b111 t3 tu 130 0
2708 7 b111 t3 tu 130 0
2709 4 b111 m112 u111 110 14400
2709 4 b111 m112 u111 110 14400
2710 3 b112 m111 u11 120 0
2710 3 b112 m111 u11 120 0
2711 2 b111 m11 u12 111 3600
2711 2 b111 m11 u12 111 3600
2712 1 b11 m12 u111 112 7200
2712 1 b11 m12 u111 112 7200
2713 0 b12 m111 u112 111 10800
2713 0 b12 m111 u112 111 10800
2714
2714
2715 topographical sorting can't be combined with other sort keys, and you can't
2715 topographical sorting can't be combined with other sort keys, and you can't
2716 use the topo.firstbranch option when topo sort is not active:
2716 use the topo.firstbranch option when topo sort is not active:
2717
2717
2718 $ hg log -r 'sort(all(), "topo user")'
2718 $ hg log -r 'sort(all(), "topo user")'
2719 hg: parse error: topo sort order cannot be combined with other sort keys
2719 hg: parse error: topo sort order cannot be combined with other sort keys
2720 [255]
2720 [255]
2721
2721
2722 $ hg log -r 'sort(all(), user, topo.firstbranch=book1)'
2722 $ hg log -r 'sort(all(), user, topo.firstbranch=book1)'
2723 hg: parse error: topo.firstbranch can only be used when using the topo sort key
2723 hg: parse error: topo.firstbranch can only be used when using the topo sort key
2724 [255]
2724 [255]
2725
2725
2726 topo.firstbranch should accept any kind of expressions:
2726 topo.firstbranch should accept any kind of expressions:
2727
2727
2728 $ hg log -r 'sort(0, topo, topo.firstbranch=(book1))'
2728 $ hg log -r 'sort(0, topo, topo.firstbranch=(book1))'
2729 0 b12 m111 u112 111 10800
2729 0 b12 m111 u112 111 10800
2730
2730
2731 $ cd ..
2731 $ cd ..
2732 $ cd repo
2732 $ cd repo
2733
2733
2734 test subtracting something from an addset
2734 test subtracting something from an addset
2735
2735
2736 $ log '(outgoing() or removes(a)) - removes(a)'
2736 $ log '(outgoing() or removes(a)) - removes(a)'
2737 8
2737 8
2738 9
2738 9
2739
2739
2740 test intersecting something with an addset
2740 test intersecting something with an addset
2741
2741
2742 $ log 'parents(outgoing() or removes(a))'
2742 $ log 'parents(outgoing() or removes(a))'
2743 1
2743 1
2744 4
2744 4
2745 5
2745 5
2746 8
2746 8
2747
2747
2748 test that `or` operation combines elements in the right order:
2748 test that `or` operation combines elements in the right order:
2749
2749
2750 $ log '3:4 or 2:5'
2750 $ log '3:4 or 2:5'
2751 3
2751 3
2752 4
2752 4
2753 2
2753 2
2754 5
2754 5
2755 $ log '3:4 or 5:2'
2755 $ log '3:4 or 5:2'
2756 3
2756 3
2757 4
2757 4
2758 5
2758 5
2759 2
2759 2
2760 $ log 'sort(3:4 or 2:5)'
2760 $ log 'sort(3:4 or 2:5)'
2761 2
2761 2
2762 3
2762 3
2763 4
2763 4
2764 5
2764 5
2765 $ log 'sort(3:4 or 5:2)'
2765 $ log 'sort(3:4 or 5:2)'
2766 2
2766 2
2767 3
2767 3
2768 4
2768 4
2769 5
2769 5
2770
2770
2771 test that more than one `-r`s are combined in the right order and deduplicated:
2771 test that more than one `-r`s are combined in the right order and deduplicated:
2772
2772
2773 $ hg log -T '{rev}\n' -r 3 -r 3 -r 4 -r 5:2 -r 'ancestors(4)'
2773 $ hg log -T '{rev}\n' -r 3 -r 3 -r 4 -r 5:2 -r 'ancestors(4)'
2774 3
2774 3
2775 4
2775 4
2776 5
2776 5
2777 2
2777 2
2778 0
2778 0
2779 1
2779 1
2780
2780
2781 test that `or` operation skips duplicated revisions from right-hand side
2781 test that `or` operation skips duplicated revisions from right-hand side
2782
2782
2783 $ try 'reverse(1::5) or ancestors(4)'
2783 $ try 'reverse(1::5) or ancestors(4)'
2784 (or
2784 (or
2785 (list
2785 (list
2786 (func
2786 (func
2787 ('symbol', 'reverse')
2787 ('symbol', 'reverse')
2788 (dagrange
2788 (dagrange
2789 ('symbol', '1')
2789 ('symbol', '1')
2790 ('symbol', '5')))
2790 ('symbol', '5')))
2791 (func
2791 (func
2792 ('symbol', 'ancestors')
2792 ('symbol', 'ancestors')
2793 ('symbol', '4'))))
2793 ('symbol', '4'))))
2794 * set:
2794 * set:
2795 <addset
2795 <addset
2796 <baseset- [1, 3, 5]>,
2796 <baseset- [1, 3, 5]>,
2797 <generatorset+>>
2797 <generatorset+>>
2798 5
2798 5
2799 3
2799 3
2800 1
2800 1
2801 0
2801 0
2802 2
2802 2
2803 4
2803 4
2804 $ try 'sort(ancestors(4) or reverse(1::5))'
2804 $ try 'sort(ancestors(4) or reverse(1::5))'
2805 (func
2805 (func
2806 ('symbol', 'sort')
2806 ('symbol', 'sort')
2807 (or
2807 (or
2808 (list
2808 (list
2809 (func
2809 (func
2810 ('symbol', 'ancestors')
2810 ('symbol', 'ancestors')
2811 ('symbol', '4'))
2811 ('symbol', '4'))
2812 (func
2812 (func
2813 ('symbol', 'reverse')
2813 ('symbol', 'reverse')
2814 (dagrange
2814 (dagrange
2815 ('symbol', '1')
2815 ('symbol', '1')
2816 ('symbol', '5'))))))
2816 ('symbol', '5'))))))
2817 * set:
2817 * set:
2818 <addset+
2818 <addset+
2819 <generatorset+>,
2819 <generatorset+>,
2820 <baseset- [1, 3, 5]>>
2820 <baseset- [1, 3, 5]>>
2821 0
2821 0
2822 1
2822 1
2823 2
2823 2
2824 3
2824 3
2825 4
2825 4
2826 5
2826 5
2827
2827
2828 test optimization of trivial `or` operation
2828 test optimization of trivial `or` operation
2829
2829
2830 $ try --optimize '0|(1)|"2"|-2|tip|null'
2830 $ try --optimize '0|(1)|"2"|-2|tip|null'
2831 (or
2831 (or
2832 (list
2832 (list
2833 ('symbol', '0')
2833 ('symbol', '0')
2834 (group
2834 (group
2835 ('symbol', '1'))
2835 ('symbol', '1'))
2836 ('string', '2')
2836 ('string', '2')
2837 (negate
2837 (negate
2838 ('symbol', '2'))
2838 ('symbol', '2'))
2839 ('symbol', 'tip')
2839 ('symbol', 'tip')
2840 ('symbol', 'null')))
2840 ('symbol', 'null')))
2841 * optimized:
2841 * optimized:
2842 (func
2842 (func
2843 ('symbol', '_list')
2843 ('symbol', '_list')
2844 ('string', '0\x001\x002\x00-2\x00tip\x00null')
2844 ('string', '0\x001\x002\x00-2\x00tip\x00null')
2845 define)
2845 define)
2846 * set:
2846 * set:
2847 <baseset [0, 1, 2, 8, 9, -1]>
2847 <baseset [0, 1, 2, 8, 9, -1]>
2848 0
2848 0
2849 1
2849 1
2850 2
2850 2
2851 8
2851 8
2852 9
2852 9
2853 -1
2853 -1
2854
2854
2855 $ try --optimize '0|1|2:3'
2855 $ try --optimize '0|1|2:3'
2856 (or
2856 (or
2857 (list
2857 (list
2858 ('symbol', '0')
2858 ('symbol', '0')
2859 ('symbol', '1')
2859 ('symbol', '1')
2860 (range
2860 (range
2861 ('symbol', '2')
2861 ('symbol', '2')
2862 ('symbol', '3'))))
2862 ('symbol', '3'))))
2863 * optimized:
2863 * optimized:
2864 (or
2864 (or
2865 (list
2865 (list
2866 (func
2866 (func
2867 ('symbol', '_list')
2867 ('symbol', '_list')
2868 ('string', '0\x001')
2868 ('string', '0\x001')
2869 define)
2869 define)
2870 (range
2870 (range
2871 ('symbol', '2')
2871 ('symbol', '2')
2872 ('symbol', '3')
2872 ('symbol', '3')
2873 define))
2873 define))
2874 define)
2874 define)
2875 * set:
2875 * set:
2876 <addset
2876 <addset
2877 <baseset [0, 1]>,
2877 <baseset [0, 1]>,
2878 <spanset+ 2:4>>
2878 <spanset+ 2:4>>
2879 0
2879 0
2880 1
2880 1
2881 2
2881 2
2882 3
2882 3
2883
2883
2884 $ try --optimize '0:1|2|3:4|5|6'
2884 $ try --optimize '0:1|2|3:4|5|6'
2885 (or
2885 (or
2886 (list
2886 (list
2887 (range
2887 (range
2888 ('symbol', '0')
2888 ('symbol', '0')
2889 ('symbol', '1'))
2889 ('symbol', '1'))
2890 ('symbol', '2')
2890 ('symbol', '2')
2891 (range
2891 (range
2892 ('symbol', '3')
2892 ('symbol', '3')
2893 ('symbol', '4'))
2893 ('symbol', '4'))
2894 ('symbol', '5')
2894 ('symbol', '5')
2895 ('symbol', '6')))
2895 ('symbol', '6')))
2896 * optimized:
2896 * optimized:
2897 (or
2897 (or
2898 (list
2898 (list
2899 (range
2899 (range
2900 ('symbol', '0')
2900 ('symbol', '0')
2901 ('symbol', '1')
2901 ('symbol', '1')
2902 define)
2902 define)
2903 ('symbol', '2')
2903 ('symbol', '2')
2904 (range
2904 (range
2905 ('symbol', '3')
2905 ('symbol', '3')
2906 ('symbol', '4')
2906 ('symbol', '4')
2907 define)
2907 define)
2908 (func
2908 (func
2909 ('symbol', '_list')
2909 ('symbol', '_list')
2910 ('string', '5\x006')
2910 ('string', '5\x006')
2911 define))
2911 define))
2912 define)
2912 define)
2913 * set:
2913 * set:
2914 <addset
2914 <addset
2915 <addset
2915 <addset
2916 <spanset+ 0:2>,
2916 <spanset+ 0:2>,
2917 <baseset [2]>>,
2917 <baseset [2]>>,
2918 <addset
2918 <addset
2919 <spanset+ 3:5>,
2919 <spanset+ 3:5>,
2920 <baseset [5, 6]>>>
2920 <baseset [5, 6]>>>
2921 0
2921 0
2922 1
2922 1
2923 2
2923 2
2924 3
2924 3
2925 4
2925 4
2926 5
2926 5
2927 6
2927 6
2928
2928
2929 unoptimized `or` looks like this
2929 unoptimized `or` looks like this
2930
2930
2931 $ try --no-optimized -p analyzed '0|1|2|3|4'
2931 $ try --no-optimized -p analyzed '0|1|2|3|4'
2932 * analyzed:
2932 * analyzed:
2933 (or
2933 (or
2934 (list
2934 (list
2935 ('symbol', '0')
2935 ('symbol', '0')
2936 ('symbol', '1')
2936 ('symbol', '1')
2937 ('symbol', '2')
2937 ('symbol', '2')
2938 ('symbol', '3')
2938 ('symbol', '3')
2939 ('symbol', '4'))
2939 ('symbol', '4'))
2940 define)
2940 define)
2941 * set:
2941 * set:
2942 <addset
2942 <addset
2943 <addset
2943 <addset
2944 <baseset [0]>,
2944 <baseset [0]>,
2945 <baseset [1]>>,
2945 <baseset [1]>>,
2946 <addset
2946 <addset
2947 <baseset [2]>,
2947 <baseset [2]>,
2948 <addset
2948 <addset
2949 <baseset [3]>,
2949 <baseset [3]>,
2950 <baseset [4]>>>>
2950 <baseset [4]>>>>
2951 0
2951 0
2952 1
2952 1
2953 2
2953 2
2954 3
2954 3
2955 4
2955 4
2956
2956
2957 test that `_list` should be narrowed by provided `subset`
2957 test that `_list` should be narrowed by provided `subset`
2958
2958
2959 $ log '0:2 and (null|1|2|3)'
2959 $ log '0:2 and (null|1|2|3)'
2960 1
2960 1
2961 2
2961 2
2962
2962
2963 test that `_list` should remove duplicates
2963 test that `_list` should remove duplicates
2964
2964
2965 $ log '0|1|2|1|2|-1|tip'
2965 $ log '0|1|2|1|2|-1|tip'
2966 0
2966 0
2967 1
2967 1
2968 2
2968 2
2969 9
2969 9
2970
2970
2971 test unknown revision in `_list`
2971 test unknown revision in `_list`
2972
2972
2973 $ log '0|unknown'
2973 $ log '0|unknown'
2974 abort: unknown revision 'unknown'!
2974 abort: unknown revision 'unknown'!
2975 [255]
2975 [255]
2976
2976
2977 test integer range in `_list`
2977 test integer range in `_list`
2978
2978
2979 $ log '-1|-10'
2979 $ log '-1|-10'
2980 9
2980 9
2981 0
2981 0
2982
2982
2983 $ log '-10|-11'
2983 $ log '-10|-11'
2984 abort: unknown revision '-11'!
2984 abort: unknown revision '-11'!
2985 [255]
2985 [255]
2986
2986
2987 $ log '9|10'
2987 $ log '9|10'
2988 abort: unknown revision '10'!
2988 abort: unknown revision '10'!
2989 [255]
2989 [255]
2990
2990
2991 test '0000' != '0' in `_list`
2991 test '0000' != '0' in `_list`
2992
2992
2993 $ log '0|0000'
2993 $ log '0|0000'
2994 0
2994 0
2995 -1
2995 -1
2996
2996
2997 test ',' in `_list`
2997 test ',' in `_list`
2998 $ log '0,1'
2998 $ log '0,1'
2999 hg: parse error: can't use a list in this context
2999 hg: parse error: can't use a list in this context
3000 (see hg help "revsets.x or y")
3000 (see hg help "revsets.x or y")
3001 [255]
3001 [255]
3002 $ try '0,1,2'
3002 $ try '0,1,2'
3003 (list
3003 (list
3004 ('symbol', '0')
3004 ('symbol', '0')
3005 ('symbol', '1')
3005 ('symbol', '1')
3006 ('symbol', '2'))
3006 ('symbol', '2'))
3007 hg: parse error: can't use a list in this context
3007 hg: parse error: can't use a list in this context
3008 (see hg help "revsets.x or y")
3008 (see hg help "revsets.x or y")
3009 [255]
3009 [255]
3010
3010
3011 test that chained `or` operations make balanced addsets
3011 test that chained `or` operations make balanced addsets
3012
3012
3013 $ try '0:1|1:2|2:3|3:4|4:5'
3013 $ try '0:1|1:2|2:3|3:4|4:5'
3014 (or
3014 (or
3015 (list
3015 (list
3016 (range
3016 (range
3017 ('symbol', '0')
3017 ('symbol', '0')
3018 ('symbol', '1'))
3018 ('symbol', '1'))
3019 (range
3019 (range
3020 ('symbol', '1')
3020 ('symbol', '1')
3021 ('symbol', '2'))
3021 ('symbol', '2'))
3022 (range
3022 (range
3023 ('symbol', '2')
3023 ('symbol', '2')
3024 ('symbol', '3'))
3024 ('symbol', '3'))
3025 (range
3025 (range
3026 ('symbol', '3')
3026 ('symbol', '3')
3027 ('symbol', '4'))
3027 ('symbol', '4'))
3028 (range
3028 (range
3029 ('symbol', '4')
3029 ('symbol', '4')
3030 ('symbol', '5'))))
3030 ('symbol', '5'))))
3031 * set:
3031 * set:
3032 <addset
3032 <addset
3033 <addset
3033 <addset
3034 <spanset+ 0:2>,
3034 <spanset+ 0:2>,
3035 <spanset+ 1:3>>,
3035 <spanset+ 1:3>>,
3036 <addset
3036 <addset
3037 <spanset+ 2:4>,
3037 <spanset+ 2:4>,
3038 <addset
3038 <addset
3039 <spanset+ 3:5>,
3039 <spanset+ 3:5>,
3040 <spanset+ 4:6>>>>
3040 <spanset+ 4:6>>>>
3041 0
3041 0
3042 1
3042 1
3043 2
3043 2
3044 3
3044 3
3045 4
3045 4
3046 5
3046 5
3047
3047
3048 no crash by empty group "()" while optimizing `or` operations
3048 no crash by empty group "()" while optimizing `or` operations
3049
3049
3050 $ try --optimize '0|()'
3050 $ try --optimize '0|()'
3051 (or
3051 (or
3052 (list
3052 (list
3053 ('symbol', '0')
3053 ('symbol', '0')
3054 (group
3054 (group
3055 None)))
3055 None)))
3056 * optimized:
3056 * optimized:
3057 (or
3057 (or
3058 (list
3058 (list
3059 ('symbol', '0')
3059 ('symbol', '0')
3060 None)
3060 None)
3061 define)
3061 define)
3062 hg: parse error: missing argument
3062 hg: parse error: missing argument
3063 [255]
3063 [255]
3064
3064
3065 test that chained `or` operations never eat up stack (issue4624)
3065 test that chained `or` operations never eat up stack (issue4624)
3066 (uses `0:1` instead of `0` to avoid future optimization of trivial revisions)
3066 (uses `0:1` instead of `0` to avoid future optimization of trivial revisions)
3067
3067
3068 $ hg log -T '{rev}\n' -r `$PYTHON -c "print '+'.join(['0:1'] * 500)"`
3068 $ hg log -T '{rev}\n' -r `$PYTHON -c "print '+'.join(['0:1'] * 500)"`
3069 0
3069 0
3070 1
3070 1
3071
3071
3072 test that repeated `-r` options never eat up stack (issue4565)
3072 test that repeated `-r` options never eat up stack (issue4565)
3073 (uses `-r 0::1` to avoid possible optimization at old-style parser)
3073 (uses `-r 0::1` to avoid possible optimization at old-style parser)
3074
3074
3075 $ hg log -T '{rev}\n' `$PYTHON -c "for i in xrange(500): print '-r 0::1 ',"`
3075 $ hg log -T '{rev}\n' `$PYTHON -c "for i in xrange(500): print '-r 0::1 ',"`
3076 0
3076 0
3077 1
3077 1
3078
3078
3079 check that conversion to only works
3079 check that conversion to only works
3080 $ try --optimize '::3 - ::1'
3080 $ try --optimize '::3 - ::1'
3081 (minus
3081 (minus
3082 (dagrangepre
3082 (dagrangepre
3083 ('symbol', '3'))
3083 ('symbol', '3'))
3084 (dagrangepre
3084 (dagrangepre
3085 ('symbol', '1')))
3085 ('symbol', '1')))
3086 * optimized:
3086 * optimized:
3087 (func
3087 (func
3088 ('symbol', 'only')
3088 ('symbol', 'only')
3089 (list
3089 (list
3090 ('symbol', '3')
3090 ('symbol', '3')
3091 ('symbol', '1'))
3091 ('symbol', '1'))
3092 define)
3092 define)
3093 * set:
3093 * set:
3094 <baseset+ [3]>
3094 <baseset+ [3]>
3095 3
3095 3
3096 $ try --optimize 'ancestors(1) - ancestors(3)'
3096 $ try --optimize 'ancestors(1) - ancestors(3)'
3097 (minus
3097 (minus
3098 (func
3098 (func
3099 ('symbol', 'ancestors')
3099 ('symbol', 'ancestors')
3100 ('symbol', '1'))
3100 ('symbol', '1'))
3101 (func
3101 (func
3102 ('symbol', 'ancestors')
3102 ('symbol', 'ancestors')
3103 ('symbol', '3')))
3103 ('symbol', '3')))
3104 * optimized:
3104 * optimized:
3105 (func
3105 (func
3106 ('symbol', 'only')
3106 ('symbol', 'only')
3107 (list
3107 (list
3108 ('symbol', '1')
3108 ('symbol', '1')
3109 ('symbol', '3'))
3109 ('symbol', '3'))
3110 define)
3110 define)
3111 * set:
3111 * set:
3112 <baseset+ []>
3112 <baseset+ []>
3113 $ try --optimize 'not ::2 and ::6'
3113 $ try --optimize 'not ::2 and ::6'
3114 (and
3114 (and
3115 (not
3115 (not
3116 (dagrangepre
3116 (dagrangepre
3117 ('symbol', '2')))
3117 ('symbol', '2')))
3118 (dagrangepre
3118 (dagrangepre
3119 ('symbol', '6')))
3119 ('symbol', '6')))
3120 * optimized:
3120 * optimized:
3121 (func
3121 (func
3122 ('symbol', 'only')
3122 ('symbol', 'only')
3123 (list
3123 (list
3124 ('symbol', '6')
3124 ('symbol', '6')
3125 ('symbol', '2'))
3125 ('symbol', '2'))
3126 define)
3126 define)
3127 * set:
3127 * set:
3128 <baseset+ [3, 4, 5, 6]>
3128 <baseset+ [3, 4, 5, 6]>
3129 3
3129 3
3130 4
3130 4
3131 5
3131 5
3132 6
3132 6
3133 $ try --optimize 'ancestors(6) and not ancestors(4)'
3133 $ try --optimize 'ancestors(6) and not ancestors(4)'
3134 (and
3134 (and
3135 (func
3135 (func
3136 ('symbol', 'ancestors')
3136 ('symbol', 'ancestors')
3137 ('symbol', '6'))
3137 ('symbol', '6'))
3138 (not
3138 (not
3139 (func
3139 (func
3140 ('symbol', 'ancestors')
3140 ('symbol', 'ancestors')
3141 ('symbol', '4'))))
3141 ('symbol', '4'))))
3142 * optimized:
3142 * optimized:
3143 (func
3143 (func
3144 ('symbol', 'only')
3144 ('symbol', 'only')
3145 (list
3145 (list
3146 ('symbol', '6')
3146 ('symbol', '6')
3147 ('symbol', '4'))
3147 ('symbol', '4'))
3148 define)
3148 define)
3149 * set:
3149 * set:
3150 <baseset+ [3, 5, 6]>
3150 <baseset+ [3, 5, 6]>
3151 3
3151 3
3152 5
3152 5
3153 6
3153 6
3154
3154
3155 no crash by empty group "()" while optimizing to "only()"
3155 no crash by empty group "()" while optimizing to "only()"
3156
3156
3157 $ try --optimize '::1 and ()'
3157 $ try --optimize '::1 and ()'
3158 (and
3158 (and
3159 (dagrangepre
3159 (dagrangepre
3160 ('symbol', '1'))
3160 ('symbol', '1'))
3161 (group
3161 (group
3162 None))
3162 None))
3163 * optimized:
3163 * optimized:
3164 (and
3164 (and
3165 None
3165 None
3166 (func
3166 (func
3167 ('symbol', 'ancestors')
3167 ('symbol', 'ancestors')
3168 ('symbol', '1')
3168 ('symbol', '1')
3169 define)
3169 define)
3170 define)
3170 define)
3171 hg: parse error: missing argument
3171 hg: parse error: missing argument
3172 [255]
3172 [255]
3173
3173
3174 optimization to only() works only if ancestors() takes only one argument
3174 optimization to only() works only if ancestors() takes only one argument
3175
3175
3176 $ hg debugrevspec -p optimized 'ancestors(6) - ancestors(4, 1)'
3176 $ hg debugrevspec -p optimized 'ancestors(6) - ancestors(4, 1)'
3177 * optimized:
3177 * optimized:
3178 (difference
3178 (difference
3179 (func
3179 (func
3180 ('symbol', 'ancestors')
3180 ('symbol', 'ancestors')
3181 ('symbol', '6')
3181 ('symbol', '6')
3182 define)
3182 define)
3183 (func
3183 (func
3184 ('symbol', 'ancestors')
3184 ('symbol', 'ancestors')
3185 (list
3185 (list
3186 ('symbol', '4')
3186 ('symbol', '4')
3187 ('symbol', '1'))
3187 ('symbol', '1'))
3188 any)
3188 any)
3189 define)
3189 define)
3190 0
3190 0
3191 1
3191 1
3192 3
3192 3
3193 5
3193 5
3194 6
3194 6
3195 $ hg debugrevspec -p optimized 'ancestors(6, 1) - ancestors(4)'
3195 $ hg debugrevspec -p optimized 'ancestors(6, 1) - ancestors(4)'
3196 * optimized:
3196 * optimized:
3197 (difference
3197 (difference
3198 (func
3198 (func
3199 ('symbol', 'ancestors')
3199 ('symbol', 'ancestors')
3200 (list
3200 (list
3201 ('symbol', '6')
3201 ('symbol', '6')
3202 ('symbol', '1'))
3202 ('symbol', '1'))
3203 define)
3203 define)
3204 (func
3204 (func
3205 ('symbol', 'ancestors')
3205 ('symbol', 'ancestors')
3206 ('symbol', '4')
3206 ('symbol', '4')
3207 any)
3207 any)
3208 define)
3208 define)
3209 5
3209 5
3210 6
3210 6
3211
3211
3212 optimization disabled if keyword arguments passed (because we're too lazy
3212 optimization disabled if keyword arguments passed (because we're too lazy
3213 to support it)
3213 to support it)
3214
3214
3215 $ hg debugrevspec -p optimized 'ancestors(set=6) - ancestors(set=4)'
3215 $ hg debugrevspec -p optimized 'ancestors(set=6) - ancestors(set=4)'
3216 * optimized:
3216 * optimized:
3217 (difference
3217 (difference
3218 (func
3218 (func
3219 ('symbol', 'ancestors')
3219 ('symbol', 'ancestors')
3220 (keyvalue
3220 (keyvalue
3221 ('symbol', 'set')
3221 ('symbol', 'set')
3222 ('symbol', '6'))
3222 ('symbol', '6'))
3223 define)
3223 define)
3224 (func
3224 (func
3225 ('symbol', 'ancestors')
3225 ('symbol', 'ancestors')
3226 (keyvalue
3226 (keyvalue
3227 ('symbol', 'set')
3227 ('symbol', 'set')
3228 ('symbol', '4'))
3228 ('symbol', '4'))
3229 any)
3229 any)
3230 define)
3230 define)
3231 3
3231 3
3232 5
3232 5
3233 6
3233 6
3234
3234
3235 invalid function call should not be optimized to only()
3235 invalid function call should not be optimized to only()
3236
3236
3237 $ log '"ancestors"(6) and not ancestors(4)'
3237 $ log '"ancestors"(6) and not ancestors(4)'
3238 hg: parse error: not a symbol
3238 hg: parse error: not a symbol
3239 [255]
3239 [255]
3240
3240
3241 $ log 'ancestors(6) and not "ancestors"(4)'
3241 $ log 'ancestors(6) and not "ancestors"(4)'
3242 hg: parse error: not a symbol
3242 hg: parse error: not a symbol
3243 [255]
3243 [255]
3244
3244
3245 we can use patterns when searching for tags
3245 we can use patterns when searching for tags
3246
3246
3247 $ log 'tag("1..*")'
3247 $ log 'tag("1..*")'
3248 abort: tag '1..*' does not exist!
3248 abort: tag '1..*' does not exist!
3249 [255]
3249 [255]
3250 $ log 'tag("re:1..*")'
3250 $ log 'tag("re:1..*")'
3251 6
3251 6
3252 $ log 'tag("re:[0-9].[0-9]")'
3252 $ log 'tag("re:[0-9].[0-9]")'
3253 6
3253 6
3254 $ log 'tag("literal:1.0")'
3254 $ log 'tag("literal:1.0")'
3255 6
3255 6
3256 $ log 'tag("re:0..*")'
3256 $ log 'tag("re:0..*")'
3257
3257
3258 $ log 'tag(unknown)'
3258 $ log 'tag(unknown)'
3259 abort: tag 'unknown' does not exist!
3259 abort: tag 'unknown' does not exist!
3260 [255]
3260 [255]
3261 $ log 'tag("re:unknown")'
3261 $ log 'tag("re:unknown")'
3262 $ log 'present(tag("unknown"))'
3262 $ log 'present(tag("unknown"))'
3263 $ log 'present(tag("re:unknown"))'
3263 $ log 'present(tag("re:unknown"))'
3264 $ log 'branch(unknown)'
3264 $ log 'branch(unknown)'
3265 abort: unknown revision 'unknown'!
3265 abort: unknown revision 'unknown'!
3266 [255]
3266 [255]
3267 $ log 'branch("literal:unknown")'
3267 $ log 'branch("literal:unknown")'
3268 abort: branch 'unknown' does not exist!
3268 abort: branch 'unknown' does not exist!
3269 [255]
3269 [255]
3270 $ log 'branch("re:unknown")'
3270 $ log 'branch("re:unknown")'
3271 $ log 'present(branch("unknown"))'
3271 $ log 'present(branch("unknown"))'
3272 $ log 'present(branch("re:unknown"))'
3272 $ log 'present(branch("re:unknown"))'
3273 $ log 'user(bob)'
3273 $ log 'user(bob)'
3274 2
3274 2
3275
3275
3276 $ log '4::8'
3276 $ log '4::8'
3277 4
3277 4
3278 8
3278 8
3279 $ log '4:8'
3279 $ log '4:8'
3280 4
3280 4
3281 5
3281 5
3282 6
3282 6
3283 7
3283 7
3284 8
3284 8
3285
3285
3286 $ log 'sort(!merge() & (modifies(b) | user(bob) | keyword(bug) | keyword(issue) & 1::9), "-date")'
3286 $ log 'sort(!merge() & (modifies(b) | user(bob) | keyword(bug) | keyword(issue) & 1::9), "-date")'
3287 4
3287 4
3288 2
3288 2
3289 5
3289 5
3290
3290
3291 $ log 'not 0 and 0:2'
3291 $ log 'not 0 and 0:2'
3292 1
3292 1
3293 2
3293 2
3294 $ log 'not 1 and 0:2'
3294 $ log 'not 1 and 0:2'
3295 0
3295 0
3296 2
3296 2
3297 $ log 'not 2 and 0:2'
3297 $ log 'not 2 and 0:2'
3298 0
3298 0
3299 1
3299 1
3300 $ log '(1 and 2)::'
3300 $ log '(1 and 2)::'
3301 $ log '(1 and 2):'
3301 $ log '(1 and 2):'
3302 $ log '(1 and 2):3'
3302 $ log '(1 and 2):3'
3303 $ log 'sort(head(), -rev)'
3303 $ log 'sort(head(), -rev)'
3304 9
3304 9
3305 7
3305 7
3306 6
3306 6
3307 5
3307 5
3308 4
3308 4
3309 3
3309 3
3310 2
3310 2
3311 1
3311 1
3312 0
3312 0
3313 $ log '4::8 - 8'
3313 $ log '4::8 - 8'
3314 4
3314 4
3315
3315
3316 matching() should preserve the order of the input set:
3316 matching() should preserve the order of the input set:
3317
3317
3318 $ log '(2 or 3 or 1) and matching(1 or 2 or 3)'
3318 $ log '(2 or 3 or 1) and matching(1 or 2 or 3)'
3319 2
3319 2
3320 3
3320 3
3321 1
3321 1
3322
3322
3323 $ log 'named("unknown")'
3323 $ log 'named("unknown")'
3324 abort: namespace 'unknown' does not exist!
3324 abort: namespace 'unknown' does not exist!
3325 [255]
3325 [255]
3326 $ log 'named("re:unknown")'
3326 $ log 'named("re:unknown")'
3327 abort: no namespace exists that match 'unknown'!
3327 abort: no namespace exists that match 'unknown'!
3328 [255]
3328 [255]
3329 $ log 'present(named("unknown"))'
3329 $ log 'present(named("unknown"))'
3330 $ log 'present(named("re:unknown"))'
3330 $ log 'present(named("re:unknown"))'
3331
3331
3332 $ log 'tag()'
3332 $ log 'tag()'
3333 6
3333 6
3334 $ log 'named("tags")'
3334 $ log 'named("tags")'
3335 6
3335 6
3336
3336
3337 issue2437
3337 issue2437
3338
3338
3339 $ log '3 and p1(5)'
3339 $ log '3 and p1(5)'
3340 3
3340 3
3341 $ log '4 and p2(6)'
3341 $ log '4 and p2(6)'
3342 4
3342 4
3343 $ log '1 and parents(:2)'
3343 $ log '1 and parents(:2)'
3344 1
3344 1
3345 $ log '2 and children(1:)'
3345 $ log '2 and children(1:)'
3346 2
3346 2
3347 $ log 'roots(all()) or roots(all())'
3347 $ log 'roots(all()) or roots(all())'
3348 0
3348 0
3349 $ hg debugrevspec 'roots(all()) or roots(all())'
3349 $ hg debugrevspec 'roots(all()) or roots(all())'
3350 0
3350 0
3351 $ log 'heads(branch(Γ©)) or heads(branch(Γ©))'
3351 $ log 'heads(branch(Γ©)) or heads(branch(Γ©))'
3352 9
3352 9
3353 $ log 'ancestors(8) and (heads(branch("-a-b-c-")) or heads(branch(Γ©)))'
3353 $ log 'ancestors(8) and (heads(branch("-a-b-c-")) or heads(branch(Γ©)))'
3354 4
3354 4
3355
3355
3356 issue2654: report a parse error if the revset was not completely parsed
3356 issue2654: report a parse error if the revset was not completely parsed
3357
3357
3358 $ log '1 OR 2'
3358 $ log '1 OR 2'
3359 hg: parse error at 2: invalid token
3359 hg: parse error at 2: invalid token
3360 [255]
3360 [255]
3361
3361
3362 or operator should preserve ordering:
3362 or operator should preserve ordering:
3363 $ log 'reverse(2::4) or tip'
3363 $ log 'reverse(2::4) or tip'
3364 4
3364 4
3365 2
3365 2
3366 9
3366 9
3367
3367
3368 parentrevspec
3368 parentrevspec
3369
3369
3370 $ log 'merge()^0'
3370 $ log 'merge()^0'
3371 6
3371 6
3372 $ log 'merge()^'
3372 $ log 'merge()^'
3373 5
3373 5
3374 $ log 'merge()^1'
3374 $ log 'merge()^1'
3375 5
3375 5
3376 $ log 'merge()^2'
3376 $ log 'merge()^2'
3377 4
3377 4
3378 $ log '(not merge())^2'
3378 $ log '(not merge())^2'
3379 $ log 'merge()^^'
3379 $ log 'merge()^^'
3380 3
3380 3
3381 $ log 'merge()^1^'
3381 $ log 'merge()^1^'
3382 3
3382 3
3383 $ log 'merge()^^^'
3383 $ log 'merge()^^^'
3384 1
3384 1
3385
3385
3386 $ hg debugrevspec -s '(merge() | 0)~-1'
3386 $ hg debugrevspec -s '(merge() | 0)~-1'
3387 * set:
3387 * set:
3388 <baseset+ [1, 7]>
3388 <baseset+ [1, 7]>
3389 1
3389 1
3390 7
3390 7
3391 $ log 'merge()~-1'
3391 $ log 'merge()~-1'
3392 7
3392 7
3393 $ log 'tip~-1'
3393 $ log 'tip~-1'
3394 $ log '(tip | merge())~-1'
3394 $ log '(tip | merge())~-1'
3395 7
3395 7
3396 $ log 'merge()~0'
3396 $ log 'merge()~0'
3397 6
3397 6
3398 $ log 'merge()~1'
3398 $ log 'merge()~1'
3399 5
3399 5
3400 $ log 'merge()~2'
3400 $ log 'merge()~2'
3401 3
3401 3
3402 $ log 'merge()~2^1'
3402 $ log 'merge()~2^1'
3403 1
3403 1
3404 $ log 'merge()~3'
3404 $ log 'merge()~3'
3405 1
3405 1
3406
3406
3407 $ log '(-3:tip)^'
3407 $ log '(-3:tip)^'
3408 4
3408 4
3409 6
3409 6
3410 8
3410 8
3411
3411
3412 $ log 'tip^foo'
3412 $ log 'tip^foo'
3413 hg: parse error: ^ expects a number 0, 1, or 2
3413 hg: parse error: ^ expects a number 0, 1, or 2
3414 [255]
3414 [255]
3415
3415
3416 $ log 'branchpoint()~-1'
3416 $ log 'branchpoint()~-1'
3417 abort: revision in set has more than one child!
3417 abort: revision in set has more than one child!
3418 [255]
3418 [255]
3419
3419
3420 Bogus function gets suggestions
3420 Bogus function gets suggestions
3421 $ log 'add()'
3421 $ log 'add()'
3422 hg: parse error: unknown identifier: add
3422 hg: parse error: unknown identifier: add
3423 (did you mean adds?)
3423 (did you mean adds?)
3424 [255]
3424 [255]
3425 $ log 'added()'
3425 $ log 'added()'
3426 hg: parse error: unknown identifier: added
3426 hg: parse error: unknown identifier: added
3427 (did you mean adds?)
3427 (did you mean adds?)
3428 [255]
3428 [255]
3429 $ log 'remo()'
3429 $ log 'remo()'
3430 hg: parse error: unknown identifier: remo
3430 hg: parse error: unknown identifier: remo
3431 (did you mean one of remote, removes?)
3431 (did you mean one of remote, removes?)
3432 [255]
3432 [255]
3433 $ log 'babar()'
3433 $ log 'babar()'
3434 hg: parse error: unknown identifier: babar
3434 hg: parse error: unknown identifier: babar
3435 [255]
3435 [255]
3436
3436
3437 Bogus function with a similar internal name doesn't suggest the internal name
3437 Bogus function with a similar internal name doesn't suggest the internal name
3438 $ log 'matches()'
3438 $ log 'matches()'
3439 hg: parse error: unknown identifier: matches
3439 hg: parse error: unknown identifier: matches
3440 (did you mean matching?)
3440 (did you mean matching?)
3441 [255]
3441 [255]
3442
3442
3443 Undocumented functions aren't suggested as similar either
3443 Undocumented functions aren't suggested as similar either
3444 $ log 'tagged2()'
3444 $ log 'tagged2()'
3445 hg: parse error: unknown identifier: tagged2
3445 hg: parse error: unknown identifier: tagged2
3446 [255]
3446 [255]
3447
3447
3448 multiple revspecs
3448 multiple revspecs
3449
3449
3450 $ hg log -r 'tip~1:tip' -r 'tip~2:tip~1' --template '{rev}\n'
3450 $ hg log -r 'tip~1:tip' -r 'tip~2:tip~1' --template '{rev}\n'
3451 8
3451 8
3452 9
3452 9
3453 4
3453 4
3454 5
3454 5
3455 6
3455 6
3456 7
3456 7
3457
3457
3458 test usage in revpair (with "+")
3458 test usage in revpair (with "+")
3459
3459
3460 (real pair)
3460 (real pair)
3461
3461
3462 $ hg diff -r 'tip^^' -r 'tip'
3462 $ hg diff -r 'tip^^' -r 'tip'
3463 diff -r 2326846efdab -r 24286f4ae135 .hgtags
3463 diff -r 2326846efdab -r 24286f4ae135 .hgtags
3464 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3464 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3465 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
3465 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
3466 @@ -0,0 +1,1 @@
3466 @@ -0,0 +1,1 @@
3467 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3467 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3468 $ hg diff -r 'tip^^::tip'
3468 $ hg diff -r 'tip^^::tip'
3469 diff -r 2326846efdab -r 24286f4ae135 .hgtags
3469 diff -r 2326846efdab -r 24286f4ae135 .hgtags
3470 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3470 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3471 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
3471 +++ b/.hgtags Thu Jan 01 00:00:00 1970 +0000
3472 @@ -0,0 +1,1 @@
3472 @@ -0,0 +1,1 @@
3473 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3473 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3474
3474
3475 (single rev)
3475 (single rev)
3476
3476
3477 $ hg diff -r 'tip^' -r 'tip^'
3477 $ hg diff -r 'tip^' -r 'tip^'
3478 $ hg diff -r 'tip^:tip^'
3478 $ hg diff -r 'tip^:tip^'
3479
3479
3480 (single rev that does not looks like a range)
3480 (single rev that does not looks like a range)
3481
3481
3482 $ hg diff -r 'tip^::tip^ or tip^'
3482 $ hg diff -r 'tip^::tip^ or tip^'
3483 diff -r d5d0dcbdc4d9 .hgtags
3483 diff -r d5d0dcbdc4d9 .hgtags
3484 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3484 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3485 +++ b/.hgtags * (glob)
3485 +++ b/.hgtags * (glob)
3486 @@ -0,0 +1,1 @@
3486 @@ -0,0 +1,1 @@
3487 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3487 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3488 $ hg diff -r 'tip^ or tip^'
3488 $ hg diff -r 'tip^ or tip^'
3489 diff -r d5d0dcbdc4d9 .hgtags
3489 diff -r d5d0dcbdc4d9 .hgtags
3490 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3490 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3491 +++ b/.hgtags * (glob)
3491 +++ b/.hgtags * (glob)
3492 @@ -0,0 +1,1 @@
3492 @@ -0,0 +1,1 @@
3493 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3493 +e0cc66ef77e8b6f711815af4e001a6594fde3ba5 1.0
3494
3494
3495 (no rev)
3495 (no rev)
3496
3496
3497 $ hg diff -r 'author("babar") or author("celeste")'
3497 $ hg diff -r 'author("babar") or author("celeste")'
3498 abort: empty revision range
3498 abort: empty revision range
3499 [255]
3499 [255]
3500
3500
3501 aliases:
3501 aliases:
3502
3502
3503 $ echo '[revsetalias]' >> .hg/hgrc
3503 $ echo '[revsetalias]' >> .hg/hgrc
3504 $ echo 'm = merge()' >> .hg/hgrc
3504 $ echo 'm = merge()' >> .hg/hgrc
3505 (revset aliases can override builtin revsets)
3505 (revset aliases can override builtin revsets)
3506 $ echo 'p2($1) = p1($1)' >> .hg/hgrc
3506 $ echo 'p2($1) = p1($1)' >> .hg/hgrc
3507 $ echo 'sincem = descendants(m)' >> .hg/hgrc
3507 $ echo 'sincem = descendants(m)' >> .hg/hgrc
3508 $ echo 'd($1) = reverse(sort($1, date))' >> .hg/hgrc
3508 $ echo 'd($1) = reverse(sort($1, date))' >> .hg/hgrc
3509 $ echo 'rs(ARG1, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
3509 $ echo 'rs(ARG1, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
3510 $ echo 'rs4(ARG1, ARGA, ARGB, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
3510 $ echo 'rs4(ARG1, ARGA, ARGB, ARG2) = reverse(sort(ARG1, ARG2))' >> .hg/hgrc
3511
3511
3512 $ try m
3512 $ try m
3513 ('symbol', 'm')
3513 ('symbol', 'm')
3514 * expanded:
3514 * expanded:
3515 (func
3515 (func
3516 ('symbol', 'merge')
3516 ('symbol', 'merge')
3517 None)
3517 None)
3518 * set:
3518 * set:
3519 <filteredset
3519 <filteredset
3520 <fullreposet+ 0:10>,
3520 <fullreposet+ 0:10>,
3521 <merge>>
3521 <merge>>
3522 6
3522 6
3523
3523
3524 $ HGPLAIN=1
3524 $ HGPLAIN=1
3525 $ export HGPLAIN
3525 $ export HGPLAIN
3526 $ try m
3526 $ try m
3527 ('symbol', 'm')
3527 ('symbol', 'm')
3528 abort: unknown revision 'm'!
3528 abort: unknown revision 'm'!
3529 [255]
3529 [255]
3530
3530
3531 $ HGPLAINEXCEPT=revsetalias
3531 $ HGPLAINEXCEPT=revsetalias
3532 $ export HGPLAINEXCEPT
3532 $ export HGPLAINEXCEPT
3533 $ try m
3533 $ try m
3534 ('symbol', 'm')
3534 ('symbol', 'm')
3535 * expanded:
3535 * expanded:
3536 (func
3536 (func
3537 ('symbol', 'merge')
3537 ('symbol', 'merge')
3538 None)
3538 None)
3539 * set:
3539 * set:
3540 <filteredset
3540 <filteredset
3541 <fullreposet+ 0:10>,
3541 <fullreposet+ 0:10>,
3542 <merge>>
3542 <merge>>
3543 6
3543 6
3544
3544
3545 $ unset HGPLAIN
3545 $ unset HGPLAIN
3546 $ unset HGPLAINEXCEPT
3546 $ unset HGPLAINEXCEPT
3547
3547
3548 $ try 'p2(.)'
3548 $ try 'p2(.)'
3549 (func
3549 (func
3550 ('symbol', 'p2')
3550 ('symbol', 'p2')
3551 ('symbol', '.'))
3551 ('symbol', '.'))
3552 * expanded:
3552 * expanded:
3553 (func
3553 (func
3554 ('symbol', 'p1')
3554 ('symbol', 'p1')
3555 ('symbol', '.'))
3555 ('symbol', '.'))
3556 * set:
3556 * set:
3557 <baseset+ [8]>
3557 <baseset+ [8]>
3558 8
3558 8
3559
3559
3560 $ HGPLAIN=1
3560 $ HGPLAIN=1
3561 $ export HGPLAIN
3561 $ export HGPLAIN
3562 $ try 'p2(.)'
3562 $ try 'p2(.)'
3563 (func
3563 (func
3564 ('symbol', 'p2')
3564 ('symbol', 'p2')
3565 ('symbol', '.'))
3565 ('symbol', '.'))
3566 * set:
3566 * set:
3567 <baseset+ []>
3567 <baseset+ []>
3568
3568
3569 $ HGPLAINEXCEPT=revsetalias
3569 $ HGPLAINEXCEPT=revsetalias
3570 $ export HGPLAINEXCEPT
3570 $ export HGPLAINEXCEPT
3571 $ try 'p2(.)'
3571 $ try 'p2(.)'
3572 (func
3572 (func
3573 ('symbol', 'p2')
3573 ('symbol', 'p2')
3574 ('symbol', '.'))
3574 ('symbol', '.'))
3575 * expanded:
3575 * expanded:
3576 (func
3576 (func
3577 ('symbol', 'p1')
3577 ('symbol', 'p1')
3578 ('symbol', '.'))
3578 ('symbol', '.'))
3579 * set:
3579 * set:
3580 <baseset+ [8]>
3580 <baseset+ [8]>
3581 8
3581 8
3582
3582
3583 $ unset HGPLAIN
3583 $ unset HGPLAIN
3584 $ unset HGPLAINEXCEPT
3584 $ unset HGPLAINEXCEPT
3585
3585
3586 test alias recursion
3586 test alias recursion
3587
3587
3588 $ try sincem
3588 $ try sincem
3589 ('symbol', 'sincem')
3589 ('symbol', 'sincem')
3590 * expanded:
3590 * expanded:
3591 (func
3591 (func
3592 ('symbol', 'descendants')
3592 ('symbol', 'descendants')
3593 (func
3593 (func
3594 ('symbol', 'merge')
3594 ('symbol', 'merge')
3595 None))
3595 None))
3596 * set:
3596 * set:
3597 <generatorset+>
3597 <generatorset+>
3598 6
3598 6
3599 7
3599 7
3600
3600
3601 test infinite recursion
3601 test infinite recursion
3602
3602
3603 $ echo 'recurse1 = recurse2' >> .hg/hgrc
3603 $ echo 'recurse1 = recurse2' >> .hg/hgrc
3604 $ echo 'recurse2 = recurse1' >> .hg/hgrc
3604 $ echo 'recurse2 = recurse1' >> .hg/hgrc
3605 $ try recurse1
3605 $ try recurse1
3606 ('symbol', 'recurse1')
3606 ('symbol', 'recurse1')
3607 hg: parse error: infinite expansion of revset alias "recurse1" detected
3607 hg: parse error: infinite expansion of revset alias "recurse1" detected
3608 [255]
3608 [255]
3609
3609
3610 $ echo 'level1($1, $2) = $1 or $2' >> .hg/hgrc
3610 $ echo 'level1($1, $2) = $1 or $2' >> .hg/hgrc
3611 $ echo 'level2($1, $2) = level1($2, $1)' >> .hg/hgrc
3611 $ echo 'level2($1, $2) = level1($2, $1)' >> .hg/hgrc
3612 $ try "level2(level1(1, 2), 3)"
3612 $ try "level2(level1(1, 2), 3)"
3613 (func
3613 (func
3614 ('symbol', 'level2')
3614 ('symbol', 'level2')
3615 (list
3615 (list
3616 (func
3616 (func
3617 ('symbol', 'level1')
3617 ('symbol', 'level1')
3618 (list
3618 (list
3619 ('symbol', '1')
3619 ('symbol', '1')
3620 ('symbol', '2')))
3620 ('symbol', '2')))
3621 ('symbol', '3')))
3621 ('symbol', '3')))
3622 * expanded:
3622 * expanded:
3623 (or
3623 (or
3624 (list
3624 (list
3625 ('symbol', '3')
3625 ('symbol', '3')
3626 (or
3626 (or
3627 (list
3627 (list
3628 ('symbol', '1')
3628 ('symbol', '1')
3629 ('symbol', '2')))))
3629 ('symbol', '2')))))
3630 * set:
3630 * set:
3631 <addset
3631 <addset
3632 <baseset [3]>,
3632 <baseset [3]>,
3633 <baseset [1, 2]>>
3633 <baseset [1, 2]>>
3634 3
3634 3
3635 1
3635 1
3636 2
3636 2
3637
3637
3638 test nesting and variable passing
3638 test nesting and variable passing
3639
3639
3640 $ echo 'nested($1) = nested2($1)' >> .hg/hgrc
3640 $ echo 'nested($1) = nested2($1)' >> .hg/hgrc
3641 $ echo 'nested2($1) = nested3($1)' >> .hg/hgrc
3641 $ echo 'nested2($1) = nested3($1)' >> .hg/hgrc
3642 $ echo 'nested3($1) = max($1)' >> .hg/hgrc
3642 $ echo 'nested3($1) = max($1)' >> .hg/hgrc
3643 $ try 'nested(2:5)'
3643 $ try 'nested(2:5)'
3644 (func
3644 (func
3645 ('symbol', 'nested')
3645 ('symbol', 'nested')
3646 (range
3646 (range
3647 ('symbol', '2')
3647 ('symbol', '2')
3648 ('symbol', '5')))
3648 ('symbol', '5')))
3649 * expanded:
3649 * expanded:
3650 (func
3650 (func
3651 ('symbol', 'max')
3651 ('symbol', 'max')
3652 (range
3652 (range
3653 ('symbol', '2')
3653 ('symbol', '2')
3654 ('symbol', '5')))
3654 ('symbol', '5')))
3655 * set:
3655 * set:
3656 <baseset
3656 <baseset
3657 <max
3657 <max
3658 <fullreposet+ 0:10>,
3658 <fullreposet+ 0:10>,
3659 <spanset+ 2:6>>>
3659 <spanset+ 2:6>>>
3660 5
3660 5
3661
3661
3662 test chained `or` operations are flattened at parsing phase
3662 test chained `or` operations are flattened at parsing phase
3663
3663
3664 $ echo 'chainedorops($1, $2, $3) = $1|$2|$3' >> .hg/hgrc
3664 $ echo 'chainedorops($1, $2, $3) = $1|$2|$3' >> .hg/hgrc
3665 $ try 'chainedorops(0:1, 1:2, 2:3)'
3665 $ try 'chainedorops(0:1, 1:2, 2:3)'
3666 (func
3666 (func
3667 ('symbol', 'chainedorops')
3667 ('symbol', 'chainedorops')
3668 (list
3668 (list
3669 (range
3669 (range
3670 ('symbol', '0')
3670 ('symbol', '0')
3671 ('symbol', '1'))
3671 ('symbol', '1'))
3672 (range
3672 (range
3673 ('symbol', '1')
3673 ('symbol', '1')
3674 ('symbol', '2'))
3674 ('symbol', '2'))
3675 (range
3675 (range
3676 ('symbol', '2')
3676 ('symbol', '2')
3677 ('symbol', '3'))))
3677 ('symbol', '3'))))
3678 * expanded:
3678 * expanded:
3679 (or
3679 (or
3680 (list
3680 (list
3681 (range
3681 (range
3682 ('symbol', '0')
3682 ('symbol', '0')
3683 ('symbol', '1'))
3683 ('symbol', '1'))
3684 (range
3684 (range
3685 ('symbol', '1')
3685 ('symbol', '1')
3686 ('symbol', '2'))
3686 ('symbol', '2'))
3687 (range
3687 (range
3688 ('symbol', '2')
3688 ('symbol', '2')
3689 ('symbol', '3'))))
3689 ('symbol', '3'))))
3690 * set:
3690 * set:
3691 <addset
3691 <addset
3692 <spanset+ 0:2>,
3692 <spanset+ 0:2>,
3693 <addset
3693 <addset
3694 <spanset+ 1:3>,
3694 <spanset+ 1:3>,
3695 <spanset+ 2:4>>>
3695 <spanset+ 2:4>>>
3696 0
3696 0
3697 1
3697 1
3698 2
3698 2
3699 3
3699 3
3700
3700
3701 test variable isolation, variable placeholders are rewritten as string
3701 test variable isolation, variable placeholders are rewritten as string
3702 then parsed and matched again as string. Check they do not leak too
3702 then parsed and matched again as string. Check they do not leak too
3703 far away.
3703 far away.
3704
3704
3705 $ echo 'injectparamasstring = max("$1")' >> .hg/hgrc
3705 $ echo 'injectparamasstring = max("$1")' >> .hg/hgrc
3706 $ echo 'callinjection($1) = descendants(injectparamasstring)' >> .hg/hgrc
3706 $ echo 'callinjection($1) = descendants(injectparamasstring)' >> .hg/hgrc
3707 $ try 'callinjection(2:5)'
3707 $ try 'callinjection(2:5)'
3708 (func
3708 (func
3709 ('symbol', 'callinjection')
3709 ('symbol', 'callinjection')
3710 (range
3710 (range
3711 ('symbol', '2')
3711 ('symbol', '2')
3712 ('symbol', '5')))
3712 ('symbol', '5')))
3713 * expanded:
3713 * expanded:
3714 (func
3714 (func
3715 ('symbol', 'descendants')
3715 ('symbol', 'descendants')
3716 (func
3716 (func
3717 ('symbol', 'max')
3717 ('symbol', 'max')
3718 ('string', '$1')))
3718 ('string', '$1')))
3719 abort: unknown revision '$1'!
3719 abort: unknown revision '$1'!
3720 [255]
3720 [255]
3721
3721
3722 test scope of alias expansion: 'universe' is expanded prior to 'shadowall(0)',
3722 test scope of alias expansion: 'universe' is expanded prior to 'shadowall(0)',
3723 but 'all()' should never be substituted to '0()'.
3723 but 'all()' should never be substituted to '0()'.
3724
3724
3725 $ echo 'universe = all()' >> .hg/hgrc
3725 $ echo 'universe = all()' >> .hg/hgrc
3726 $ echo 'shadowall(all) = all and universe' >> .hg/hgrc
3726 $ echo 'shadowall(all) = all and universe' >> .hg/hgrc
3727 $ try 'shadowall(0)'
3727 $ try 'shadowall(0)'
3728 (func
3728 (func
3729 ('symbol', 'shadowall')
3729 ('symbol', 'shadowall')
3730 ('symbol', '0'))
3730 ('symbol', '0'))
3731 * expanded:
3731 * expanded:
3732 (and
3732 (and
3733 ('symbol', '0')
3733 ('symbol', '0')
3734 (func
3734 (func
3735 ('symbol', 'all')
3735 ('symbol', 'all')
3736 None))
3736 None))
3737 * set:
3737 * set:
3738 <filteredset
3738 <filteredset
3739 <baseset [0]>,
3739 <baseset [0]>,
3740 <spanset+ 0:10>>
3740 <spanset+ 0:10>>
3741 0
3741 0
3742
3742
3743 test unknown reference:
3743 test unknown reference:
3744
3744
3745 $ try "unknownref(0)" --config 'revsetalias.unknownref($1)=$1:$2'
3745 $ try "unknownref(0)" --config 'revsetalias.unknownref($1)=$1:$2'
3746 (func
3746 (func
3747 ('symbol', 'unknownref')
3747 ('symbol', 'unknownref')
3748 ('symbol', '0'))
3748 ('symbol', '0'))
3749 abort: bad definition of revset alias "unknownref": invalid symbol '$2'
3749 abort: bad definition of revset alias "unknownref": invalid symbol '$2'
3750 [255]
3750 [255]
3751
3751
3752 $ hg debugrevspec --debug --config revsetalias.anotherbadone='branch(' "tip"
3752 $ hg debugrevspec --debug --config revsetalias.anotherbadone='branch(' "tip"
3753 ('symbol', 'tip')
3753 ('symbol', 'tip')
3754 warning: bad definition of revset alias "anotherbadone": at 7: not a prefix: end
3754 warning: bad definition of revset alias "anotherbadone": at 7: not a prefix: end
3755 * set:
3755 * set:
3756 <baseset [9]>
3756 <baseset [9]>
3757 9
3757 9
3758
3758
3759 $ try 'tip'
3759 $ try 'tip'
3760 ('symbol', 'tip')
3760 ('symbol', 'tip')
3761 * set:
3761 * set:
3762 <baseset [9]>
3762 <baseset [9]>
3763 9
3763 9
3764
3764
3765 $ hg debugrevspec --debug --config revsetalias.'bad name'='tip' "tip"
3765 $ hg debugrevspec --debug --config revsetalias.'bad name'='tip' "tip"
3766 ('symbol', 'tip')
3766 ('symbol', 'tip')
3767 warning: bad declaration of revset alias "bad name": at 4: invalid token
3767 warning: bad declaration of revset alias "bad name": at 4: invalid token
3768 * set:
3768 * set:
3769 <baseset [9]>
3769 <baseset [9]>
3770 9
3770 9
3771 $ echo 'strictreplacing($1, $10) = $10 or desc("$1")' >> .hg/hgrc
3771 $ echo 'strictreplacing($1, $10) = $10 or desc("$1")' >> .hg/hgrc
3772 $ try 'strictreplacing("foo", tip)'
3772 $ try 'strictreplacing("foo", tip)'
3773 (func
3773 (func
3774 ('symbol', 'strictreplacing')
3774 ('symbol', 'strictreplacing')
3775 (list
3775 (list
3776 ('string', 'foo')
3776 ('string', 'foo')
3777 ('symbol', 'tip')))
3777 ('symbol', 'tip')))
3778 * expanded:
3778 * expanded:
3779 (or
3779 (or
3780 (list
3780 (list
3781 ('symbol', 'tip')
3781 ('symbol', 'tip')
3782 (func
3782 (func
3783 ('symbol', 'desc')
3783 ('symbol', 'desc')
3784 ('string', '$1'))))
3784 ('string', '$1'))))
3785 * set:
3785 * set:
3786 <addset
3786 <addset
3787 <baseset [9]>,
3787 <baseset [9]>,
3788 <filteredset
3788 <filteredset
3789 <fullreposet+ 0:10>,
3789 <fullreposet+ 0:10>,
3790 <desc '$1'>>>
3790 <desc '$1'>>>
3791 9
3791 9
3792
3792
3793 $ try 'd(2:5)'
3793 $ try 'd(2:5)'
3794 (func
3794 (func
3795 ('symbol', 'd')
3795 ('symbol', 'd')
3796 (range
3796 (range
3797 ('symbol', '2')
3797 ('symbol', '2')
3798 ('symbol', '5')))
3798 ('symbol', '5')))
3799 * expanded:
3799 * expanded:
3800 (func
3800 (func
3801 ('symbol', 'reverse')
3801 ('symbol', 'reverse')
3802 (func
3802 (func
3803 ('symbol', 'sort')
3803 ('symbol', 'sort')
3804 (list
3804 (list
3805 (range
3805 (range
3806 ('symbol', '2')
3806 ('symbol', '2')
3807 ('symbol', '5'))
3807 ('symbol', '5'))
3808 ('symbol', 'date'))))
3808 ('symbol', 'date'))))
3809 * set:
3809 * set:
3810 <baseset [4, 5, 3, 2]>
3810 <baseset [4, 5, 3, 2]>
3811 4
3811 4
3812 5
3812 5
3813 3
3813 3
3814 2
3814 2
3815 $ try 'rs(2 or 3, date)'
3815 $ try 'rs(2 or 3, date)'
3816 (func
3816 (func
3817 ('symbol', 'rs')
3817 ('symbol', 'rs')
3818 (list
3818 (list
3819 (or
3819 (or
3820 (list
3820 (list
3821 ('symbol', '2')
3821 ('symbol', '2')
3822 ('symbol', '3')))
3822 ('symbol', '3')))
3823 ('symbol', 'date')))
3823 ('symbol', 'date')))
3824 * expanded:
3824 * expanded:
3825 (func
3825 (func
3826 ('symbol', 'reverse')
3826 ('symbol', 'reverse')
3827 (func
3827 (func
3828 ('symbol', 'sort')
3828 ('symbol', 'sort')
3829 (list
3829 (list
3830 (or
3830 (or
3831 (list
3831 (list
3832 ('symbol', '2')
3832 ('symbol', '2')
3833 ('symbol', '3')))
3833 ('symbol', '3')))
3834 ('symbol', 'date'))))
3834 ('symbol', 'date'))))
3835 * set:
3835 * set:
3836 <baseset [3, 2]>
3836 <baseset [3, 2]>
3837 3
3837 3
3838 2
3838 2
3839 $ try 'rs()'
3839 $ try 'rs()'
3840 (func
3840 (func
3841 ('symbol', 'rs')
3841 ('symbol', 'rs')
3842 None)
3842 None)
3843 hg: parse error: invalid number of arguments: 0
3843 hg: parse error: invalid number of arguments: 0
3844 [255]
3844 [255]
3845 $ try 'rs(2)'
3845 $ try 'rs(2)'
3846 (func
3846 (func
3847 ('symbol', 'rs')
3847 ('symbol', 'rs')
3848 ('symbol', '2'))
3848 ('symbol', '2'))
3849 hg: parse error: invalid number of arguments: 1
3849 hg: parse error: invalid number of arguments: 1
3850 [255]
3850 [255]
3851 $ try 'rs(2, data, 7)'
3851 $ try 'rs(2, data, 7)'
3852 (func
3852 (func
3853 ('symbol', 'rs')
3853 ('symbol', 'rs')
3854 (list
3854 (list
3855 ('symbol', '2')
3855 ('symbol', '2')
3856 ('symbol', 'data')
3856 ('symbol', 'data')
3857 ('symbol', '7')))
3857 ('symbol', '7')))
3858 hg: parse error: invalid number of arguments: 3
3858 hg: parse error: invalid number of arguments: 3
3859 [255]
3859 [255]
3860 $ try 'rs4(2 or 3, x, x, date)'
3860 $ try 'rs4(2 or 3, x, x, date)'
3861 (func
3861 (func
3862 ('symbol', 'rs4')
3862 ('symbol', 'rs4')
3863 (list
3863 (list
3864 (or
3864 (or
3865 (list
3865 (list
3866 ('symbol', '2')
3866 ('symbol', '2')
3867 ('symbol', '3')))
3867 ('symbol', '3')))
3868 ('symbol', 'x')
3868 ('symbol', 'x')
3869 ('symbol', 'x')
3869 ('symbol', 'x')
3870 ('symbol', 'date')))
3870 ('symbol', 'date')))
3871 * expanded:
3871 * expanded:
3872 (func
3872 (func
3873 ('symbol', 'reverse')
3873 ('symbol', 'reverse')
3874 (func
3874 (func
3875 ('symbol', 'sort')
3875 ('symbol', 'sort')
3876 (list
3876 (list
3877 (or
3877 (or
3878 (list
3878 (list
3879 ('symbol', '2')
3879 ('symbol', '2')
3880 ('symbol', '3')))
3880 ('symbol', '3')))
3881 ('symbol', 'date'))))
3881 ('symbol', 'date'))))
3882 * set:
3882 * set:
3883 <baseset [3, 2]>
3883 <baseset [3, 2]>
3884 3
3884 3
3885 2
3885 2
3886
3886
3887 issue4553: check that revset aliases override existing hash prefix
3887 issue4553: check that revset aliases override existing hash prefix
3888
3888
3889 $ hg log -qr e
3889 $ hg log -qr e
3890 6:e0cc66ef77e8
3890 6:e0cc66ef77e8
3891
3891
3892 $ hg log -qr e --config revsetalias.e="all()"
3892 $ hg log -qr e --config revsetalias.e="all()"
3893 0:2785f51eece5
3893 0:2785f51eece5
3894 1:d75937da8da0
3894 1:d75937da8da0
3895 2:5ed5505e9f1c
3895 2:5ed5505e9f1c
3896 3:8528aa5637f2
3896 3:8528aa5637f2
3897 4:2326846efdab
3897 4:2326846efdab
3898 5:904fa392b941
3898 5:904fa392b941
3899 6:e0cc66ef77e8
3899 6:e0cc66ef77e8
3900 7:013af1973af4
3900 7:013af1973af4
3901 8:d5d0dcbdc4d9
3901 8:d5d0dcbdc4d9
3902 9:24286f4ae135
3902 9:24286f4ae135
3903
3903
3904 $ hg log -qr e: --config revsetalias.e="0"
3904 $ hg log -qr e: --config revsetalias.e="0"
3905 0:2785f51eece5
3905 0:2785f51eece5
3906 1:d75937da8da0
3906 1:d75937da8da0
3907 2:5ed5505e9f1c
3907 2:5ed5505e9f1c
3908 3:8528aa5637f2
3908 3:8528aa5637f2
3909 4:2326846efdab
3909 4:2326846efdab
3910 5:904fa392b941
3910 5:904fa392b941
3911 6:e0cc66ef77e8
3911 6:e0cc66ef77e8
3912 7:013af1973af4
3912 7:013af1973af4
3913 8:d5d0dcbdc4d9
3913 8:d5d0dcbdc4d9
3914 9:24286f4ae135
3914 9:24286f4ae135
3915
3915
3916 $ hg log -qr :e --config revsetalias.e="9"
3916 $ hg log -qr :e --config revsetalias.e="9"
3917 0:2785f51eece5
3917 0:2785f51eece5
3918 1:d75937da8da0
3918 1:d75937da8da0
3919 2:5ed5505e9f1c
3919 2:5ed5505e9f1c
3920 3:8528aa5637f2
3920 3:8528aa5637f2
3921 4:2326846efdab
3921 4:2326846efdab
3922 5:904fa392b941
3922 5:904fa392b941
3923 6:e0cc66ef77e8
3923 6:e0cc66ef77e8
3924 7:013af1973af4
3924 7:013af1973af4
3925 8:d5d0dcbdc4d9
3925 8:d5d0dcbdc4d9
3926 9:24286f4ae135
3926 9:24286f4ae135
3927
3927
3928 $ hg log -qr e:
3928 $ hg log -qr e:
3929 6:e0cc66ef77e8
3929 6:e0cc66ef77e8
3930 7:013af1973af4
3930 7:013af1973af4
3931 8:d5d0dcbdc4d9
3931 8:d5d0dcbdc4d9
3932 9:24286f4ae135
3932 9:24286f4ae135
3933
3933
3934 $ hg log -qr :e
3934 $ hg log -qr :e
3935 0:2785f51eece5
3935 0:2785f51eece5
3936 1:d75937da8da0
3936 1:d75937da8da0
3937 2:5ed5505e9f1c
3937 2:5ed5505e9f1c
3938 3:8528aa5637f2
3938 3:8528aa5637f2
3939 4:2326846efdab
3939 4:2326846efdab
3940 5:904fa392b941
3940 5:904fa392b941
3941 6:e0cc66ef77e8
3941 6:e0cc66ef77e8
3942
3942
3943 issue2549 - correct optimizations
3943 issue2549 - correct optimizations
3944
3944
3945 $ try 'limit(1 or 2 or 3, 2) and not 2'
3945 $ try 'limit(1 or 2 or 3, 2) and not 2'
3946 (and
3946 (and
3947 (func
3947 (func
3948 ('symbol', 'limit')
3948 ('symbol', 'limit')
3949 (list
3949 (list
3950 (or
3950 (or
3951 (list
3951 (list
3952 ('symbol', '1')
3952 ('symbol', '1')
3953 ('symbol', '2')
3953 ('symbol', '2')
3954 ('symbol', '3')))
3954 ('symbol', '3')))
3955 ('symbol', '2')))
3955 ('symbol', '2')))
3956 (not
3956 (not
3957 ('symbol', '2')))
3957 ('symbol', '2')))
3958 * set:
3958 * set:
3959 <filteredset
3959 <filteredset
3960 <baseset [1, 2]>,
3960 <baseset [1, 2]>,
3961 <not
3961 <not
3962 <baseset [2]>>>
3962 <baseset [2]>>>
3963 1
3963 1
3964 $ try 'max(1 or 2) and not 2'
3964 $ try 'max(1 or 2) and not 2'
3965 (and
3965 (and
3966 (func
3966 (func
3967 ('symbol', 'max')
3967 ('symbol', 'max')
3968 (or
3968 (or
3969 (list
3969 (list
3970 ('symbol', '1')
3970 ('symbol', '1')
3971 ('symbol', '2'))))
3971 ('symbol', '2'))))
3972 (not
3972 (not
3973 ('symbol', '2')))
3973 ('symbol', '2')))
3974 * set:
3974 * set:
3975 <filteredset
3975 <filteredset
3976 <baseset
3976 <baseset
3977 <max
3977 <max
3978 <fullreposet+ 0:10>,
3978 <fullreposet+ 0:10>,
3979 <baseset [1, 2]>>>,
3979 <baseset [1, 2]>>>,
3980 <not
3980 <not
3981 <baseset [2]>>>
3981 <baseset [2]>>>
3982 $ try 'min(1 or 2) and not 1'
3982 $ try 'min(1 or 2) and not 1'
3983 (and
3983 (and
3984 (func
3984 (func
3985 ('symbol', 'min')
3985 ('symbol', 'min')
3986 (or
3986 (or
3987 (list
3987 (list
3988 ('symbol', '1')
3988 ('symbol', '1')
3989 ('symbol', '2'))))
3989 ('symbol', '2'))))
3990 (not
3990 (not
3991 ('symbol', '1')))
3991 ('symbol', '1')))
3992 * set:
3992 * set:
3993 <filteredset
3993 <filteredset
3994 <baseset
3994 <baseset
3995 <min
3995 <min
3996 <fullreposet+ 0:10>,
3996 <fullreposet+ 0:10>,
3997 <baseset [1, 2]>>>,
3997 <baseset [1, 2]>>>,
3998 <not
3998 <not
3999 <baseset [1]>>>
3999 <baseset [1]>>>
4000 $ try 'last(1 or 2, 1) and not 2'
4000 $ try 'last(1 or 2, 1) and not 2'
4001 (and
4001 (and
4002 (func
4002 (func
4003 ('symbol', 'last')
4003 ('symbol', 'last')
4004 (list
4004 (list
4005 (or
4005 (or
4006 (list
4006 (list
4007 ('symbol', '1')
4007 ('symbol', '1')
4008 ('symbol', '2')))
4008 ('symbol', '2')))
4009 ('symbol', '1')))
4009 ('symbol', '1')))
4010 (not
4010 (not
4011 ('symbol', '2')))
4011 ('symbol', '2')))
4012 * set:
4012 * set:
4013 <filteredset
4013 <filteredset
4014 <baseset [2]>,
4014 <baseset [2]>,
4015 <not
4015 <not
4016 <baseset [2]>>>
4016 <baseset [2]>>>
4017
4017
4018 issue4289 - ordering of built-ins
4018 issue4289 - ordering of built-ins
4019 $ hg log -M -q -r 3:2
4019 $ hg log -M -q -r 3:2
4020 3:8528aa5637f2
4020 3:8528aa5637f2
4021 2:5ed5505e9f1c
4021 2:5ed5505e9f1c
4022
4022
4023 test revsets started with 40-chars hash (issue3669)
4023 test revsets started with 40-chars hash (issue3669)
4024
4024
4025 $ ISSUE3669_TIP=`hg tip --template '{node}'`
4025 $ ISSUE3669_TIP=`hg tip --template '{node}'`
4026 $ hg log -r "${ISSUE3669_TIP}" --template '{rev}\n'
4026 $ hg log -r "${ISSUE3669_TIP}" --template '{rev}\n'
4027 9
4027 9
4028 $ hg log -r "${ISSUE3669_TIP}^" --template '{rev}\n'
4028 $ hg log -r "${ISSUE3669_TIP}^" --template '{rev}\n'
4029 8
4029 8
4030
4030
4031 test or-ed indirect predicates (issue3775)
4031 test or-ed indirect predicates (issue3775)
4032
4032
4033 $ log '6 or 6^1' | sort
4033 $ log '6 or 6^1' | sort
4034 5
4034 5
4035 6
4035 6
4036 $ log '6^1 or 6' | sort
4036 $ log '6^1 or 6' | sort
4037 5
4037 5
4038 6
4038 6
4039 $ log '4 or 4~1' | sort
4039 $ log '4 or 4~1' | sort
4040 2
4040 2
4041 4
4041 4
4042 $ log '4~1 or 4' | sort
4042 $ log '4~1 or 4' | sort
4043 2
4043 2
4044 4
4044 4
4045 $ log '(0 or 2):(4 or 6) or 0 or 6' | sort
4045 $ log '(0 or 2):(4 or 6) or 0 or 6' | sort
4046 0
4046 0
4047 1
4047 1
4048 2
4048 2
4049 3
4049 3
4050 4
4050 4
4051 5
4051 5
4052 6
4052 6
4053 $ log '0 or 6 or (0 or 2):(4 or 6)' | sort
4053 $ log '0 or 6 or (0 or 2):(4 or 6)' | sort
4054 0
4054 0
4055 1
4055 1
4056 2
4056 2
4057 3
4057 3
4058 4
4058 4
4059 5
4059 5
4060 6
4060 6
4061
4061
4062 tests for 'remote()' predicate:
4062 tests for 'remote()' predicate:
4063 #. (csets in remote) (id) (remote)
4063 #. (csets in remote) (id) (remote)
4064 1. less than local current branch "default"
4064 1. less than local current branch "default"
4065 2. same with local specified "default"
4065 2. same with local specified "default"
4066 3. more than local specified specified
4066 3. more than local specified specified
4067
4067
4068 $ hg clone --quiet -U . ../remote3
4068 $ hg clone --quiet -U . ../remote3
4069 $ cd ../remote3
4069 $ cd ../remote3
4070 $ hg update -q 7
4070 $ hg update -q 7
4071 $ echo r > r
4071 $ echo r > r
4072 $ hg ci -Aqm 10
4072 $ hg ci -Aqm 10
4073 $ log 'remote()'
4073 $ log 'remote()'
4074 7
4074 7
4075 $ log 'remote("a-b-c-")'
4075 $ log 'remote("a-b-c-")'
4076 2
4076 2
4077 $ cd ../repo
4077 $ cd ../repo
4078 $ log 'remote(".a.b.c.", "../remote3")'
4078 $ log 'remote(".a.b.c.", "../remote3")'
4079
4079
4080 tests for concatenation of strings/symbols by "##"
4080 tests for concatenation of strings/symbols by "##"
4081
4081
4082 $ try "278 ## '5f5' ## 1ee ## 'ce5'"
4082 $ try "278 ## '5f5' ## 1ee ## 'ce5'"
4083 (_concat
4083 (_concat
4084 (_concat
4084 (_concat
4085 (_concat
4085 (_concat
4086 ('symbol', '278')
4086 ('symbol', '278')
4087 ('string', '5f5'))
4087 ('string', '5f5'))
4088 ('symbol', '1ee'))
4088 ('symbol', '1ee'))
4089 ('string', 'ce5'))
4089 ('string', 'ce5'))
4090 * concatenated:
4090 * concatenated:
4091 ('string', '2785f51eece5')
4091 ('string', '2785f51eece5')
4092 * set:
4092 * set:
4093 <baseset [0]>
4093 <baseset [0]>
4094 0
4094 0
4095
4095
4096 $ echo 'cat4($1, $2, $3, $4) = $1 ## $2 ## $3 ## $4' >> .hg/hgrc
4096 $ echo 'cat4($1, $2, $3, $4) = $1 ## $2 ## $3 ## $4' >> .hg/hgrc
4097 $ try "cat4(278, '5f5', 1ee, 'ce5')"
4097 $ try "cat4(278, '5f5', 1ee, 'ce5')"
4098 (func
4098 (func
4099 ('symbol', 'cat4')
4099 ('symbol', 'cat4')
4100 (list
4100 (list
4101 ('symbol', '278')
4101 ('symbol', '278')
4102 ('string', '5f5')
4102 ('string', '5f5')
4103 ('symbol', '1ee')
4103 ('symbol', '1ee')
4104 ('string', 'ce5')))
4104 ('string', 'ce5')))
4105 * expanded:
4105 * expanded:
4106 (_concat
4106 (_concat
4107 (_concat
4107 (_concat
4108 (_concat
4108 (_concat
4109 ('symbol', '278')
4109 ('symbol', '278')
4110 ('string', '5f5'))
4110 ('string', '5f5'))
4111 ('symbol', '1ee'))
4111 ('symbol', '1ee'))
4112 ('string', 'ce5'))
4112 ('string', 'ce5'))
4113 * concatenated:
4113 * concatenated:
4114 ('string', '2785f51eece5')
4114 ('string', '2785f51eece5')
4115 * set:
4115 * set:
4116 <baseset [0]>
4116 <baseset [0]>
4117 0
4117 0
4118
4118
4119 (check concatenation in alias nesting)
4119 (check concatenation in alias nesting)
4120
4120
4121 $ echo 'cat2($1, $2) = $1 ## $2' >> .hg/hgrc
4121 $ echo 'cat2($1, $2) = $1 ## $2' >> .hg/hgrc
4122 $ echo 'cat2x2($1, $2, $3, $4) = cat2($1 ## $2, $3 ## $4)' >> .hg/hgrc
4122 $ echo 'cat2x2($1, $2, $3, $4) = cat2($1 ## $2, $3 ## $4)' >> .hg/hgrc
4123 $ log "cat2x2(278, '5f5', 1ee, 'ce5')"
4123 $ log "cat2x2(278, '5f5', 1ee, 'ce5')"
4124 0
4124 0
4125
4125
4126 (check operator priority)
4126 (check operator priority)
4127
4127
4128 $ echo 'cat2n2($1, $2, $3, $4) = $1 ## $2 or $3 ## $4~2' >> .hg/hgrc
4128 $ echo 'cat2n2($1, $2, $3, $4) = $1 ## $2 or $3 ## $4~2' >> .hg/hgrc
4129 $ log "cat2n2(2785f5, 1eece5, 24286f, 4ae135)"
4129 $ log "cat2n2(2785f5, 1eece5, 24286f, 4ae135)"
4130 0
4130 0
4131 4
4131 4
4132
4132
4133 $ cd ..
4133 $ cd ..
4134
4134
4135 prepare repository that has "default" branches of multiple roots
4135 prepare repository that has "default" branches of multiple roots
4136
4136
4137 $ hg init namedbranch
4137 $ hg init namedbranch
4138 $ cd namedbranch
4138 $ cd namedbranch
4139
4139
4140 $ echo default0 >> a
4140 $ echo default0 >> a
4141 $ hg ci -Aqm0
4141 $ hg ci -Aqm0
4142 $ echo default1 >> a
4142 $ echo default1 >> a
4143 $ hg ci -m1
4143 $ hg ci -m1
4144
4144
4145 $ hg branch -q stable
4145 $ hg branch -q stable
4146 $ echo stable2 >> a
4146 $ echo stable2 >> a
4147 $ hg ci -m2
4147 $ hg ci -m2
4148 $ echo stable3 >> a
4148 $ echo stable3 >> a
4149 $ hg ci -m3
4149 $ hg ci -m3
4150
4150
4151 $ hg update -q null
4151 $ hg update -q null
4152 $ echo default4 >> a
4152 $ echo default4 >> a
4153 $ hg ci -Aqm4
4153 $ hg ci -Aqm4
4154 $ echo default5 >> a
4154 $ echo default5 >> a
4155 $ hg ci -m5
4155 $ hg ci -m5
4156
4156
4157 "null" revision belongs to "default" branch (issue4683)
4157 "null" revision belongs to "default" branch (issue4683)
4158
4158
4159 $ log 'branch(null)'
4159 $ log 'branch(null)'
4160 0
4160 0
4161 1
4161 1
4162 4
4162 4
4163 5
4163 5
4164
4164
4165 "null" revision belongs to "default" branch, but it shouldn't appear in set
4165 "null" revision belongs to "default" branch, but it shouldn't appear in set
4166 unless explicitly specified (issue4682)
4166 unless explicitly specified (issue4682)
4167
4167
4168 $ log 'children(branch(default))'
4168 $ log 'children(branch(default))'
4169 1
4169 1
4170 2
4170 2
4171 5
4171 5
4172
4172
4173 $ cd ..
4173 $ cd ..
4174
4174
4175 test author/desc/keyword in problematic encoding
4175 test author/desc/keyword in problematic encoding
4176 # unicode: cp932:
4176 # unicode: cp932:
4177 # u30A2 0x83 0x41(= 'A')
4177 # u30A2 0x83 0x41(= 'A')
4178 # u30C2 0x83 0x61(= 'a')
4178 # u30C2 0x83 0x61(= 'a')
4179
4179
4180 $ hg init problematicencoding
4180 $ hg init problematicencoding
4181 $ cd problematicencoding
4181 $ cd problematicencoding
4182
4182
4183 $ $PYTHON > setup.sh <<EOF
4183 $ $PYTHON > setup.sh <<EOF
4184 > print u'''
4184 > print u'''
4185 > echo a > text
4185 > echo a > text
4186 > hg add text
4186 > hg add text
4187 > hg --encoding utf-8 commit -u '\u30A2' -m none
4187 > hg --encoding utf-8 commit -u '\u30A2' -m none
4188 > echo b > text
4188 > echo b > text
4189 > hg --encoding utf-8 commit -u '\u30C2' -m none
4189 > hg --encoding utf-8 commit -u '\u30C2' -m none
4190 > echo c > text
4190 > echo c > text
4191 > hg --encoding utf-8 commit -u none -m '\u30A2'
4191 > hg --encoding utf-8 commit -u none -m '\u30A2'
4192 > echo d > text
4192 > echo d > text
4193 > hg --encoding utf-8 commit -u none -m '\u30C2'
4193 > hg --encoding utf-8 commit -u none -m '\u30C2'
4194 > '''.encode('utf-8')
4194 > '''.encode('utf-8')
4195 > EOF
4195 > EOF
4196 $ sh < setup.sh
4196 $ sh < setup.sh
4197
4197
4198 test in problematic encoding
4198 test in problematic encoding
4199 $ $PYTHON > test.sh <<EOF
4199 $ $PYTHON > test.sh <<EOF
4200 > print u'''
4200 > print u'''
4201 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30A2)'
4201 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30A2)'
4202 > echo ====
4202 > echo ====
4203 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30C2)'
4203 > hg --encoding cp932 log --template '{rev}\\n' -r 'author(\u30C2)'
4204 > echo ====
4204 > echo ====
4205 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30A2)'
4205 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30A2)'
4206 > echo ====
4206 > echo ====
4207 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30C2)'
4207 > hg --encoding cp932 log --template '{rev}\\n' -r 'desc(\u30C2)'
4208 > echo ====
4208 > echo ====
4209 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30A2)'
4209 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30A2)'
4210 > echo ====
4210 > echo ====
4211 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30C2)'
4211 > hg --encoding cp932 log --template '{rev}\\n' -r 'keyword(\u30C2)'
4212 > '''.encode('cp932')
4212 > '''.encode('cp932')
4213 > EOF
4213 > EOF
4214 $ sh < test.sh
4214 $ sh < test.sh
4215 0
4215 0
4216 ====
4216 ====
4217 1
4217 1
4218 ====
4218 ====
4219 2
4219 2
4220 ====
4220 ====
4221 3
4221 3
4222 ====
4222 ====
4223 0
4223 0
4224 2
4224 2
4225 ====
4225 ====
4226 1
4226 1
4227 3
4227 3
4228
4228
4229 test error message of bad revset
4229 test error message of bad revset
4230 $ hg log -r 'foo\\'
4230 $ hg log -r 'foo\\'
4231 hg: parse error at 3: syntax error in revset 'foo\\'
4231 hg: parse error at 3: syntax error in revset 'foo\\'
4232 [255]
4232 [255]
4233
4233
4234 $ cd ..
4234 $ cd ..
4235
4235
4236 Test that revset predicate of extension isn't loaded at failure of
4236 Test that revset predicate of extension isn't loaded at failure of
4237 loading it
4237 loading it
4238
4238
4239 $ cd repo
4239 $ cd repo
4240
4240
4241 $ cat <<EOF > $TESTTMP/custompredicate.py
4241 $ cat <<EOF > $TESTTMP/custompredicate.py
4242 > from mercurial import error, registrar, revset
4242 > from mercurial import error, registrar, revset
4243 >
4243 >
4244 > revsetpredicate = registrar.revsetpredicate()
4244 > revsetpredicate = registrar.revsetpredicate()
4245 >
4245 >
4246 > @revsetpredicate('custom1()')
4246 > @revsetpredicate('custom1()')
4247 > def custom1(repo, subset, x):
4247 > def custom1(repo, subset, x):
4248 > return revset.baseset([1])
4248 > return revset.baseset([1])
4249 >
4249 >
4250 > raise error.Abort('intentional failure of loading extension')
4250 > raise error.Abort('intentional failure of loading extension')
4251 > EOF
4251 > EOF
4252 $ cat <<EOF > .hg/hgrc
4252 $ cat <<EOF > .hg/hgrc
4253 > [extensions]
4253 > [extensions]
4254 > custompredicate = $TESTTMP/custompredicate.py
4254 > custompredicate = $TESTTMP/custompredicate.py
4255 > EOF
4255 > EOF
4256
4256
4257 $ hg debugrevspec "custom1()"
4257 $ hg debugrevspec "custom1()"
4258 *** failed to import extension custompredicate from $TESTTMP/custompredicate.py: intentional failure of loading extension
4258 *** failed to import extension custompredicate from $TESTTMP/custompredicate.py: intentional failure of loading extension
4259 hg: parse error: unknown identifier: custom1
4259 hg: parse error: unknown identifier: custom1
4260 [255]
4260 [255]
4261
4261
4262 Test repo.anyrevs with customized revset overrides
4263
4264 $ cat > $TESTTMP/printprevset.py <<EOF
4265 > from mercurial import encoding
4266 > def reposetup(ui, repo):
4267 > alias = {}
4268 > p = encoding.environ.get('P')
4269 > if p:
4270 > alias['P'] = p
4271 > revs = repo.anyrevs(['P'], user=True, localalias=alias)
4272 > ui.write('P=%r' % list(revs))
4273 > EOF
4274
4275 $ cat >> .hg/hgrc <<EOF
4276 > custompredicate = !
4277 > printprevset = $TESTTMP/printprevset.py
4278 > EOF
4279
4280 $ hg --config revsetalias.P=1 log -r . -T '\n'
4281 P=[1]
4282 $ P=3 hg --config revsetalias.P=2 log -r . -T '\n'
4283 P=[3]
4284
4262 $ cd ..
4285 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now