##// END OF EJS Templates
exchange: drop support for lock-based unbundling (BC)...
Gregory Szorc -
r33667:fda0867c default
parent child Browse files
Show More
@@ -1,2022 +1,2009 b''
1 # exchange.py - utility to exchange data between repos.
1 # exchange.py - utility to exchange data between repos.
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
12
13 from .i18n import _
13 from .i18n import _
14 from .node import (
14 from .node import (
15 hex,
15 hex,
16 nullid,
16 nullid,
17 )
17 )
18 from . import (
18 from . import (
19 bookmarks as bookmod,
19 bookmarks as bookmod,
20 bundle2,
20 bundle2,
21 changegroup,
21 changegroup,
22 discovery,
22 discovery,
23 error,
23 error,
24 lock as lockmod,
24 lock as lockmod,
25 obsolete,
25 obsolete,
26 phases,
26 phases,
27 pushkey,
27 pushkey,
28 pycompat,
28 pycompat,
29 scmutil,
29 scmutil,
30 sslutil,
30 sslutil,
31 streamclone,
31 streamclone,
32 url as urlmod,
32 url as urlmod,
33 util,
33 util,
34 )
34 )
35
35
36 urlerr = util.urlerr
36 urlerr = util.urlerr
37 urlreq = util.urlreq
37 urlreq = util.urlreq
38
38
39 # Maps bundle version human names to changegroup versions.
39 # Maps bundle version human names to changegroup versions.
40 _bundlespeccgversions = {'v1': '01',
40 _bundlespeccgversions = {'v1': '01',
41 'v2': '02',
41 'v2': '02',
42 'packed1': 's1',
42 'packed1': 's1',
43 'bundle2': '02', #legacy
43 'bundle2': '02', #legacy
44 }
44 }
45
45
46 # Compression engines allowed in version 1. THIS SHOULD NEVER CHANGE.
46 # Compression engines allowed in version 1. THIS SHOULD NEVER CHANGE.
47 _bundlespecv1compengines = {'gzip', 'bzip2', 'none'}
47 _bundlespecv1compengines = {'gzip', 'bzip2', 'none'}
48
48
49 def parsebundlespec(repo, spec, strict=True, externalnames=False):
49 def parsebundlespec(repo, spec, strict=True, externalnames=False):
50 """Parse a bundle string specification into parts.
50 """Parse a bundle string specification into parts.
51
51
52 Bundle specifications denote a well-defined bundle/exchange format.
52 Bundle specifications denote a well-defined bundle/exchange format.
53 The content of a given specification should not change over time in
53 The content of a given specification should not change over time in
54 order to ensure that bundles produced by a newer version of Mercurial are
54 order to ensure that bundles produced by a newer version of Mercurial are
55 readable from an older version.
55 readable from an older version.
56
56
57 The string currently has the form:
57 The string currently has the form:
58
58
59 <compression>-<type>[;<parameter0>[;<parameter1>]]
59 <compression>-<type>[;<parameter0>[;<parameter1>]]
60
60
61 Where <compression> is one of the supported compression formats
61 Where <compression> is one of the supported compression formats
62 and <type> is (currently) a version string. A ";" can follow the type and
62 and <type> is (currently) a version string. A ";" can follow the type and
63 all text afterwards is interpreted as URI encoded, ";" delimited key=value
63 all text afterwards is interpreted as URI encoded, ";" delimited key=value
64 pairs.
64 pairs.
65
65
66 If ``strict`` is True (the default) <compression> is required. Otherwise,
66 If ``strict`` is True (the default) <compression> is required. Otherwise,
67 it is optional.
67 it is optional.
68
68
69 If ``externalnames`` is False (the default), the human-centric names will
69 If ``externalnames`` is False (the default), the human-centric names will
70 be converted to their internal representation.
70 be converted to their internal representation.
71
71
72 Returns a 3-tuple of (compression, version, parameters). Compression will
72 Returns a 3-tuple of (compression, version, parameters). Compression will
73 be ``None`` if not in strict mode and a compression isn't defined.
73 be ``None`` if not in strict mode and a compression isn't defined.
74
74
75 An ``InvalidBundleSpecification`` is raised when the specification is
75 An ``InvalidBundleSpecification`` is raised when the specification is
76 not syntactically well formed.
76 not syntactically well formed.
77
77
78 An ``UnsupportedBundleSpecification`` is raised when the compression or
78 An ``UnsupportedBundleSpecification`` is raised when the compression or
79 bundle type/version is not recognized.
79 bundle type/version is not recognized.
80
80
81 Note: this function will likely eventually return a more complex data
81 Note: this function will likely eventually return a more complex data
82 structure, including bundle2 part information.
82 structure, including bundle2 part information.
83 """
83 """
84 def parseparams(s):
84 def parseparams(s):
85 if ';' not in s:
85 if ';' not in s:
86 return s, {}
86 return s, {}
87
87
88 params = {}
88 params = {}
89 version, paramstr = s.split(';', 1)
89 version, paramstr = s.split(';', 1)
90
90
91 for p in paramstr.split(';'):
91 for p in paramstr.split(';'):
92 if '=' not in p:
92 if '=' not in p:
93 raise error.InvalidBundleSpecification(
93 raise error.InvalidBundleSpecification(
94 _('invalid bundle specification: '
94 _('invalid bundle specification: '
95 'missing "=" in parameter: %s') % p)
95 'missing "=" in parameter: %s') % p)
96
96
97 key, value = p.split('=', 1)
97 key, value = p.split('=', 1)
98 key = urlreq.unquote(key)
98 key = urlreq.unquote(key)
99 value = urlreq.unquote(value)
99 value = urlreq.unquote(value)
100 params[key] = value
100 params[key] = value
101
101
102 return version, params
102 return version, params
103
103
104
104
105 if strict and '-' not in spec:
105 if strict and '-' not in spec:
106 raise error.InvalidBundleSpecification(
106 raise error.InvalidBundleSpecification(
107 _('invalid bundle specification; '
107 _('invalid bundle specification; '
108 'must be prefixed with compression: %s') % spec)
108 'must be prefixed with compression: %s') % spec)
109
109
110 if '-' in spec:
110 if '-' in spec:
111 compression, version = spec.split('-', 1)
111 compression, version = spec.split('-', 1)
112
112
113 if compression not in util.compengines.supportedbundlenames:
113 if compression not in util.compengines.supportedbundlenames:
114 raise error.UnsupportedBundleSpecification(
114 raise error.UnsupportedBundleSpecification(
115 _('%s compression is not supported') % compression)
115 _('%s compression is not supported') % compression)
116
116
117 version, params = parseparams(version)
117 version, params = parseparams(version)
118
118
119 if version not in _bundlespeccgversions:
119 if version not in _bundlespeccgversions:
120 raise error.UnsupportedBundleSpecification(
120 raise error.UnsupportedBundleSpecification(
121 _('%s is not a recognized bundle version') % version)
121 _('%s is not a recognized bundle version') % version)
122 else:
122 else:
123 # Value could be just the compression or just the version, in which
123 # Value could be just the compression or just the version, in which
124 # case some defaults are assumed (but only when not in strict mode).
124 # case some defaults are assumed (but only when not in strict mode).
125 assert not strict
125 assert not strict
126
126
127 spec, params = parseparams(spec)
127 spec, params = parseparams(spec)
128
128
129 if spec in util.compengines.supportedbundlenames:
129 if spec in util.compengines.supportedbundlenames:
130 compression = spec
130 compression = spec
131 version = 'v1'
131 version = 'v1'
132 # Generaldelta repos require v2.
132 # Generaldelta repos require v2.
133 if 'generaldelta' in repo.requirements:
133 if 'generaldelta' in repo.requirements:
134 version = 'v2'
134 version = 'v2'
135 # Modern compression engines require v2.
135 # Modern compression engines require v2.
136 if compression not in _bundlespecv1compengines:
136 if compression not in _bundlespecv1compengines:
137 version = 'v2'
137 version = 'v2'
138 elif spec in _bundlespeccgversions:
138 elif spec in _bundlespeccgversions:
139 if spec == 'packed1':
139 if spec == 'packed1':
140 compression = 'none'
140 compression = 'none'
141 else:
141 else:
142 compression = 'bzip2'
142 compression = 'bzip2'
143 version = spec
143 version = spec
144 else:
144 else:
145 raise error.UnsupportedBundleSpecification(
145 raise error.UnsupportedBundleSpecification(
146 _('%s is not a recognized bundle specification') % spec)
146 _('%s is not a recognized bundle specification') % spec)
147
147
148 # Bundle version 1 only supports a known set of compression engines.
148 # Bundle version 1 only supports a known set of compression engines.
149 if version == 'v1' and compression not in _bundlespecv1compengines:
149 if version == 'v1' and compression not in _bundlespecv1compengines:
150 raise error.UnsupportedBundleSpecification(
150 raise error.UnsupportedBundleSpecification(
151 _('compression engine %s is not supported on v1 bundles') %
151 _('compression engine %s is not supported on v1 bundles') %
152 compression)
152 compression)
153
153
154 # The specification for packed1 can optionally declare the data formats
154 # The specification for packed1 can optionally declare the data formats
155 # required to apply it. If we see this metadata, compare against what the
155 # required to apply it. If we see this metadata, compare against what the
156 # repo supports and error if the bundle isn't compatible.
156 # repo supports and error if the bundle isn't compatible.
157 if version == 'packed1' and 'requirements' in params:
157 if version == 'packed1' and 'requirements' in params:
158 requirements = set(params['requirements'].split(','))
158 requirements = set(params['requirements'].split(','))
159 missingreqs = requirements - repo.supportedformats
159 missingreqs = requirements - repo.supportedformats
160 if missingreqs:
160 if missingreqs:
161 raise error.UnsupportedBundleSpecification(
161 raise error.UnsupportedBundleSpecification(
162 _('missing support for repository features: %s') %
162 _('missing support for repository features: %s') %
163 ', '.join(sorted(missingreqs)))
163 ', '.join(sorted(missingreqs)))
164
164
165 if not externalnames:
165 if not externalnames:
166 engine = util.compengines.forbundlename(compression)
166 engine = util.compengines.forbundlename(compression)
167 compression = engine.bundletype()[1]
167 compression = engine.bundletype()[1]
168 version = _bundlespeccgversions[version]
168 version = _bundlespeccgversions[version]
169 return compression, version, params
169 return compression, version, params
170
170
171 def readbundle(ui, fh, fname, vfs=None):
171 def readbundle(ui, fh, fname, vfs=None):
172 header = changegroup.readexactly(fh, 4)
172 header = changegroup.readexactly(fh, 4)
173
173
174 alg = None
174 alg = None
175 if not fname:
175 if not fname:
176 fname = "stream"
176 fname = "stream"
177 if not header.startswith('HG') and header.startswith('\0'):
177 if not header.startswith('HG') and header.startswith('\0'):
178 fh = changegroup.headerlessfixup(fh, header)
178 fh = changegroup.headerlessfixup(fh, header)
179 header = "HG10"
179 header = "HG10"
180 alg = 'UN'
180 alg = 'UN'
181 elif vfs:
181 elif vfs:
182 fname = vfs.join(fname)
182 fname = vfs.join(fname)
183
183
184 magic, version = header[0:2], header[2:4]
184 magic, version = header[0:2], header[2:4]
185
185
186 if magic != 'HG':
186 if magic != 'HG':
187 raise error.Abort(_('%s: not a Mercurial bundle') % fname)
187 raise error.Abort(_('%s: not a Mercurial bundle') % fname)
188 if version == '10':
188 if version == '10':
189 if alg is None:
189 if alg is None:
190 alg = changegroup.readexactly(fh, 2)
190 alg = changegroup.readexactly(fh, 2)
191 return changegroup.cg1unpacker(fh, alg)
191 return changegroup.cg1unpacker(fh, alg)
192 elif version.startswith('2'):
192 elif version.startswith('2'):
193 return bundle2.getunbundler(ui, fh, magicstring=magic + version)
193 return bundle2.getunbundler(ui, fh, magicstring=magic + version)
194 elif version == 'S1':
194 elif version == 'S1':
195 return streamclone.streamcloneapplier(fh)
195 return streamclone.streamcloneapplier(fh)
196 else:
196 else:
197 raise error.Abort(_('%s: unknown bundle version %s') % (fname, version))
197 raise error.Abort(_('%s: unknown bundle version %s') % (fname, version))
198
198
199 def getbundlespec(ui, fh):
199 def getbundlespec(ui, fh):
200 """Infer the bundlespec from a bundle file handle.
200 """Infer the bundlespec from a bundle file handle.
201
201
202 The input file handle is seeked and the original seek position is not
202 The input file handle is seeked and the original seek position is not
203 restored.
203 restored.
204 """
204 """
205 def speccompression(alg):
205 def speccompression(alg):
206 try:
206 try:
207 return util.compengines.forbundletype(alg).bundletype()[0]
207 return util.compengines.forbundletype(alg).bundletype()[0]
208 except KeyError:
208 except KeyError:
209 return None
209 return None
210
210
211 b = readbundle(ui, fh, None)
211 b = readbundle(ui, fh, None)
212 if isinstance(b, changegroup.cg1unpacker):
212 if isinstance(b, changegroup.cg1unpacker):
213 alg = b._type
213 alg = b._type
214 if alg == '_truncatedBZ':
214 if alg == '_truncatedBZ':
215 alg = 'BZ'
215 alg = 'BZ'
216 comp = speccompression(alg)
216 comp = speccompression(alg)
217 if not comp:
217 if not comp:
218 raise error.Abort(_('unknown compression algorithm: %s') % alg)
218 raise error.Abort(_('unknown compression algorithm: %s') % alg)
219 return '%s-v1' % comp
219 return '%s-v1' % comp
220 elif isinstance(b, bundle2.unbundle20):
220 elif isinstance(b, bundle2.unbundle20):
221 if 'Compression' in b.params:
221 if 'Compression' in b.params:
222 comp = speccompression(b.params['Compression'])
222 comp = speccompression(b.params['Compression'])
223 if not comp:
223 if not comp:
224 raise error.Abort(_('unknown compression algorithm: %s') % comp)
224 raise error.Abort(_('unknown compression algorithm: %s') % comp)
225 else:
225 else:
226 comp = 'none'
226 comp = 'none'
227
227
228 version = None
228 version = None
229 for part in b.iterparts():
229 for part in b.iterparts():
230 if part.type == 'changegroup':
230 if part.type == 'changegroup':
231 version = part.params['version']
231 version = part.params['version']
232 if version in ('01', '02'):
232 if version in ('01', '02'):
233 version = 'v2'
233 version = 'v2'
234 else:
234 else:
235 raise error.Abort(_('changegroup version %s does not have '
235 raise error.Abort(_('changegroup version %s does not have '
236 'a known bundlespec') % version,
236 'a known bundlespec') % version,
237 hint=_('try upgrading your Mercurial '
237 hint=_('try upgrading your Mercurial '
238 'client'))
238 'client'))
239
239
240 if not version:
240 if not version:
241 raise error.Abort(_('could not identify changegroup version in '
241 raise error.Abort(_('could not identify changegroup version in '
242 'bundle'))
242 'bundle'))
243
243
244 return '%s-%s' % (comp, version)
244 return '%s-%s' % (comp, version)
245 elif isinstance(b, streamclone.streamcloneapplier):
245 elif isinstance(b, streamclone.streamcloneapplier):
246 requirements = streamclone.readbundle1header(fh)[2]
246 requirements = streamclone.readbundle1header(fh)[2]
247 params = 'requirements=%s' % ','.join(sorted(requirements))
247 params = 'requirements=%s' % ','.join(sorted(requirements))
248 return 'none-packed1;%s' % urlreq.quote(params)
248 return 'none-packed1;%s' % urlreq.quote(params)
249 else:
249 else:
250 raise error.Abort(_('unknown bundle type: %s') % b)
250 raise error.Abort(_('unknown bundle type: %s') % b)
251
251
252 def _computeoutgoing(repo, heads, common):
252 def _computeoutgoing(repo, heads, common):
253 """Computes which revs are outgoing given a set of common
253 """Computes which revs are outgoing given a set of common
254 and a set of heads.
254 and a set of heads.
255
255
256 This is a separate function so extensions can have access to
256 This is a separate function so extensions can have access to
257 the logic.
257 the logic.
258
258
259 Returns a discovery.outgoing object.
259 Returns a discovery.outgoing object.
260 """
260 """
261 cl = repo.changelog
261 cl = repo.changelog
262 if common:
262 if common:
263 hasnode = cl.hasnode
263 hasnode = cl.hasnode
264 common = [n for n in common if hasnode(n)]
264 common = [n for n in common if hasnode(n)]
265 else:
265 else:
266 common = [nullid]
266 common = [nullid]
267 if not heads:
267 if not heads:
268 heads = cl.heads()
268 heads = cl.heads()
269 return discovery.outgoing(repo, common, heads)
269 return discovery.outgoing(repo, common, heads)
270
270
271 def _forcebundle1(op):
271 def _forcebundle1(op):
272 """return true if a pull/push must use bundle1
272 """return true if a pull/push must use bundle1
273
273
274 This function is used to allow testing of the older bundle version"""
274 This function is used to allow testing of the older bundle version"""
275 ui = op.repo.ui
275 ui = op.repo.ui
276 forcebundle1 = False
276 forcebundle1 = False
277 # The goal is this config is to allow developer to choose the bundle
277 # The goal is this config is to allow developer to choose the bundle
278 # version used during exchanged. This is especially handy during test.
278 # version used during exchanged. This is especially handy during test.
279 # Value is a list of bundle version to be picked from, highest version
279 # Value is a list of bundle version to be picked from, highest version
280 # should be used.
280 # should be used.
281 #
281 #
282 # developer config: devel.legacy.exchange
282 # developer config: devel.legacy.exchange
283 exchange = ui.configlist('devel', 'legacy.exchange')
283 exchange = ui.configlist('devel', 'legacy.exchange')
284 forcebundle1 = 'bundle2' not in exchange and 'bundle1' in exchange
284 forcebundle1 = 'bundle2' not in exchange and 'bundle1' in exchange
285 return forcebundle1 or not op.remote.capable('bundle2')
285 return forcebundle1 or not op.remote.capable('bundle2')
286
286
287 class pushoperation(object):
287 class pushoperation(object):
288 """A object that represent a single push operation
288 """A object that represent a single push operation
289
289
290 Its purpose is to carry push related state and very common operations.
290 Its purpose is to carry push related state and very common operations.
291
291
292 A new pushoperation should be created at the beginning of each push and
292 A new pushoperation should be created at the beginning of each push and
293 discarded afterward.
293 discarded afterward.
294 """
294 """
295
295
296 def __init__(self, repo, remote, force=False, revs=None, newbranch=False,
296 def __init__(self, repo, remote, force=False, revs=None, newbranch=False,
297 bookmarks=()):
297 bookmarks=()):
298 # repo we push from
298 # repo we push from
299 self.repo = repo
299 self.repo = repo
300 self.ui = repo.ui
300 self.ui = repo.ui
301 # repo we push to
301 # repo we push to
302 self.remote = remote
302 self.remote = remote
303 # force option provided
303 # force option provided
304 self.force = force
304 self.force = force
305 # revs to be pushed (None is "all")
305 # revs to be pushed (None is "all")
306 self.revs = revs
306 self.revs = revs
307 # bookmark explicitly pushed
307 # bookmark explicitly pushed
308 self.bookmarks = bookmarks
308 self.bookmarks = bookmarks
309 # allow push of new branch
309 # allow push of new branch
310 self.newbranch = newbranch
310 self.newbranch = newbranch
311 # did a local lock get acquired?
311 # did a local lock get acquired?
312 self.locallocked = None
312 self.locallocked = None
313 # step already performed
313 # step already performed
314 # (used to check what steps have been already performed through bundle2)
314 # (used to check what steps have been already performed through bundle2)
315 self.stepsdone = set()
315 self.stepsdone = set()
316 # Integer version of the changegroup push result
316 # Integer version of the changegroup push result
317 # - None means nothing to push
317 # - None means nothing to push
318 # - 0 means HTTP error
318 # - 0 means HTTP error
319 # - 1 means we pushed and remote head count is unchanged *or*
319 # - 1 means we pushed and remote head count is unchanged *or*
320 # we have outgoing changesets but refused to push
320 # we have outgoing changesets but refused to push
321 # - other values as described by addchangegroup()
321 # - other values as described by addchangegroup()
322 self.cgresult = None
322 self.cgresult = None
323 # Boolean value for the bookmark push
323 # Boolean value for the bookmark push
324 self.bkresult = None
324 self.bkresult = None
325 # discover.outgoing object (contains common and outgoing data)
325 # discover.outgoing object (contains common and outgoing data)
326 self.outgoing = None
326 self.outgoing = None
327 # all remote topological heads before the push
327 # all remote topological heads before the push
328 self.remoteheads = None
328 self.remoteheads = None
329 # Details of the remote branch pre and post push
329 # Details of the remote branch pre and post push
330 #
330 #
331 # mapping: {'branch': ([remoteheads],
331 # mapping: {'branch': ([remoteheads],
332 # [newheads],
332 # [newheads],
333 # [unsyncedheads],
333 # [unsyncedheads],
334 # [discardedheads])}
334 # [discardedheads])}
335 # - branch: the branch name
335 # - branch: the branch name
336 # - remoteheads: the list of remote heads known locally
336 # - remoteheads: the list of remote heads known locally
337 # None if the branch is new
337 # None if the branch is new
338 # - newheads: the new remote heads (known locally) with outgoing pushed
338 # - newheads: the new remote heads (known locally) with outgoing pushed
339 # - unsyncedheads: the list of remote heads unknown locally.
339 # - unsyncedheads: the list of remote heads unknown locally.
340 # - discardedheads: the list of remote heads made obsolete by the push
340 # - discardedheads: the list of remote heads made obsolete by the push
341 self.pushbranchmap = None
341 self.pushbranchmap = None
342 # testable as a boolean indicating if any nodes are missing locally.
342 # testable as a boolean indicating if any nodes are missing locally.
343 self.incoming = None
343 self.incoming = None
344 # phases changes that must be pushed along side the changesets
344 # phases changes that must be pushed along side the changesets
345 self.outdatedphases = None
345 self.outdatedphases = None
346 # phases changes that must be pushed if changeset push fails
346 # phases changes that must be pushed if changeset push fails
347 self.fallbackoutdatedphases = None
347 self.fallbackoutdatedphases = None
348 # outgoing obsmarkers
348 # outgoing obsmarkers
349 self.outobsmarkers = set()
349 self.outobsmarkers = set()
350 # outgoing bookmarks
350 # outgoing bookmarks
351 self.outbookmarks = []
351 self.outbookmarks = []
352 # transaction manager
352 # transaction manager
353 self.trmanager = None
353 self.trmanager = None
354 # map { pushkey partid -> callback handling failure}
354 # map { pushkey partid -> callback handling failure}
355 # used to handle exception from mandatory pushkey part failure
355 # used to handle exception from mandatory pushkey part failure
356 self.pkfailcb = {}
356 self.pkfailcb = {}
357
357
358 @util.propertycache
358 @util.propertycache
359 def futureheads(self):
359 def futureheads(self):
360 """future remote heads if the changeset push succeeds"""
360 """future remote heads if the changeset push succeeds"""
361 return self.outgoing.missingheads
361 return self.outgoing.missingheads
362
362
363 @util.propertycache
363 @util.propertycache
364 def fallbackheads(self):
364 def fallbackheads(self):
365 """future remote heads if the changeset push fails"""
365 """future remote heads if the changeset push fails"""
366 if self.revs is None:
366 if self.revs is None:
367 # not target to push, all common are relevant
367 # not target to push, all common are relevant
368 return self.outgoing.commonheads
368 return self.outgoing.commonheads
369 unfi = self.repo.unfiltered()
369 unfi = self.repo.unfiltered()
370 # I want cheads = heads(::missingheads and ::commonheads)
370 # I want cheads = heads(::missingheads and ::commonheads)
371 # (missingheads is revs with secret changeset filtered out)
371 # (missingheads is revs with secret changeset filtered out)
372 #
372 #
373 # This can be expressed as:
373 # This can be expressed as:
374 # cheads = ( (missingheads and ::commonheads)
374 # cheads = ( (missingheads and ::commonheads)
375 # + (commonheads and ::missingheads))"
375 # + (commonheads and ::missingheads))"
376 # )
376 # )
377 #
377 #
378 # while trying to push we already computed the following:
378 # while trying to push we already computed the following:
379 # common = (::commonheads)
379 # common = (::commonheads)
380 # missing = ((commonheads::missingheads) - commonheads)
380 # missing = ((commonheads::missingheads) - commonheads)
381 #
381 #
382 # We can pick:
382 # We can pick:
383 # * missingheads part of common (::commonheads)
383 # * missingheads part of common (::commonheads)
384 common = self.outgoing.common
384 common = self.outgoing.common
385 nm = self.repo.changelog.nodemap
385 nm = self.repo.changelog.nodemap
386 cheads = [node for node in self.revs if nm[node] in common]
386 cheads = [node for node in self.revs if nm[node] in common]
387 # and
387 # and
388 # * commonheads parents on missing
388 # * commonheads parents on missing
389 revset = unfi.set('%ln and parents(roots(%ln))',
389 revset = unfi.set('%ln and parents(roots(%ln))',
390 self.outgoing.commonheads,
390 self.outgoing.commonheads,
391 self.outgoing.missing)
391 self.outgoing.missing)
392 cheads.extend(c.node() for c in revset)
392 cheads.extend(c.node() for c in revset)
393 return cheads
393 return cheads
394
394
395 @property
395 @property
396 def commonheads(self):
396 def commonheads(self):
397 """set of all common heads after changeset bundle push"""
397 """set of all common heads after changeset bundle push"""
398 if self.cgresult:
398 if self.cgresult:
399 return self.futureheads
399 return self.futureheads
400 else:
400 else:
401 return self.fallbackheads
401 return self.fallbackheads
402
402
403 # mapping of message used when pushing bookmark
403 # mapping of message used when pushing bookmark
404 bookmsgmap = {'update': (_("updating bookmark %s\n"),
404 bookmsgmap = {'update': (_("updating bookmark %s\n"),
405 _('updating bookmark %s failed!\n')),
405 _('updating bookmark %s failed!\n')),
406 'export': (_("exporting bookmark %s\n"),
406 'export': (_("exporting bookmark %s\n"),
407 _('exporting bookmark %s failed!\n')),
407 _('exporting bookmark %s failed!\n')),
408 'delete': (_("deleting remote bookmark %s\n"),
408 'delete': (_("deleting remote bookmark %s\n"),
409 _('deleting remote bookmark %s failed!\n')),
409 _('deleting remote bookmark %s failed!\n')),
410 }
410 }
411
411
412
412
413 def push(repo, remote, force=False, revs=None, newbranch=False, bookmarks=(),
413 def push(repo, remote, force=False, revs=None, newbranch=False, bookmarks=(),
414 opargs=None):
414 opargs=None):
415 '''Push outgoing changesets (limited by revs) from a local
415 '''Push outgoing changesets (limited by revs) from a local
416 repository to remote. Return an integer:
416 repository to remote. Return an integer:
417 - None means nothing to push
417 - None means nothing to push
418 - 0 means HTTP error
418 - 0 means HTTP error
419 - 1 means we pushed and remote head count is unchanged *or*
419 - 1 means we pushed and remote head count is unchanged *or*
420 we have outgoing changesets but refused to push
420 we have outgoing changesets but refused to push
421 - other values as described by addchangegroup()
421 - other values as described by addchangegroup()
422 '''
422 '''
423 if opargs is None:
423 if opargs is None:
424 opargs = {}
424 opargs = {}
425 pushop = pushoperation(repo, remote, force, revs, newbranch, bookmarks,
425 pushop = pushoperation(repo, remote, force, revs, newbranch, bookmarks,
426 **opargs)
426 **opargs)
427 if pushop.remote.local():
427 if pushop.remote.local():
428 missing = (set(pushop.repo.requirements)
428 missing = (set(pushop.repo.requirements)
429 - pushop.remote.local().supported)
429 - pushop.remote.local().supported)
430 if missing:
430 if missing:
431 msg = _("required features are not"
431 msg = _("required features are not"
432 " supported in the destination:"
432 " supported in the destination:"
433 " %s") % (', '.join(sorted(missing)))
433 " %s") % (', '.join(sorted(missing)))
434 raise error.Abort(msg)
434 raise error.Abort(msg)
435
435
436 # there are two ways to push to remote repo:
437 #
438 # addchangegroup assumes local user can lock remote
439 # repo (local filesystem, old ssh servers).
440 #
441 # unbundle assumes local user cannot lock remote repo (new ssh
442 # servers, http servers).
443
444 if not pushop.remote.canpush():
436 if not pushop.remote.canpush():
445 raise error.Abort(_("destination does not support push"))
437 raise error.Abort(_("destination does not support push"))
438
439 if not pushop.remote.capable('unbundle'):
440 raise error.Abort(_('cannot push: destination does not support the '
441 'unbundle wire protocol command'))
442
446 # get local lock as we might write phase data
443 # get local lock as we might write phase data
447 localwlock = locallock = None
444 localwlock = locallock = None
448 try:
445 try:
449 # bundle2 push may receive a reply bundle touching bookmarks or other
446 # bundle2 push may receive a reply bundle touching bookmarks or other
450 # things requiring the wlock. Take it now to ensure proper ordering.
447 # things requiring the wlock. Take it now to ensure proper ordering.
451 maypushback = pushop.ui.configbool('experimental', 'bundle2.pushback')
448 maypushback = pushop.ui.configbool('experimental', 'bundle2.pushback')
452 if (not _forcebundle1(pushop)) and maypushback:
449 if (not _forcebundle1(pushop)) and maypushback:
453 localwlock = pushop.repo.wlock()
450 localwlock = pushop.repo.wlock()
454 locallock = pushop.repo.lock()
451 locallock = pushop.repo.lock()
455 pushop.locallocked = True
452 pushop.locallocked = True
456 except IOError as err:
453 except IOError as err:
457 pushop.locallocked = False
454 pushop.locallocked = False
458 if err.errno != errno.EACCES:
455 if err.errno != errno.EACCES:
459 raise
456 raise
460 # source repo cannot be locked.
457 # source repo cannot be locked.
461 # We do not abort the push, but just disable the local phase
458 # We do not abort the push, but just disable the local phase
462 # synchronisation.
459 # synchronisation.
463 msg = 'cannot lock source repository: %s\n' % err
460 msg = 'cannot lock source repository: %s\n' % err
464 pushop.ui.debug(msg)
461 pushop.ui.debug(msg)
465 try:
462 try:
466 if pushop.locallocked:
463 if pushop.locallocked:
467 pushop.trmanager = transactionmanager(pushop.repo,
464 pushop.trmanager = transactionmanager(pushop.repo,
468 'push-response',
465 'push-response',
469 pushop.remote.url())
466 pushop.remote.url())
470 pushop.repo.checkpush(pushop)
467 pushop.repo.checkpush(pushop)
471 lock = None
472 unbundle = pushop.remote.capable('unbundle')
473 if not unbundle:
474 lock = pushop.remote.lock()
475 try:
476 _pushdiscovery(pushop)
468 _pushdiscovery(pushop)
477 if not _forcebundle1(pushop):
469 if not _forcebundle1(pushop):
478 _pushbundle2(pushop)
470 _pushbundle2(pushop)
479 _pushchangeset(pushop)
471 _pushchangeset(pushop)
480 _pushsyncphase(pushop)
472 _pushsyncphase(pushop)
481 _pushobsolete(pushop)
473 _pushobsolete(pushop)
482 _pushbookmark(pushop)
474 _pushbookmark(pushop)
483 finally:
475
484 if lock is not None:
485 lock.release()
486 if pushop.trmanager:
476 if pushop.trmanager:
487 pushop.trmanager.close()
477 pushop.trmanager.close()
488 finally:
478 finally:
489 if pushop.trmanager:
479 if pushop.trmanager:
490 pushop.trmanager.release()
480 pushop.trmanager.release()
491 if locallock is not None:
481 if locallock is not None:
492 locallock.release()
482 locallock.release()
493 if localwlock is not None:
483 if localwlock is not None:
494 localwlock.release()
484 localwlock.release()
495
485
496 return pushop
486 return pushop
497
487
498 # list of steps to perform discovery before push
488 # list of steps to perform discovery before push
499 pushdiscoveryorder = []
489 pushdiscoveryorder = []
500
490
501 # Mapping between step name and function
491 # Mapping between step name and function
502 #
492 #
503 # This exists to help extensions wrap steps if necessary
493 # This exists to help extensions wrap steps if necessary
504 pushdiscoverymapping = {}
494 pushdiscoverymapping = {}
505
495
506 def pushdiscovery(stepname):
496 def pushdiscovery(stepname):
507 """decorator for function performing discovery before push
497 """decorator for function performing discovery before push
508
498
509 The function is added to the step -> function mapping and appended to the
499 The function is added to the step -> function mapping and appended to the
510 list of steps. Beware that decorated function will be added in order (this
500 list of steps. Beware that decorated function will be added in order (this
511 may matter).
501 may matter).
512
502
513 You can only use this decorator for a new step, if you want to wrap a step
503 You can only use this decorator for a new step, if you want to wrap a step
514 from an extension, change the pushdiscovery dictionary directly."""
504 from an extension, change the pushdiscovery dictionary directly."""
515 def dec(func):
505 def dec(func):
516 assert stepname not in pushdiscoverymapping
506 assert stepname not in pushdiscoverymapping
517 pushdiscoverymapping[stepname] = func
507 pushdiscoverymapping[stepname] = func
518 pushdiscoveryorder.append(stepname)
508 pushdiscoveryorder.append(stepname)
519 return func
509 return func
520 return dec
510 return dec
521
511
522 def _pushdiscovery(pushop):
512 def _pushdiscovery(pushop):
523 """Run all discovery steps"""
513 """Run all discovery steps"""
524 for stepname in pushdiscoveryorder:
514 for stepname in pushdiscoveryorder:
525 step = pushdiscoverymapping[stepname]
515 step = pushdiscoverymapping[stepname]
526 step(pushop)
516 step(pushop)
527
517
528 @pushdiscovery('changeset')
518 @pushdiscovery('changeset')
529 def _pushdiscoverychangeset(pushop):
519 def _pushdiscoverychangeset(pushop):
530 """discover the changeset that need to be pushed"""
520 """discover the changeset that need to be pushed"""
531 fci = discovery.findcommonincoming
521 fci = discovery.findcommonincoming
532 commoninc = fci(pushop.repo, pushop.remote, force=pushop.force)
522 commoninc = fci(pushop.repo, pushop.remote, force=pushop.force)
533 common, inc, remoteheads = commoninc
523 common, inc, remoteheads = commoninc
534 fco = discovery.findcommonoutgoing
524 fco = discovery.findcommonoutgoing
535 outgoing = fco(pushop.repo, pushop.remote, onlyheads=pushop.revs,
525 outgoing = fco(pushop.repo, pushop.remote, onlyheads=pushop.revs,
536 commoninc=commoninc, force=pushop.force)
526 commoninc=commoninc, force=pushop.force)
537 pushop.outgoing = outgoing
527 pushop.outgoing = outgoing
538 pushop.remoteheads = remoteheads
528 pushop.remoteheads = remoteheads
539 pushop.incoming = inc
529 pushop.incoming = inc
540
530
541 @pushdiscovery('phase')
531 @pushdiscovery('phase')
542 def _pushdiscoveryphase(pushop):
532 def _pushdiscoveryphase(pushop):
543 """discover the phase that needs to be pushed
533 """discover the phase that needs to be pushed
544
534
545 (computed for both success and failure case for changesets push)"""
535 (computed for both success and failure case for changesets push)"""
546 outgoing = pushop.outgoing
536 outgoing = pushop.outgoing
547 unfi = pushop.repo.unfiltered()
537 unfi = pushop.repo.unfiltered()
548 remotephases = pushop.remote.listkeys('phases')
538 remotephases = pushop.remote.listkeys('phases')
549 publishing = remotephases.get('publishing', False)
539 publishing = remotephases.get('publishing', False)
550 if (pushop.ui.configbool('ui', '_usedassubrepo')
540 if (pushop.ui.configbool('ui', '_usedassubrepo')
551 and remotephases # server supports phases
541 and remotephases # server supports phases
552 and not pushop.outgoing.missing # no changesets to be pushed
542 and not pushop.outgoing.missing # no changesets to be pushed
553 and publishing):
543 and publishing):
554 # When:
544 # When:
555 # - this is a subrepo push
545 # - this is a subrepo push
556 # - and remote support phase
546 # - and remote support phase
557 # - and no changeset are to be pushed
547 # - and no changeset are to be pushed
558 # - and remote is publishing
548 # - and remote is publishing
559 # We may be in issue 3871 case!
549 # We may be in issue 3871 case!
560 # We drop the possible phase synchronisation done by
550 # We drop the possible phase synchronisation done by
561 # courtesy to publish changesets possibly locally draft
551 # courtesy to publish changesets possibly locally draft
562 # on the remote.
552 # on the remote.
563 remotephases = {'publishing': 'True'}
553 remotephases = {'publishing': 'True'}
564 ana = phases.analyzeremotephases(pushop.repo,
554 ana = phases.analyzeremotephases(pushop.repo,
565 pushop.fallbackheads,
555 pushop.fallbackheads,
566 remotephases)
556 remotephases)
567 pheads, droots = ana
557 pheads, droots = ana
568 extracond = ''
558 extracond = ''
569 if not publishing:
559 if not publishing:
570 extracond = ' and public()'
560 extracond = ' and public()'
571 revset = 'heads((%%ln::%%ln) %s)' % extracond
561 revset = 'heads((%%ln::%%ln) %s)' % extracond
572 # Get the list of all revs draft on remote by public here.
562 # Get the list of all revs draft on remote by public here.
573 # XXX Beware that revset break if droots is not strictly
563 # XXX Beware that revset break if droots is not strictly
574 # XXX root we may want to ensure it is but it is costly
564 # XXX root we may want to ensure it is but it is costly
575 fallback = list(unfi.set(revset, droots, pushop.fallbackheads))
565 fallback = list(unfi.set(revset, droots, pushop.fallbackheads))
576 if not outgoing.missing:
566 if not outgoing.missing:
577 future = fallback
567 future = fallback
578 else:
568 else:
579 # adds changeset we are going to push as draft
569 # adds changeset we are going to push as draft
580 #
570 #
581 # should not be necessary for publishing server, but because of an
571 # should not be necessary for publishing server, but because of an
582 # issue fixed in xxxxx we have to do it anyway.
572 # issue fixed in xxxxx we have to do it anyway.
583 fdroots = list(unfi.set('roots(%ln + %ln::)',
573 fdroots = list(unfi.set('roots(%ln + %ln::)',
584 outgoing.missing, droots))
574 outgoing.missing, droots))
585 fdroots = [f.node() for f in fdroots]
575 fdroots = [f.node() for f in fdroots]
586 future = list(unfi.set(revset, fdroots, pushop.futureheads))
576 future = list(unfi.set(revset, fdroots, pushop.futureheads))
587 pushop.outdatedphases = future
577 pushop.outdatedphases = future
588 pushop.fallbackoutdatedphases = fallback
578 pushop.fallbackoutdatedphases = fallback
589
579
590 @pushdiscovery('obsmarker')
580 @pushdiscovery('obsmarker')
591 def _pushdiscoveryobsmarkers(pushop):
581 def _pushdiscoveryobsmarkers(pushop):
592 if (obsolete.isenabled(pushop.repo, obsolete.exchangeopt)
582 if (obsolete.isenabled(pushop.repo, obsolete.exchangeopt)
593 and pushop.repo.obsstore
583 and pushop.repo.obsstore
594 and 'obsolete' in pushop.remote.listkeys('namespaces')):
584 and 'obsolete' in pushop.remote.listkeys('namespaces')):
595 repo = pushop.repo
585 repo = pushop.repo
596 # very naive computation, that can be quite expensive on big repo.
586 # very naive computation, that can be quite expensive on big repo.
597 # However: evolution is currently slow on them anyway.
587 # However: evolution is currently slow on them anyway.
598 nodes = (c.node() for c in repo.set('::%ln', pushop.futureheads))
588 nodes = (c.node() for c in repo.set('::%ln', pushop.futureheads))
599 pushop.outobsmarkers = pushop.repo.obsstore.relevantmarkers(nodes)
589 pushop.outobsmarkers = pushop.repo.obsstore.relevantmarkers(nodes)
600
590
601 @pushdiscovery('bookmarks')
591 @pushdiscovery('bookmarks')
602 def _pushdiscoverybookmarks(pushop):
592 def _pushdiscoverybookmarks(pushop):
603 ui = pushop.ui
593 ui = pushop.ui
604 repo = pushop.repo.unfiltered()
594 repo = pushop.repo.unfiltered()
605 remote = pushop.remote
595 remote = pushop.remote
606 ui.debug("checking for updated bookmarks\n")
596 ui.debug("checking for updated bookmarks\n")
607 ancestors = ()
597 ancestors = ()
608 if pushop.revs:
598 if pushop.revs:
609 revnums = map(repo.changelog.rev, pushop.revs)
599 revnums = map(repo.changelog.rev, pushop.revs)
610 ancestors = repo.changelog.ancestors(revnums, inclusive=True)
600 ancestors = repo.changelog.ancestors(revnums, inclusive=True)
611 remotebookmark = remote.listkeys('bookmarks')
601 remotebookmark = remote.listkeys('bookmarks')
612
602
613 explicit = set([repo._bookmarks.expandname(bookmark)
603 explicit = set([repo._bookmarks.expandname(bookmark)
614 for bookmark in pushop.bookmarks])
604 for bookmark in pushop.bookmarks])
615
605
616 remotebookmark = bookmod.unhexlifybookmarks(remotebookmark)
606 remotebookmark = bookmod.unhexlifybookmarks(remotebookmark)
617 comp = bookmod.comparebookmarks(repo, repo._bookmarks, remotebookmark)
607 comp = bookmod.comparebookmarks(repo, repo._bookmarks, remotebookmark)
618
608
619 def safehex(x):
609 def safehex(x):
620 if x is None:
610 if x is None:
621 return x
611 return x
622 return hex(x)
612 return hex(x)
623
613
624 def hexifycompbookmarks(bookmarks):
614 def hexifycompbookmarks(bookmarks):
625 for b, scid, dcid in bookmarks:
615 for b, scid, dcid in bookmarks:
626 yield b, safehex(scid), safehex(dcid)
616 yield b, safehex(scid), safehex(dcid)
627
617
628 comp = [hexifycompbookmarks(marks) for marks in comp]
618 comp = [hexifycompbookmarks(marks) for marks in comp]
629 addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = comp
619 addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = comp
630
620
631 for b, scid, dcid in advsrc:
621 for b, scid, dcid in advsrc:
632 if b in explicit:
622 if b in explicit:
633 explicit.remove(b)
623 explicit.remove(b)
634 if not ancestors or repo[scid].rev() in ancestors:
624 if not ancestors or repo[scid].rev() in ancestors:
635 pushop.outbookmarks.append((b, dcid, scid))
625 pushop.outbookmarks.append((b, dcid, scid))
636 # search added bookmark
626 # search added bookmark
637 for b, scid, dcid in addsrc:
627 for b, scid, dcid in addsrc:
638 if b in explicit:
628 if b in explicit:
639 explicit.remove(b)
629 explicit.remove(b)
640 pushop.outbookmarks.append((b, '', scid))
630 pushop.outbookmarks.append((b, '', scid))
641 # search for overwritten bookmark
631 # search for overwritten bookmark
642 for b, scid, dcid in list(advdst) + list(diverge) + list(differ):
632 for b, scid, dcid in list(advdst) + list(diverge) + list(differ):
643 if b in explicit:
633 if b in explicit:
644 explicit.remove(b)
634 explicit.remove(b)
645 pushop.outbookmarks.append((b, dcid, scid))
635 pushop.outbookmarks.append((b, dcid, scid))
646 # search for bookmark to delete
636 # search for bookmark to delete
647 for b, scid, dcid in adddst:
637 for b, scid, dcid in adddst:
648 if b in explicit:
638 if b in explicit:
649 explicit.remove(b)
639 explicit.remove(b)
650 # treat as "deleted locally"
640 # treat as "deleted locally"
651 pushop.outbookmarks.append((b, dcid, ''))
641 pushop.outbookmarks.append((b, dcid, ''))
652 # identical bookmarks shouldn't get reported
642 # identical bookmarks shouldn't get reported
653 for b, scid, dcid in same:
643 for b, scid, dcid in same:
654 if b in explicit:
644 if b in explicit:
655 explicit.remove(b)
645 explicit.remove(b)
656
646
657 if explicit:
647 if explicit:
658 explicit = sorted(explicit)
648 explicit = sorted(explicit)
659 # we should probably list all of them
649 # we should probably list all of them
660 ui.warn(_('bookmark %s does not exist on the local '
650 ui.warn(_('bookmark %s does not exist on the local '
661 'or remote repository!\n') % explicit[0])
651 'or remote repository!\n') % explicit[0])
662 pushop.bkresult = 2
652 pushop.bkresult = 2
663
653
664 pushop.outbookmarks.sort()
654 pushop.outbookmarks.sort()
665
655
666 def _pushcheckoutgoing(pushop):
656 def _pushcheckoutgoing(pushop):
667 outgoing = pushop.outgoing
657 outgoing = pushop.outgoing
668 unfi = pushop.repo.unfiltered()
658 unfi = pushop.repo.unfiltered()
669 if not outgoing.missing:
659 if not outgoing.missing:
670 # nothing to push
660 # nothing to push
671 scmutil.nochangesfound(unfi.ui, unfi, outgoing.excluded)
661 scmutil.nochangesfound(unfi.ui, unfi, outgoing.excluded)
672 return False
662 return False
673 # something to push
663 # something to push
674 if not pushop.force:
664 if not pushop.force:
675 # if repo.obsstore == False --> no obsolete
665 # if repo.obsstore == False --> no obsolete
676 # then, save the iteration
666 # then, save the iteration
677 if unfi.obsstore:
667 if unfi.obsstore:
678 # this message are here for 80 char limit reason
668 # this message are here for 80 char limit reason
679 mso = _("push includes obsolete changeset: %s!")
669 mso = _("push includes obsolete changeset: %s!")
680 mspd = _("push includes phase-divergent changeset: %s!")
670 mspd = _("push includes phase-divergent changeset: %s!")
681 mscd = _("push includes content-divergent changeset: %s!")
671 mscd = _("push includes content-divergent changeset: %s!")
682 mst = {"orphan": _("push includes orphan changeset: %s!"),
672 mst = {"orphan": _("push includes orphan changeset: %s!"),
683 "phase-divergent": mspd,
673 "phase-divergent": mspd,
684 "content-divergent": mscd}
674 "content-divergent": mscd}
685 # If we are to push if there is at least one
675 # If we are to push if there is at least one
686 # obsolete or unstable changeset in missing, at
676 # obsolete or unstable changeset in missing, at
687 # least one of the missinghead will be obsolete or
677 # least one of the missinghead will be obsolete or
688 # unstable. So checking heads only is ok
678 # unstable. So checking heads only is ok
689 for node in outgoing.missingheads:
679 for node in outgoing.missingheads:
690 ctx = unfi[node]
680 ctx = unfi[node]
691 if ctx.obsolete():
681 if ctx.obsolete():
692 raise error.Abort(mso % ctx)
682 raise error.Abort(mso % ctx)
693 elif ctx.troubled():
683 elif ctx.troubled():
694 raise error.Abort(mst[ctx.troubles()[0]] % ctx)
684 raise error.Abort(mst[ctx.troubles()[0]] % ctx)
695
685
696 discovery.checkheads(pushop)
686 discovery.checkheads(pushop)
697 return True
687 return True
698
688
699 # List of names of steps to perform for an outgoing bundle2, order matters.
689 # List of names of steps to perform for an outgoing bundle2, order matters.
700 b2partsgenorder = []
690 b2partsgenorder = []
701
691
702 # Mapping between step name and function
692 # Mapping between step name and function
703 #
693 #
704 # This exists to help extensions wrap steps if necessary
694 # This exists to help extensions wrap steps if necessary
705 b2partsgenmapping = {}
695 b2partsgenmapping = {}
706
696
707 def b2partsgenerator(stepname, idx=None):
697 def b2partsgenerator(stepname, idx=None):
708 """decorator for function generating bundle2 part
698 """decorator for function generating bundle2 part
709
699
710 The function is added to the step -> function mapping and appended to the
700 The function is added to the step -> function mapping and appended to the
711 list of steps. Beware that decorated functions will be added in order
701 list of steps. Beware that decorated functions will be added in order
712 (this may matter).
702 (this may matter).
713
703
714 You can only use this decorator for new steps, if you want to wrap a step
704 You can only use this decorator for new steps, if you want to wrap a step
715 from an extension, attack the b2partsgenmapping dictionary directly."""
705 from an extension, attack the b2partsgenmapping dictionary directly."""
716 def dec(func):
706 def dec(func):
717 assert stepname not in b2partsgenmapping
707 assert stepname not in b2partsgenmapping
718 b2partsgenmapping[stepname] = func
708 b2partsgenmapping[stepname] = func
719 if idx is None:
709 if idx is None:
720 b2partsgenorder.append(stepname)
710 b2partsgenorder.append(stepname)
721 else:
711 else:
722 b2partsgenorder.insert(idx, stepname)
712 b2partsgenorder.insert(idx, stepname)
723 return func
713 return func
724 return dec
714 return dec
725
715
726 def _pushb2ctxcheckheads(pushop, bundler):
716 def _pushb2ctxcheckheads(pushop, bundler):
727 """Generate race condition checking parts
717 """Generate race condition checking parts
728
718
729 Exists as an independent function to aid extensions
719 Exists as an independent function to aid extensions
730 """
720 """
731 # * 'force' do not check for push race,
721 # * 'force' do not check for push race,
732 # * if we don't push anything, there are nothing to check.
722 # * if we don't push anything, there are nothing to check.
733 if not pushop.force and pushop.outgoing.missingheads:
723 if not pushop.force and pushop.outgoing.missingheads:
734 allowunrelated = 'related' in bundler.capabilities.get('checkheads', ())
724 allowunrelated = 'related' in bundler.capabilities.get('checkheads', ())
735 emptyremote = pushop.pushbranchmap is None
725 emptyremote = pushop.pushbranchmap is None
736 if not allowunrelated or emptyremote:
726 if not allowunrelated or emptyremote:
737 bundler.newpart('check:heads', data=iter(pushop.remoteheads))
727 bundler.newpart('check:heads', data=iter(pushop.remoteheads))
738 else:
728 else:
739 affected = set()
729 affected = set()
740 for branch, heads in pushop.pushbranchmap.iteritems():
730 for branch, heads in pushop.pushbranchmap.iteritems():
741 remoteheads, newheads, unsyncedheads, discardedheads = heads
731 remoteheads, newheads, unsyncedheads, discardedheads = heads
742 if remoteheads is not None:
732 if remoteheads is not None:
743 remote = set(remoteheads)
733 remote = set(remoteheads)
744 affected |= set(discardedheads) & remote
734 affected |= set(discardedheads) & remote
745 affected |= remote - set(newheads)
735 affected |= remote - set(newheads)
746 if affected:
736 if affected:
747 data = iter(sorted(affected))
737 data = iter(sorted(affected))
748 bundler.newpart('check:updated-heads', data=data)
738 bundler.newpart('check:updated-heads', data=data)
749
739
750 @b2partsgenerator('changeset')
740 @b2partsgenerator('changeset')
751 def _pushb2ctx(pushop, bundler):
741 def _pushb2ctx(pushop, bundler):
752 """handle changegroup push through bundle2
742 """handle changegroup push through bundle2
753
743
754 addchangegroup result is stored in the ``pushop.cgresult`` attribute.
744 addchangegroup result is stored in the ``pushop.cgresult`` attribute.
755 """
745 """
756 if 'changesets' in pushop.stepsdone:
746 if 'changesets' in pushop.stepsdone:
757 return
747 return
758 pushop.stepsdone.add('changesets')
748 pushop.stepsdone.add('changesets')
759 # Send known heads to the server for race detection.
749 # Send known heads to the server for race detection.
760 if not _pushcheckoutgoing(pushop):
750 if not _pushcheckoutgoing(pushop):
761 return
751 return
762 pushop.repo.prepushoutgoinghooks(pushop)
752 pushop.repo.prepushoutgoinghooks(pushop)
763
753
764 _pushb2ctxcheckheads(pushop, bundler)
754 _pushb2ctxcheckheads(pushop, bundler)
765
755
766 b2caps = bundle2.bundle2caps(pushop.remote)
756 b2caps = bundle2.bundle2caps(pushop.remote)
767 version = '01'
757 version = '01'
768 cgversions = b2caps.get('changegroup')
758 cgversions = b2caps.get('changegroup')
769 if cgversions: # 3.1 and 3.2 ship with an empty value
759 if cgversions: # 3.1 and 3.2 ship with an empty value
770 cgversions = [v for v in cgversions
760 cgversions = [v for v in cgversions
771 if v in changegroup.supportedoutgoingversions(
761 if v in changegroup.supportedoutgoingversions(
772 pushop.repo)]
762 pushop.repo)]
773 if not cgversions:
763 if not cgversions:
774 raise ValueError(_('no common changegroup version'))
764 raise ValueError(_('no common changegroup version'))
775 version = max(cgversions)
765 version = max(cgversions)
776 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
766 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
777 pushop.outgoing,
767 pushop.outgoing,
778 version=version)
768 version=version)
779 cgpart = bundler.newpart('changegroup', data=cg)
769 cgpart = bundler.newpart('changegroup', data=cg)
780 if cgversions:
770 if cgversions:
781 cgpart.addparam('version', version)
771 cgpart.addparam('version', version)
782 if 'treemanifest' in pushop.repo.requirements:
772 if 'treemanifest' in pushop.repo.requirements:
783 cgpart.addparam('treemanifest', '1')
773 cgpart.addparam('treemanifest', '1')
784 def handlereply(op):
774 def handlereply(op):
785 """extract addchangegroup returns from server reply"""
775 """extract addchangegroup returns from server reply"""
786 cgreplies = op.records.getreplies(cgpart.id)
776 cgreplies = op.records.getreplies(cgpart.id)
787 assert len(cgreplies['changegroup']) == 1
777 assert len(cgreplies['changegroup']) == 1
788 pushop.cgresult = cgreplies['changegroup'][0]['return']
778 pushop.cgresult = cgreplies['changegroup'][0]['return']
789 return handlereply
779 return handlereply
790
780
791 @b2partsgenerator('phase')
781 @b2partsgenerator('phase')
792 def _pushb2phases(pushop, bundler):
782 def _pushb2phases(pushop, bundler):
793 """handle phase push through bundle2"""
783 """handle phase push through bundle2"""
794 if 'phases' in pushop.stepsdone:
784 if 'phases' in pushop.stepsdone:
795 return
785 return
796 b2caps = bundle2.bundle2caps(pushop.remote)
786 b2caps = bundle2.bundle2caps(pushop.remote)
797 if not 'pushkey' in b2caps:
787 if not 'pushkey' in b2caps:
798 return
788 return
799 pushop.stepsdone.add('phases')
789 pushop.stepsdone.add('phases')
800 part2node = []
790 part2node = []
801
791
802 def handlefailure(pushop, exc):
792 def handlefailure(pushop, exc):
803 targetid = int(exc.partid)
793 targetid = int(exc.partid)
804 for partid, node in part2node:
794 for partid, node in part2node:
805 if partid == targetid:
795 if partid == targetid:
806 raise error.Abort(_('updating %s to public failed') % node)
796 raise error.Abort(_('updating %s to public failed') % node)
807
797
808 enc = pushkey.encode
798 enc = pushkey.encode
809 for newremotehead in pushop.outdatedphases:
799 for newremotehead in pushop.outdatedphases:
810 part = bundler.newpart('pushkey')
800 part = bundler.newpart('pushkey')
811 part.addparam('namespace', enc('phases'))
801 part.addparam('namespace', enc('phases'))
812 part.addparam('key', enc(newremotehead.hex()))
802 part.addparam('key', enc(newremotehead.hex()))
813 part.addparam('old', enc(str(phases.draft)))
803 part.addparam('old', enc(str(phases.draft)))
814 part.addparam('new', enc(str(phases.public)))
804 part.addparam('new', enc(str(phases.public)))
815 part2node.append((part.id, newremotehead))
805 part2node.append((part.id, newremotehead))
816 pushop.pkfailcb[part.id] = handlefailure
806 pushop.pkfailcb[part.id] = handlefailure
817
807
818 def handlereply(op):
808 def handlereply(op):
819 for partid, node in part2node:
809 for partid, node in part2node:
820 partrep = op.records.getreplies(partid)
810 partrep = op.records.getreplies(partid)
821 results = partrep['pushkey']
811 results = partrep['pushkey']
822 assert len(results) <= 1
812 assert len(results) <= 1
823 msg = None
813 msg = None
824 if not results:
814 if not results:
825 msg = _('server ignored update of %s to public!\n') % node
815 msg = _('server ignored update of %s to public!\n') % node
826 elif not int(results[0]['return']):
816 elif not int(results[0]['return']):
827 msg = _('updating %s to public failed!\n') % node
817 msg = _('updating %s to public failed!\n') % node
828 if msg is not None:
818 if msg is not None:
829 pushop.ui.warn(msg)
819 pushop.ui.warn(msg)
830 return handlereply
820 return handlereply
831
821
832 @b2partsgenerator('obsmarkers')
822 @b2partsgenerator('obsmarkers')
833 def _pushb2obsmarkers(pushop, bundler):
823 def _pushb2obsmarkers(pushop, bundler):
834 if 'obsmarkers' in pushop.stepsdone:
824 if 'obsmarkers' in pushop.stepsdone:
835 return
825 return
836 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
826 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
837 if obsolete.commonversion(remoteversions) is None:
827 if obsolete.commonversion(remoteversions) is None:
838 return
828 return
839 pushop.stepsdone.add('obsmarkers')
829 pushop.stepsdone.add('obsmarkers')
840 if pushop.outobsmarkers:
830 if pushop.outobsmarkers:
841 markers = sorted(pushop.outobsmarkers)
831 markers = sorted(pushop.outobsmarkers)
842 bundle2.buildobsmarkerspart(bundler, markers)
832 bundle2.buildobsmarkerspart(bundler, markers)
843
833
844 @b2partsgenerator('bookmarks')
834 @b2partsgenerator('bookmarks')
845 def _pushb2bookmarks(pushop, bundler):
835 def _pushb2bookmarks(pushop, bundler):
846 """handle bookmark push through bundle2"""
836 """handle bookmark push through bundle2"""
847 if 'bookmarks' in pushop.stepsdone:
837 if 'bookmarks' in pushop.stepsdone:
848 return
838 return
849 b2caps = bundle2.bundle2caps(pushop.remote)
839 b2caps = bundle2.bundle2caps(pushop.remote)
850 if 'pushkey' not in b2caps:
840 if 'pushkey' not in b2caps:
851 return
841 return
852 pushop.stepsdone.add('bookmarks')
842 pushop.stepsdone.add('bookmarks')
853 part2book = []
843 part2book = []
854 enc = pushkey.encode
844 enc = pushkey.encode
855
845
856 def handlefailure(pushop, exc):
846 def handlefailure(pushop, exc):
857 targetid = int(exc.partid)
847 targetid = int(exc.partid)
858 for partid, book, action in part2book:
848 for partid, book, action in part2book:
859 if partid == targetid:
849 if partid == targetid:
860 raise error.Abort(bookmsgmap[action][1].rstrip() % book)
850 raise error.Abort(bookmsgmap[action][1].rstrip() % book)
861 # we should not be called for part we did not generated
851 # we should not be called for part we did not generated
862 assert False
852 assert False
863
853
864 for book, old, new in pushop.outbookmarks:
854 for book, old, new in pushop.outbookmarks:
865 part = bundler.newpart('pushkey')
855 part = bundler.newpart('pushkey')
866 part.addparam('namespace', enc('bookmarks'))
856 part.addparam('namespace', enc('bookmarks'))
867 part.addparam('key', enc(book))
857 part.addparam('key', enc(book))
868 part.addparam('old', enc(old))
858 part.addparam('old', enc(old))
869 part.addparam('new', enc(new))
859 part.addparam('new', enc(new))
870 action = 'update'
860 action = 'update'
871 if not old:
861 if not old:
872 action = 'export'
862 action = 'export'
873 elif not new:
863 elif not new:
874 action = 'delete'
864 action = 'delete'
875 part2book.append((part.id, book, action))
865 part2book.append((part.id, book, action))
876 pushop.pkfailcb[part.id] = handlefailure
866 pushop.pkfailcb[part.id] = handlefailure
877
867
878 def handlereply(op):
868 def handlereply(op):
879 ui = pushop.ui
869 ui = pushop.ui
880 for partid, book, action in part2book:
870 for partid, book, action in part2book:
881 partrep = op.records.getreplies(partid)
871 partrep = op.records.getreplies(partid)
882 results = partrep['pushkey']
872 results = partrep['pushkey']
883 assert len(results) <= 1
873 assert len(results) <= 1
884 if not results:
874 if not results:
885 pushop.ui.warn(_('server ignored bookmark %s update\n') % book)
875 pushop.ui.warn(_('server ignored bookmark %s update\n') % book)
886 else:
876 else:
887 ret = int(results[0]['return'])
877 ret = int(results[0]['return'])
888 if ret:
878 if ret:
889 ui.status(bookmsgmap[action][0] % book)
879 ui.status(bookmsgmap[action][0] % book)
890 else:
880 else:
891 ui.warn(bookmsgmap[action][1] % book)
881 ui.warn(bookmsgmap[action][1] % book)
892 if pushop.bkresult is not None:
882 if pushop.bkresult is not None:
893 pushop.bkresult = 1
883 pushop.bkresult = 1
894 return handlereply
884 return handlereply
895
885
896 @b2partsgenerator('pushvars', idx=0)
886 @b2partsgenerator('pushvars', idx=0)
897 def _getbundlesendvars(pushop, bundler):
887 def _getbundlesendvars(pushop, bundler):
898 '''send shellvars via bundle2'''
888 '''send shellvars via bundle2'''
899 if getattr(pushop.repo, '_shellvars', ()):
889 if getattr(pushop.repo, '_shellvars', ()):
900 part = bundler.newpart('pushvars')
890 part = bundler.newpart('pushvars')
901
891
902 for key, value in pushop.repo._shellvars.iteritems():
892 for key, value in pushop.repo._shellvars.iteritems():
903 part.addparam(key, value, mandatory=False)
893 part.addparam(key, value, mandatory=False)
904
894
905 def _pushbundle2(pushop):
895 def _pushbundle2(pushop):
906 """push data to the remote using bundle2
896 """push data to the remote using bundle2
907
897
908 The only currently supported type of data is changegroup but this will
898 The only currently supported type of data is changegroup but this will
909 evolve in the future."""
899 evolve in the future."""
910 bundler = bundle2.bundle20(pushop.ui, bundle2.bundle2caps(pushop.remote))
900 bundler = bundle2.bundle20(pushop.ui, bundle2.bundle2caps(pushop.remote))
911 pushback = (pushop.trmanager
901 pushback = (pushop.trmanager
912 and pushop.ui.configbool('experimental', 'bundle2.pushback'))
902 and pushop.ui.configbool('experimental', 'bundle2.pushback'))
913
903
914 # create reply capability
904 # create reply capability
915 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo,
905 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo,
916 allowpushback=pushback))
906 allowpushback=pushback))
917 bundler.newpart('replycaps', data=capsblob)
907 bundler.newpart('replycaps', data=capsblob)
918 replyhandlers = []
908 replyhandlers = []
919 for partgenname in b2partsgenorder:
909 for partgenname in b2partsgenorder:
920 partgen = b2partsgenmapping[partgenname]
910 partgen = b2partsgenmapping[partgenname]
921 ret = partgen(pushop, bundler)
911 ret = partgen(pushop, bundler)
922 if callable(ret):
912 if callable(ret):
923 replyhandlers.append(ret)
913 replyhandlers.append(ret)
924 # do not push if nothing to push
914 # do not push if nothing to push
925 if bundler.nbparts <= 1:
915 if bundler.nbparts <= 1:
926 return
916 return
927 stream = util.chunkbuffer(bundler.getchunks())
917 stream = util.chunkbuffer(bundler.getchunks())
928 try:
918 try:
929 try:
919 try:
930 reply = pushop.remote.unbundle(
920 reply = pushop.remote.unbundle(
931 stream, ['force'], pushop.remote.url())
921 stream, ['force'], pushop.remote.url())
932 except error.BundleValueError as exc:
922 except error.BundleValueError as exc:
933 raise error.Abort(_('missing support for %s') % exc)
923 raise error.Abort(_('missing support for %s') % exc)
934 try:
924 try:
935 trgetter = None
925 trgetter = None
936 if pushback:
926 if pushback:
937 trgetter = pushop.trmanager.transaction
927 trgetter = pushop.trmanager.transaction
938 op = bundle2.processbundle(pushop.repo, reply, trgetter)
928 op = bundle2.processbundle(pushop.repo, reply, trgetter)
939 except error.BundleValueError as exc:
929 except error.BundleValueError as exc:
940 raise error.Abort(_('missing support for %s') % exc)
930 raise error.Abort(_('missing support for %s') % exc)
941 except bundle2.AbortFromPart as exc:
931 except bundle2.AbortFromPart as exc:
942 pushop.ui.status(_('remote: %s\n') % exc)
932 pushop.ui.status(_('remote: %s\n') % exc)
943 if exc.hint is not None:
933 if exc.hint is not None:
944 pushop.ui.status(_('remote: %s\n') % ('(%s)' % exc.hint))
934 pushop.ui.status(_('remote: %s\n') % ('(%s)' % exc.hint))
945 raise error.Abort(_('push failed on remote'))
935 raise error.Abort(_('push failed on remote'))
946 except error.PushkeyFailed as exc:
936 except error.PushkeyFailed as exc:
947 partid = int(exc.partid)
937 partid = int(exc.partid)
948 if partid not in pushop.pkfailcb:
938 if partid not in pushop.pkfailcb:
949 raise
939 raise
950 pushop.pkfailcb[partid](pushop, exc)
940 pushop.pkfailcb[partid](pushop, exc)
951 for rephand in replyhandlers:
941 for rephand in replyhandlers:
952 rephand(op)
942 rephand(op)
953
943
954 def _pushchangeset(pushop):
944 def _pushchangeset(pushop):
955 """Make the actual push of changeset bundle to remote repo"""
945 """Make the actual push of changeset bundle to remote repo"""
956 if 'changesets' in pushop.stepsdone:
946 if 'changesets' in pushop.stepsdone:
957 return
947 return
958 pushop.stepsdone.add('changesets')
948 pushop.stepsdone.add('changesets')
959 if not _pushcheckoutgoing(pushop):
949 if not _pushcheckoutgoing(pushop):
960 return
950 return
951
952 # Should have verified this in push().
953 assert pushop.remote.capable('unbundle')
954
961 pushop.repo.prepushoutgoinghooks(pushop)
955 pushop.repo.prepushoutgoinghooks(pushop)
962 outgoing = pushop.outgoing
956 outgoing = pushop.outgoing
963 unbundle = pushop.remote.capable('unbundle')
964 # TODO: get bundlecaps from remote
957 # TODO: get bundlecaps from remote
965 bundlecaps = None
958 bundlecaps = None
966 # create a changegroup from local
959 # create a changegroup from local
967 if pushop.revs is None and not (outgoing.excluded
960 if pushop.revs is None and not (outgoing.excluded
968 or pushop.repo.changelog.filteredrevs):
961 or pushop.repo.changelog.filteredrevs):
969 # push everything,
962 # push everything,
970 # use the fast path, no race possible on push
963 # use the fast path, no race possible on push
971 bundler = changegroup.cg1packer(pushop.repo, bundlecaps)
964 bundler = changegroup.cg1packer(pushop.repo, bundlecaps)
972 cg = changegroup.getsubset(pushop.repo,
965 cg = changegroup.getsubset(pushop.repo,
973 outgoing,
966 outgoing,
974 bundler,
967 bundler,
975 'push',
968 'push',
976 fastpath=True)
969 fastpath=True)
977 else:
970 else:
978 cg = changegroup.getchangegroup(pushop.repo, 'push', outgoing,
971 cg = changegroup.getchangegroup(pushop.repo, 'push', outgoing,
979 bundlecaps=bundlecaps)
972 bundlecaps=bundlecaps)
980
973
981 # apply changegroup to remote
974 # apply changegroup to remote
982 if unbundle:
983 # local repo finds heads on server, finds out what
975 # local repo finds heads on server, finds out what
984 # revs it must push. once revs transferred, if server
976 # revs it must push. once revs transferred, if server
985 # finds it has different heads (someone else won
977 # finds it has different heads (someone else won
986 # commit/push race), server aborts.
978 # commit/push race), server aborts.
987 if pushop.force:
979 if pushop.force:
988 remoteheads = ['force']
980 remoteheads = ['force']
989 else:
981 else:
990 remoteheads = pushop.remoteheads
982 remoteheads = pushop.remoteheads
991 # ssh: return remote's addchangegroup()
983 # ssh: return remote's addchangegroup()
992 # http: return remote's addchangegroup() or 0 for error
984 # http: return remote's addchangegroup() or 0 for error
993 pushop.cgresult = pushop.remote.unbundle(cg, remoteheads,
985 pushop.cgresult = pushop.remote.unbundle(cg, remoteheads,
994 pushop.repo.url())
986 pushop.repo.url())
995 else:
996 # we return an integer indicating remote head count
997 # change
998 pushop.cgresult = pushop.remote.addchangegroup(cg, 'push',
999 pushop.repo.url())
1000
987
1001 def _pushsyncphase(pushop):
988 def _pushsyncphase(pushop):
1002 """synchronise phase information locally and remotely"""
989 """synchronise phase information locally and remotely"""
1003 cheads = pushop.commonheads
990 cheads = pushop.commonheads
1004 # even when we don't push, exchanging phase data is useful
991 # even when we don't push, exchanging phase data is useful
1005 remotephases = pushop.remote.listkeys('phases')
992 remotephases = pushop.remote.listkeys('phases')
1006 if (pushop.ui.configbool('ui', '_usedassubrepo')
993 if (pushop.ui.configbool('ui', '_usedassubrepo')
1007 and remotephases # server supports phases
994 and remotephases # server supports phases
1008 and pushop.cgresult is None # nothing was pushed
995 and pushop.cgresult is None # nothing was pushed
1009 and remotephases.get('publishing', False)):
996 and remotephases.get('publishing', False)):
1010 # When:
997 # When:
1011 # - this is a subrepo push
998 # - this is a subrepo push
1012 # - and remote support phase
999 # - and remote support phase
1013 # - and no changeset was pushed
1000 # - and no changeset was pushed
1014 # - and remote is publishing
1001 # - and remote is publishing
1015 # We may be in issue 3871 case!
1002 # We may be in issue 3871 case!
1016 # We drop the possible phase synchronisation done by
1003 # We drop the possible phase synchronisation done by
1017 # courtesy to publish changesets possibly locally draft
1004 # courtesy to publish changesets possibly locally draft
1018 # on the remote.
1005 # on the remote.
1019 remotephases = {'publishing': 'True'}
1006 remotephases = {'publishing': 'True'}
1020 if not remotephases: # old server or public only reply from non-publishing
1007 if not remotephases: # old server or public only reply from non-publishing
1021 _localphasemove(pushop, cheads)
1008 _localphasemove(pushop, cheads)
1022 # don't push any phase data as there is nothing to push
1009 # don't push any phase data as there is nothing to push
1023 else:
1010 else:
1024 ana = phases.analyzeremotephases(pushop.repo, cheads,
1011 ana = phases.analyzeremotephases(pushop.repo, cheads,
1025 remotephases)
1012 remotephases)
1026 pheads, droots = ana
1013 pheads, droots = ana
1027 ### Apply remote phase on local
1014 ### Apply remote phase on local
1028 if remotephases.get('publishing', False):
1015 if remotephases.get('publishing', False):
1029 _localphasemove(pushop, cheads)
1016 _localphasemove(pushop, cheads)
1030 else: # publish = False
1017 else: # publish = False
1031 _localphasemove(pushop, pheads)
1018 _localphasemove(pushop, pheads)
1032 _localphasemove(pushop, cheads, phases.draft)
1019 _localphasemove(pushop, cheads, phases.draft)
1033 ### Apply local phase on remote
1020 ### Apply local phase on remote
1034
1021
1035 if pushop.cgresult:
1022 if pushop.cgresult:
1036 if 'phases' in pushop.stepsdone:
1023 if 'phases' in pushop.stepsdone:
1037 # phases already pushed though bundle2
1024 # phases already pushed though bundle2
1038 return
1025 return
1039 outdated = pushop.outdatedphases
1026 outdated = pushop.outdatedphases
1040 else:
1027 else:
1041 outdated = pushop.fallbackoutdatedphases
1028 outdated = pushop.fallbackoutdatedphases
1042
1029
1043 pushop.stepsdone.add('phases')
1030 pushop.stepsdone.add('phases')
1044
1031
1045 # filter heads already turned public by the push
1032 # filter heads already turned public by the push
1046 outdated = [c for c in outdated if c.node() not in pheads]
1033 outdated = [c for c in outdated if c.node() not in pheads]
1047 # fallback to independent pushkey command
1034 # fallback to independent pushkey command
1048 for newremotehead in outdated:
1035 for newremotehead in outdated:
1049 r = pushop.remote.pushkey('phases',
1036 r = pushop.remote.pushkey('phases',
1050 newremotehead.hex(),
1037 newremotehead.hex(),
1051 str(phases.draft),
1038 str(phases.draft),
1052 str(phases.public))
1039 str(phases.public))
1053 if not r:
1040 if not r:
1054 pushop.ui.warn(_('updating %s to public failed!\n')
1041 pushop.ui.warn(_('updating %s to public failed!\n')
1055 % newremotehead)
1042 % newremotehead)
1056
1043
1057 def _localphasemove(pushop, nodes, phase=phases.public):
1044 def _localphasemove(pushop, nodes, phase=phases.public):
1058 """move <nodes> to <phase> in the local source repo"""
1045 """move <nodes> to <phase> in the local source repo"""
1059 if pushop.trmanager:
1046 if pushop.trmanager:
1060 phases.advanceboundary(pushop.repo,
1047 phases.advanceboundary(pushop.repo,
1061 pushop.trmanager.transaction(),
1048 pushop.trmanager.transaction(),
1062 phase,
1049 phase,
1063 nodes)
1050 nodes)
1064 else:
1051 else:
1065 # repo is not locked, do not change any phases!
1052 # repo is not locked, do not change any phases!
1066 # Informs the user that phases should have been moved when
1053 # Informs the user that phases should have been moved when
1067 # applicable.
1054 # applicable.
1068 actualmoves = [n for n in nodes if phase < pushop.repo[n].phase()]
1055 actualmoves = [n for n in nodes if phase < pushop.repo[n].phase()]
1069 phasestr = phases.phasenames[phase]
1056 phasestr = phases.phasenames[phase]
1070 if actualmoves:
1057 if actualmoves:
1071 pushop.ui.status(_('cannot lock source repo, skipping '
1058 pushop.ui.status(_('cannot lock source repo, skipping '
1072 'local %s phase update\n') % phasestr)
1059 'local %s phase update\n') % phasestr)
1073
1060
1074 def _pushobsolete(pushop):
1061 def _pushobsolete(pushop):
1075 """utility function to push obsolete markers to a remote"""
1062 """utility function to push obsolete markers to a remote"""
1076 if 'obsmarkers' in pushop.stepsdone:
1063 if 'obsmarkers' in pushop.stepsdone:
1077 return
1064 return
1078 repo = pushop.repo
1065 repo = pushop.repo
1079 remote = pushop.remote
1066 remote = pushop.remote
1080 pushop.stepsdone.add('obsmarkers')
1067 pushop.stepsdone.add('obsmarkers')
1081 if pushop.outobsmarkers:
1068 if pushop.outobsmarkers:
1082 pushop.ui.debug('try to push obsolete markers to remote\n')
1069 pushop.ui.debug('try to push obsolete markers to remote\n')
1083 rslts = []
1070 rslts = []
1084 remotedata = obsolete._pushkeyescape(sorted(pushop.outobsmarkers))
1071 remotedata = obsolete._pushkeyescape(sorted(pushop.outobsmarkers))
1085 for key in sorted(remotedata, reverse=True):
1072 for key in sorted(remotedata, reverse=True):
1086 # reverse sort to ensure we end with dump0
1073 # reverse sort to ensure we end with dump0
1087 data = remotedata[key]
1074 data = remotedata[key]
1088 rslts.append(remote.pushkey('obsolete', key, '', data))
1075 rslts.append(remote.pushkey('obsolete', key, '', data))
1089 if [r for r in rslts if not r]:
1076 if [r for r in rslts if not r]:
1090 msg = _('failed to push some obsolete markers!\n')
1077 msg = _('failed to push some obsolete markers!\n')
1091 repo.ui.warn(msg)
1078 repo.ui.warn(msg)
1092
1079
1093 def _pushbookmark(pushop):
1080 def _pushbookmark(pushop):
1094 """Update bookmark position on remote"""
1081 """Update bookmark position on remote"""
1095 if pushop.cgresult == 0 or 'bookmarks' in pushop.stepsdone:
1082 if pushop.cgresult == 0 or 'bookmarks' in pushop.stepsdone:
1096 return
1083 return
1097 pushop.stepsdone.add('bookmarks')
1084 pushop.stepsdone.add('bookmarks')
1098 ui = pushop.ui
1085 ui = pushop.ui
1099 remote = pushop.remote
1086 remote = pushop.remote
1100
1087
1101 for b, old, new in pushop.outbookmarks:
1088 for b, old, new in pushop.outbookmarks:
1102 action = 'update'
1089 action = 'update'
1103 if not old:
1090 if not old:
1104 action = 'export'
1091 action = 'export'
1105 elif not new:
1092 elif not new:
1106 action = 'delete'
1093 action = 'delete'
1107 if remote.pushkey('bookmarks', b, old, new):
1094 if remote.pushkey('bookmarks', b, old, new):
1108 ui.status(bookmsgmap[action][0] % b)
1095 ui.status(bookmsgmap[action][0] % b)
1109 else:
1096 else:
1110 ui.warn(bookmsgmap[action][1] % b)
1097 ui.warn(bookmsgmap[action][1] % b)
1111 # discovery can have set the value form invalid entry
1098 # discovery can have set the value form invalid entry
1112 if pushop.bkresult is not None:
1099 if pushop.bkresult is not None:
1113 pushop.bkresult = 1
1100 pushop.bkresult = 1
1114
1101
1115 class pulloperation(object):
1102 class pulloperation(object):
1116 """A object that represent a single pull operation
1103 """A object that represent a single pull operation
1117
1104
1118 It purpose is to carry pull related state and very common operation.
1105 It purpose is to carry pull related state and very common operation.
1119
1106
1120 A new should be created at the beginning of each pull and discarded
1107 A new should be created at the beginning of each pull and discarded
1121 afterward.
1108 afterward.
1122 """
1109 """
1123
1110
1124 def __init__(self, repo, remote, heads=None, force=False, bookmarks=(),
1111 def __init__(self, repo, remote, heads=None, force=False, bookmarks=(),
1125 remotebookmarks=None, streamclonerequested=None):
1112 remotebookmarks=None, streamclonerequested=None):
1126 # repo we pull into
1113 # repo we pull into
1127 self.repo = repo
1114 self.repo = repo
1128 # repo we pull from
1115 # repo we pull from
1129 self.remote = remote
1116 self.remote = remote
1130 # revision we try to pull (None is "all")
1117 # revision we try to pull (None is "all")
1131 self.heads = heads
1118 self.heads = heads
1132 # bookmark pulled explicitly
1119 # bookmark pulled explicitly
1133 self.explicitbookmarks = [repo._bookmarks.expandname(bookmark)
1120 self.explicitbookmarks = [repo._bookmarks.expandname(bookmark)
1134 for bookmark in bookmarks]
1121 for bookmark in bookmarks]
1135 # do we force pull?
1122 # do we force pull?
1136 self.force = force
1123 self.force = force
1137 # whether a streaming clone was requested
1124 # whether a streaming clone was requested
1138 self.streamclonerequested = streamclonerequested
1125 self.streamclonerequested = streamclonerequested
1139 # transaction manager
1126 # transaction manager
1140 self.trmanager = None
1127 self.trmanager = None
1141 # set of common changeset between local and remote before pull
1128 # set of common changeset between local and remote before pull
1142 self.common = None
1129 self.common = None
1143 # set of pulled head
1130 # set of pulled head
1144 self.rheads = None
1131 self.rheads = None
1145 # list of missing changeset to fetch remotely
1132 # list of missing changeset to fetch remotely
1146 self.fetch = None
1133 self.fetch = None
1147 # remote bookmarks data
1134 # remote bookmarks data
1148 self.remotebookmarks = remotebookmarks
1135 self.remotebookmarks = remotebookmarks
1149 # result of changegroup pulling (used as return code by pull)
1136 # result of changegroup pulling (used as return code by pull)
1150 self.cgresult = None
1137 self.cgresult = None
1151 # list of step already done
1138 # list of step already done
1152 self.stepsdone = set()
1139 self.stepsdone = set()
1153 # Whether we attempted a clone from pre-generated bundles.
1140 # Whether we attempted a clone from pre-generated bundles.
1154 self.clonebundleattempted = False
1141 self.clonebundleattempted = False
1155
1142
1156 @util.propertycache
1143 @util.propertycache
1157 def pulledsubset(self):
1144 def pulledsubset(self):
1158 """heads of the set of changeset target by the pull"""
1145 """heads of the set of changeset target by the pull"""
1159 # compute target subset
1146 # compute target subset
1160 if self.heads is None:
1147 if self.heads is None:
1161 # We pulled every thing possible
1148 # We pulled every thing possible
1162 # sync on everything common
1149 # sync on everything common
1163 c = set(self.common)
1150 c = set(self.common)
1164 ret = list(self.common)
1151 ret = list(self.common)
1165 for n in self.rheads:
1152 for n in self.rheads:
1166 if n not in c:
1153 if n not in c:
1167 ret.append(n)
1154 ret.append(n)
1168 return ret
1155 return ret
1169 else:
1156 else:
1170 # We pulled a specific subset
1157 # We pulled a specific subset
1171 # sync on this subset
1158 # sync on this subset
1172 return self.heads
1159 return self.heads
1173
1160
1174 @util.propertycache
1161 @util.propertycache
1175 def canusebundle2(self):
1162 def canusebundle2(self):
1176 return not _forcebundle1(self)
1163 return not _forcebundle1(self)
1177
1164
1178 @util.propertycache
1165 @util.propertycache
1179 def remotebundle2caps(self):
1166 def remotebundle2caps(self):
1180 return bundle2.bundle2caps(self.remote)
1167 return bundle2.bundle2caps(self.remote)
1181
1168
1182 def gettransaction(self):
1169 def gettransaction(self):
1183 # deprecated; talk to trmanager directly
1170 # deprecated; talk to trmanager directly
1184 return self.trmanager.transaction()
1171 return self.trmanager.transaction()
1185
1172
1186 class transactionmanager(object):
1173 class transactionmanager(object):
1187 """An object to manage the life cycle of a transaction
1174 """An object to manage the life cycle of a transaction
1188
1175
1189 It creates the transaction on demand and calls the appropriate hooks when
1176 It creates the transaction on demand and calls the appropriate hooks when
1190 closing the transaction."""
1177 closing the transaction."""
1191 def __init__(self, repo, source, url):
1178 def __init__(self, repo, source, url):
1192 self.repo = repo
1179 self.repo = repo
1193 self.source = source
1180 self.source = source
1194 self.url = url
1181 self.url = url
1195 self._tr = None
1182 self._tr = None
1196
1183
1197 def transaction(self):
1184 def transaction(self):
1198 """Return an open transaction object, constructing if necessary"""
1185 """Return an open transaction object, constructing if necessary"""
1199 if not self._tr:
1186 if not self._tr:
1200 trname = '%s\n%s' % (self.source, util.hidepassword(self.url))
1187 trname = '%s\n%s' % (self.source, util.hidepassword(self.url))
1201 self._tr = self.repo.transaction(trname)
1188 self._tr = self.repo.transaction(trname)
1202 self._tr.hookargs['source'] = self.source
1189 self._tr.hookargs['source'] = self.source
1203 self._tr.hookargs['url'] = self.url
1190 self._tr.hookargs['url'] = self.url
1204 return self._tr
1191 return self._tr
1205
1192
1206 def close(self):
1193 def close(self):
1207 """close transaction if created"""
1194 """close transaction if created"""
1208 if self._tr is not None:
1195 if self._tr is not None:
1209 self._tr.close()
1196 self._tr.close()
1210
1197
1211 def release(self):
1198 def release(self):
1212 """release transaction if created"""
1199 """release transaction if created"""
1213 if self._tr is not None:
1200 if self._tr is not None:
1214 self._tr.release()
1201 self._tr.release()
1215
1202
1216 def pull(repo, remote, heads=None, force=False, bookmarks=(), opargs=None,
1203 def pull(repo, remote, heads=None, force=False, bookmarks=(), opargs=None,
1217 streamclonerequested=None):
1204 streamclonerequested=None):
1218 """Fetch repository data from a remote.
1205 """Fetch repository data from a remote.
1219
1206
1220 This is the main function used to retrieve data from a remote repository.
1207 This is the main function used to retrieve data from a remote repository.
1221
1208
1222 ``repo`` is the local repository to clone into.
1209 ``repo`` is the local repository to clone into.
1223 ``remote`` is a peer instance.
1210 ``remote`` is a peer instance.
1224 ``heads`` is an iterable of revisions we want to pull. ``None`` (the
1211 ``heads`` is an iterable of revisions we want to pull. ``None`` (the
1225 default) means to pull everything from the remote.
1212 default) means to pull everything from the remote.
1226 ``bookmarks`` is an iterable of bookmarks requesting to be pulled. By
1213 ``bookmarks`` is an iterable of bookmarks requesting to be pulled. By
1227 default, all remote bookmarks are pulled.
1214 default, all remote bookmarks are pulled.
1228 ``opargs`` are additional keyword arguments to pass to ``pulloperation``
1215 ``opargs`` are additional keyword arguments to pass to ``pulloperation``
1229 initialization.
1216 initialization.
1230 ``streamclonerequested`` is a boolean indicating whether a "streaming
1217 ``streamclonerequested`` is a boolean indicating whether a "streaming
1231 clone" is requested. A "streaming clone" is essentially a raw file copy
1218 clone" is requested. A "streaming clone" is essentially a raw file copy
1232 of revlogs from the server. This only works when the local repository is
1219 of revlogs from the server. This only works when the local repository is
1233 empty. The default value of ``None`` means to respect the server
1220 empty. The default value of ``None`` means to respect the server
1234 configuration for preferring stream clones.
1221 configuration for preferring stream clones.
1235
1222
1236 Returns the ``pulloperation`` created for this pull.
1223 Returns the ``pulloperation`` created for this pull.
1237 """
1224 """
1238 if opargs is None:
1225 if opargs is None:
1239 opargs = {}
1226 opargs = {}
1240 pullop = pulloperation(repo, remote, heads, force, bookmarks=bookmarks,
1227 pullop = pulloperation(repo, remote, heads, force, bookmarks=bookmarks,
1241 streamclonerequested=streamclonerequested, **opargs)
1228 streamclonerequested=streamclonerequested, **opargs)
1242 if pullop.remote.local():
1229 if pullop.remote.local():
1243 missing = set(pullop.remote.requirements) - pullop.repo.supported
1230 missing = set(pullop.remote.requirements) - pullop.repo.supported
1244 if missing:
1231 if missing:
1245 msg = _("required features are not"
1232 msg = _("required features are not"
1246 " supported in the destination:"
1233 " supported in the destination:"
1247 " %s") % (', '.join(sorted(missing)))
1234 " %s") % (', '.join(sorted(missing)))
1248 raise error.Abort(msg)
1235 raise error.Abort(msg)
1249
1236
1250 wlock = lock = None
1237 wlock = lock = None
1251 try:
1238 try:
1252 wlock = pullop.repo.wlock()
1239 wlock = pullop.repo.wlock()
1253 lock = pullop.repo.lock()
1240 lock = pullop.repo.lock()
1254 pullop.trmanager = transactionmanager(repo, 'pull', remote.url())
1241 pullop.trmanager = transactionmanager(repo, 'pull', remote.url())
1255 streamclone.maybeperformlegacystreamclone(pullop)
1242 streamclone.maybeperformlegacystreamclone(pullop)
1256 # This should ideally be in _pullbundle2(). However, it needs to run
1243 # This should ideally be in _pullbundle2(). However, it needs to run
1257 # before discovery to avoid extra work.
1244 # before discovery to avoid extra work.
1258 _maybeapplyclonebundle(pullop)
1245 _maybeapplyclonebundle(pullop)
1259 _pulldiscovery(pullop)
1246 _pulldiscovery(pullop)
1260 if pullop.canusebundle2:
1247 if pullop.canusebundle2:
1261 _pullbundle2(pullop)
1248 _pullbundle2(pullop)
1262 _pullchangeset(pullop)
1249 _pullchangeset(pullop)
1263 _pullphase(pullop)
1250 _pullphase(pullop)
1264 _pullbookmarks(pullop)
1251 _pullbookmarks(pullop)
1265 _pullobsolete(pullop)
1252 _pullobsolete(pullop)
1266 pullop.trmanager.close()
1253 pullop.trmanager.close()
1267 finally:
1254 finally:
1268 lockmod.release(pullop.trmanager, lock, wlock)
1255 lockmod.release(pullop.trmanager, lock, wlock)
1269
1256
1270 return pullop
1257 return pullop
1271
1258
1272 # list of steps to perform discovery before pull
1259 # list of steps to perform discovery before pull
1273 pulldiscoveryorder = []
1260 pulldiscoveryorder = []
1274
1261
1275 # Mapping between step name and function
1262 # Mapping between step name and function
1276 #
1263 #
1277 # This exists to help extensions wrap steps if necessary
1264 # This exists to help extensions wrap steps if necessary
1278 pulldiscoverymapping = {}
1265 pulldiscoverymapping = {}
1279
1266
1280 def pulldiscovery(stepname):
1267 def pulldiscovery(stepname):
1281 """decorator for function performing discovery before pull
1268 """decorator for function performing discovery before pull
1282
1269
1283 The function is added to the step -> function mapping and appended to the
1270 The function is added to the step -> function mapping and appended to the
1284 list of steps. Beware that decorated function will be added in order (this
1271 list of steps. Beware that decorated function will be added in order (this
1285 may matter).
1272 may matter).
1286
1273
1287 You can only use this decorator for a new step, if you want to wrap a step
1274 You can only use this decorator for a new step, if you want to wrap a step
1288 from an extension, change the pulldiscovery dictionary directly."""
1275 from an extension, change the pulldiscovery dictionary directly."""
1289 def dec(func):
1276 def dec(func):
1290 assert stepname not in pulldiscoverymapping
1277 assert stepname not in pulldiscoverymapping
1291 pulldiscoverymapping[stepname] = func
1278 pulldiscoverymapping[stepname] = func
1292 pulldiscoveryorder.append(stepname)
1279 pulldiscoveryorder.append(stepname)
1293 return func
1280 return func
1294 return dec
1281 return dec
1295
1282
1296 def _pulldiscovery(pullop):
1283 def _pulldiscovery(pullop):
1297 """Run all discovery steps"""
1284 """Run all discovery steps"""
1298 for stepname in pulldiscoveryorder:
1285 for stepname in pulldiscoveryorder:
1299 step = pulldiscoverymapping[stepname]
1286 step = pulldiscoverymapping[stepname]
1300 step(pullop)
1287 step(pullop)
1301
1288
1302 @pulldiscovery('b1:bookmarks')
1289 @pulldiscovery('b1:bookmarks')
1303 def _pullbookmarkbundle1(pullop):
1290 def _pullbookmarkbundle1(pullop):
1304 """fetch bookmark data in bundle1 case
1291 """fetch bookmark data in bundle1 case
1305
1292
1306 If not using bundle2, we have to fetch bookmarks before changeset
1293 If not using bundle2, we have to fetch bookmarks before changeset
1307 discovery to reduce the chance and impact of race conditions."""
1294 discovery to reduce the chance and impact of race conditions."""
1308 if pullop.remotebookmarks is not None:
1295 if pullop.remotebookmarks is not None:
1309 return
1296 return
1310 if pullop.canusebundle2 and 'listkeys' in pullop.remotebundle2caps:
1297 if pullop.canusebundle2 and 'listkeys' in pullop.remotebundle2caps:
1311 # all known bundle2 servers now support listkeys, but lets be nice with
1298 # all known bundle2 servers now support listkeys, but lets be nice with
1312 # new implementation.
1299 # new implementation.
1313 return
1300 return
1314 pullop.remotebookmarks = pullop.remote.listkeys('bookmarks')
1301 pullop.remotebookmarks = pullop.remote.listkeys('bookmarks')
1315
1302
1316
1303
1317 @pulldiscovery('changegroup')
1304 @pulldiscovery('changegroup')
1318 def _pulldiscoverychangegroup(pullop):
1305 def _pulldiscoverychangegroup(pullop):
1319 """discovery phase for the pull
1306 """discovery phase for the pull
1320
1307
1321 Current handle changeset discovery only, will change handle all discovery
1308 Current handle changeset discovery only, will change handle all discovery
1322 at some point."""
1309 at some point."""
1323 tmp = discovery.findcommonincoming(pullop.repo,
1310 tmp = discovery.findcommonincoming(pullop.repo,
1324 pullop.remote,
1311 pullop.remote,
1325 heads=pullop.heads,
1312 heads=pullop.heads,
1326 force=pullop.force)
1313 force=pullop.force)
1327 common, fetch, rheads = tmp
1314 common, fetch, rheads = tmp
1328 nm = pullop.repo.unfiltered().changelog.nodemap
1315 nm = pullop.repo.unfiltered().changelog.nodemap
1329 if fetch and rheads:
1316 if fetch and rheads:
1330 # If a remote heads in filtered locally, lets drop it from the unknown
1317 # If a remote heads in filtered locally, lets drop it from the unknown
1331 # remote heads and put in back in common.
1318 # remote heads and put in back in common.
1332 #
1319 #
1333 # This is a hackish solution to catch most of "common but locally
1320 # This is a hackish solution to catch most of "common but locally
1334 # hidden situation". We do not performs discovery on unfiltered
1321 # hidden situation". We do not performs discovery on unfiltered
1335 # repository because it end up doing a pathological amount of round
1322 # repository because it end up doing a pathological amount of round
1336 # trip for w huge amount of changeset we do not care about.
1323 # trip for w huge amount of changeset we do not care about.
1337 #
1324 #
1338 # If a set of such "common but filtered" changeset exist on the server
1325 # If a set of such "common but filtered" changeset exist on the server
1339 # but are not including a remote heads, we'll not be able to detect it,
1326 # but are not including a remote heads, we'll not be able to detect it,
1340 scommon = set(common)
1327 scommon = set(common)
1341 filteredrheads = []
1328 filteredrheads = []
1342 for n in rheads:
1329 for n in rheads:
1343 if n in nm:
1330 if n in nm:
1344 if n not in scommon:
1331 if n not in scommon:
1345 common.append(n)
1332 common.append(n)
1346 else:
1333 else:
1347 filteredrheads.append(n)
1334 filteredrheads.append(n)
1348 if not filteredrheads:
1335 if not filteredrheads:
1349 fetch = []
1336 fetch = []
1350 rheads = filteredrheads
1337 rheads = filteredrheads
1351 pullop.common = common
1338 pullop.common = common
1352 pullop.fetch = fetch
1339 pullop.fetch = fetch
1353 pullop.rheads = rheads
1340 pullop.rheads = rheads
1354
1341
1355 def _pullbundle2(pullop):
1342 def _pullbundle2(pullop):
1356 """pull data using bundle2
1343 """pull data using bundle2
1357
1344
1358 For now, the only supported data are changegroup."""
1345 For now, the only supported data are changegroup."""
1359 kwargs = {'bundlecaps': caps20to10(pullop.repo)}
1346 kwargs = {'bundlecaps': caps20to10(pullop.repo)}
1360
1347
1361 # At the moment we don't do stream clones over bundle2. If that is
1348 # At the moment we don't do stream clones over bundle2. If that is
1362 # implemented then here's where the check for that will go.
1349 # implemented then here's where the check for that will go.
1363 streaming = False
1350 streaming = False
1364
1351
1365 # pulling changegroup
1352 # pulling changegroup
1366 pullop.stepsdone.add('changegroup')
1353 pullop.stepsdone.add('changegroup')
1367
1354
1368 kwargs['common'] = pullop.common
1355 kwargs['common'] = pullop.common
1369 kwargs['heads'] = pullop.heads or pullop.rheads
1356 kwargs['heads'] = pullop.heads or pullop.rheads
1370 kwargs['cg'] = pullop.fetch
1357 kwargs['cg'] = pullop.fetch
1371 if 'listkeys' in pullop.remotebundle2caps:
1358 if 'listkeys' in pullop.remotebundle2caps:
1372 kwargs['listkeys'] = ['phases']
1359 kwargs['listkeys'] = ['phases']
1373 if pullop.remotebookmarks is None:
1360 if pullop.remotebookmarks is None:
1374 # make sure to always includes bookmark data when migrating
1361 # make sure to always includes bookmark data when migrating
1375 # `hg incoming --bundle` to using this function.
1362 # `hg incoming --bundle` to using this function.
1376 kwargs['listkeys'].append('bookmarks')
1363 kwargs['listkeys'].append('bookmarks')
1377
1364
1378 # If this is a full pull / clone and the server supports the clone bundles
1365 # If this is a full pull / clone and the server supports the clone bundles
1379 # feature, tell the server whether we attempted a clone bundle. The
1366 # feature, tell the server whether we attempted a clone bundle. The
1380 # presence of this flag indicates the client supports clone bundles. This
1367 # presence of this flag indicates the client supports clone bundles. This
1381 # will enable the server to treat clients that support clone bundles
1368 # will enable the server to treat clients that support clone bundles
1382 # differently from those that don't.
1369 # differently from those that don't.
1383 if (pullop.remote.capable('clonebundles')
1370 if (pullop.remote.capable('clonebundles')
1384 and pullop.heads is None and list(pullop.common) == [nullid]):
1371 and pullop.heads is None and list(pullop.common) == [nullid]):
1385 kwargs['cbattempted'] = pullop.clonebundleattempted
1372 kwargs['cbattempted'] = pullop.clonebundleattempted
1386
1373
1387 if streaming:
1374 if streaming:
1388 pullop.repo.ui.status(_('streaming all changes\n'))
1375 pullop.repo.ui.status(_('streaming all changes\n'))
1389 elif not pullop.fetch:
1376 elif not pullop.fetch:
1390 pullop.repo.ui.status(_("no changes found\n"))
1377 pullop.repo.ui.status(_("no changes found\n"))
1391 pullop.cgresult = 0
1378 pullop.cgresult = 0
1392 else:
1379 else:
1393 if pullop.heads is None and list(pullop.common) == [nullid]:
1380 if pullop.heads is None and list(pullop.common) == [nullid]:
1394 pullop.repo.ui.status(_("requesting all changes\n"))
1381 pullop.repo.ui.status(_("requesting all changes\n"))
1395 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1382 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1396 remoteversions = bundle2.obsmarkersversion(pullop.remotebundle2caps)
1383 remoteversions = bundle2.obsmarkersversion(pullop.remotebundle2caps)
1397 if obsolete.commonversion(remoteversions) is not None:
1384 if obsolete.commonversion(remoteversions) is not None:
1398 kwargs['obsmarkers'] = True
1385 kwargs['obsmarkers'] = True
1399 pullop.stepsdone.add('obsmarkers')
1386 pullop.stepsdone.add('obsmarkers')
1400 _pullbundle2extraprepare(pullop, kwargs)
1387 _pullbundle2extraprepare(pullop, kwargs)
1401 bundle = pullop.remote.getbundle('pull', **pycompat.strkwargs(kwargs))
1388 bundle = pullop.remote.getbundle('pull', **pycompat.strkwargs(kwargs))
1402 try:
1389 try:
1403 op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
1390 op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
1404 except bundle2.AbortFromPart as exc:
1391 except bundle2.AbortFromPart as exc:
1405 pullop.repo.ui.status(_('remote: abort: %s\n') % exc)
1392 pullop.repo.ui.status(_('remote: abort: %s\n') % exc)
1406 raise error.Abort(_('pull failed on remote'), hint=exc.hint)
1393 raise error.Abort(_('pull failed on remote'), hint=exc.hint)
1407 except error.BundleValueError as exc:
1394 except error.BundleValueError as exc:
1408 raise error.Abort(_('missing support for %s') % exc)
1395 raise error.Abort(_('missing support for %s') % exc)
1409
1396
1410 if pullop.fetch:
1397 if pullop.fetch:
1411 pullop.cgresult = bundle2.combinechangegroupresults(op)
1398 pullop.cgresult = bundle2.combinechangegroupresults(op)
1412
1399
1413 # processing phases change
1400 # processing phases change
1414 for namespace, value in op.records['listkeys']:
1401 for namespace, value in op.records['listkeys']:
1415 if namespace == 'phases':
1402 if namespace == 'phases':
1416 _pullapplyphases(pullop, value)
1403 _pullapplyphases(pullop, value)
1417
1404
1418 # processing bookmark update
1405 # processing bookmark update
1419 for namespace, value in op.records['listkeys']:
1406 for namespace, value in op.records['listkeys']:
1420 if namespace == 'bookmarks':
1407 if namespace == 'bookmarks':
1421 pullop.remotebookmarks = value
1408 pullop.remotebookmarks = value
1422
1409
1423 # bookmark data were either already there or pulled in the bundle
1410 # bookmark data were either already there or pulled in the bundle
1424 if pullop.remotebookmarks is not None:
1411 if pullop.remotebookmarks is not None:
1425 _pullbookmarks(pullop)
1412 _pullbookmarks(pullop)
1426
1413
1427 def _pullbundle2extraprepare(pullop, kwargs):
1414 def _pullbundle2extraprepare(pullop, kwargs):
1428 """hook function so that extensions can extend the getbundle call"""
1415 """hook function so that extensions can extend the getbundle call"""
1429 pass
1416 pass
1430
1417
1431 def _pullchangeset(pullop):
1418 def _pullchangeset(pullop):
1432 """pull changeset from unbundle into the local repo"""
1419 """pull changeset from unbundle into the local repo"""
1433 # We delay the open of the transaction as late as possible so we
1420 # We delay the open of the transaction as late as possible so we
1434 # don't open transaction for nothing or you break future useful
1421 # don't open transaction for nothing or you break future useful
1435 # rollback call
1422 # rollback call
1436 if 'changegroup' in pullop.stepsdone:
1423 if 'changegroup' in pullop.stepsdone:
1437 return
1424 return
1438 pullop.stepsdone.add('changegroup')
1425 pullop.stepsdone.add('changegroup')
1439 if not pullop.fetch:
1426 if not pullop.fetch:
1440 pullop.repo.ui.status(_("no changes found\n"))
1427 pullop.repo.ui.status(_("no changes found\n"))
1441 pullop.cgresult = 0
1428 pullop.cgresult = 0
1442 return
1429 return
1443 tr = pullop.gettransaction()
1430 tr = pullop.gettransaction()
1444 if pullop.heads is None and list(pullop.common) == [nullid]:
1431 if pullop.heads is None and list(pullop.common) == [nullid]:
1445 pullop.repo.ui.status(_("requesting all changes\n"))
1432 pullop.repo.ui.status(_("requesting all changes\n"))
1446 elif pullop.heads is None and pullop.remote.capable('changegroupsubset'):
1433 elif pullop.heads is None and pullop.remote.capable('changegroupsubset'):
1447 # issue1320, avoid a race if remote changed after discovery
1434 # issue1320, avoid a race if remote changed after discovery
1448 pullop.heads = pullop.rheads
1435 pullop.heads = pullop.rheads
1449
1436
1450 if pullop.remote.capable('getbundle'):
1437 if pullop.remote.capable('getbundle'):
1451 # TODO: get bundlecaps from remote
1438 # TODO: get bundlecaps from remote
1452 cg = pullop.remote.getbundle('pull', common=pullop.common,
1439 cg = pullop.remote.getbundle('pull', common=pullop.common,
1453 heads=pullop.heads or pullop.rheads)
1440 heads=pullop.heads or pullop.rheads)
1454 elif pullop.heads is None:
1441 elif pullop.heads is None:
1455 cg = pullop.remote.changegroup(pullop.fetch, 'pull')
1442 cg = pullop.remote.changegroup(pullop.fetch, 'pull')
1456 elif not pullop.remote.capable('changegroupsubset'):
1443 elif not pullop.remote.capable('changegroupsubset'):
1457 raise error.Abort(_("partial pull cannot be done because "
1444 raise error.Abort(_("partial pull cannot be done because "
1458 "other repository doesn't support "
1445 "other repository doesn't support "
1459 "changegroupsubset."))
1446 "changegroupsubset."))
1460 else:
1447 else:
1461 cg = pullop.remote.changegroupsubset(pullop.fetch, pullop.heads, 'pull')
1448 cg = pullop.remote.changegroupsubset(pullop.fetch, pullop.heads, 'pull')
1462 bundleop = bundle2.applybundle(pullop.repo, cg, tr, 'pull',
1449 bundleop = bundle2.applybundle(pullop.repo, cg, tr, 'pull',
1463 pullop.remote.url())
1450 pullop.remote.url())
1464 pullop.cgresult = bundle2.combinechangegroupresults(bundleop)
1451 pullop.cgresult = bundle2.combinechangegroupresults(bundleop)
1465
1452
1466 def _pullphase(pullop):
1453 def _pullphase(pullop):
1467 # Get remote phases data from remote
1454 # Get remote phases data from remote
1468 if 'phases' in pullop.stepsdone:
1455 if 'phases' in pullop.stepsdone:
1469 return
1456 return
1470 remotephases = pullop.remote.listkeys('phases')
1457 remotephases = pullop.remote.listkeys('phases')
1471 _pullapplyphases(pullop, remotephases)
1458 _pullapplyphases(pullop, remotephases)
1472
1459
1473 def _pullapplyphases(pullop, remotephases):
1460 def _pullapplyphases(pullop, remotephases):
1474 """apply phase movement from observed remote state"""
1461 """apply phase movement from observed remote state"""
1475 if 'phases' in pullop.stepsdone:
1462 if 'phases' in pullop.stepsdone:
1476 return
1463 return
1477 pullop.stepsdone.add('phases')
1464 pullop.stepsdone.add('phases')
1478 publishing = bool(remotephases.get('publishing', False))
1465 publishing = bool(remotephases.get('publishing', False))
1479 if remotephases and not publishing:
1466 if remotephases and not publishing:
1480 # remote is new and non-publishing
1467 # remote is new and non-publishing
1481 pheads, _dr = phases.analyzeremotephases(pullop.repo,
1468 pheads, _dr = phases.analyzeremotephases(pullop.repo,
1482 pullop.pulledsubset,
1469 pullop.pulledsubset,
1483 remotephases)
1470 remotephases)
1484 dheads = pullop.pulledsubset
1471 dheads = pullop.pulledsubset
1485 else:
1472 else:
1486 # Remote is old or publishing all common changesets
1473 # Remote is old or publishing all common changesets
1487 # should be seen as public
1474 # should be seen as public
1488 pheads = pullop.pulledsubset
1475 pheads = pullop.pulledsubset
1489 dheads = []
1476 dheads = []
1490 unfi = pullop.repo.unfiltered()
1477 unfi = pullop.repo.unfiltered()
1491 phase = unfi._phasecache.phase
1478 phase = unfi._phasecache.phase
1492 rev = unfi.changelog.nodemap.get
1479 rev = unfi.changelog.nodemap.get
1493 public = phases.public
1480 public = phases.public
1494 draft = phases.draft
1481 draft = phases.draft
1495
1482
1496 # exclude changesets already public locally and update the others
1483 # exclude changesets already public locally and update the others
1497 pheads = [pn for pn in pheads if phase(unfi, rev(pn)) > public]
1484 pheads = [pn for pn in pheads if phase(unfi, rev(pn)) > public]
1498 if pheads:
1485 if pheads:
1499 tr = pullop.gettransaction()
1486 tr = pullop.gettransaction()
1500 phases.advanceboundary(pullop.repo, tr, public, pheads)
1487 phases.advanceboundary(pullop.repo, tr, public, pheads)
1501
1488
1502 # exclude changesets already draft locally and update the others
1489 # exclude changesets already draft locally and update the others
1503 dheads = [pn for pn in dheads if phase(unfi, rev(pn)) > draft]
1490 dheads = [pn for pn in dheads if phase(unfi, rev(pn)) > draft]
1504 if dheads:
1491 if dheads:
1505 tr = pullop.gettransaction()
1492 tr = pullop.gettransaction()
1506 phases.advanceboundary(pullop.repo, tr, draft, dheads)
1493 phases.advanceboundary(pullop.repo, tr, draft, dheads)
1507
1494
1508 def _pullbookmarks(pullop):
1495 def _pullbookmarks(pullop):
1509 """process the remote bookmark information to update the local one"""
1496 """process the remote bookmark information to update the local one"""
1510 if 'bookmarks' in pullop.stepsdone:
1497 if 'bookmarks' in pullop.stepsdone:
1511 return
1498 return
1512 pullop.stepsdone.add('bookmarks')
1499 pullop.stepsdone.add('bookmarks')
1513 repo = pullop.repo
1500 repo = pullop.repo
1514 remotebookmarks = pullop.remotebookmarks
1501 remotebookmarks = pullop.remotebookmarks
1515 remotebookmarks = bookmod.unhexlifybookmarks(remotebookmarks)
1502 remotebookmarks = bookmod.unhexlifybookmarks(remotebookmarks)
1516 bookmod.updatefromremote(repo.ui, repo, remotebookmarks,
1503 bookmod.updatefromremote(repo.ui, repo, remotebookmarks,
1517 pullop.remote.url(),
1504 pullop.remote.url(),
1518 pullop.gettransaction,
1505 pullop.gettransaction,
1519 explicit=pullop.explicitbookmarks)
1506 explicit=pullop.explicitbookmarks)
1520
1507
1521 def _pullobsolete(pullop):
1508 def _pullobsolete(pullop):
1522 """utility function to pull obsolete markers from a remote
1509 """utility function to pull obsolete markers from a remote
1523
1510
1524 The `gettransaction` is function that return the pull transaction, creating
1511 The `gettransaction` is function that return the pull transaction, creating
1525 one if necessary. We return the transaction to inform the calling code that
1512 one if necessary. We return the transaction to inform the calling code that
1526 a new transaction have been created (when applicable).
1513 a new transaction have been created (when applicable).
1527
1514
1528 Exists mostly to allow overriding for experimentation purpose"""
1515 Exists mostly to allow overriding for experimentation purpose"""
1529 if 'obsmarkers' in pullop.stepsdone:
1516 if 'obsmarkers' in pullop.stepsdone:
1530 return
1517 return
1531 pullop.stepsdone.add('obsmarkers')
1518 pullop.stepsdone.add('obsmarkers')
1532 tr = None
1519 tr = None
1533 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1520 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1534 pullop.repo.ui.debug('fetching remote obsolete markers\n')
1521 pullop.repo.ui.debug('fetching remote obsolete markers\n')
1535 remoteobs = pullop.remote.listkeys('obsolete')
1522 remoteobs = pullop.remote.listkeys('obsolete')
1536 if 'dump0' in remoteobs:
1523 if 'dump0' in remoteobs:
1537 tr = pullop.gettransaction()
1524 tr = pullop.gettransaction()
1538 markers = []
1525 markers = []
1539 for key in sorted(remoteobs, reverse=True):
1526 for key in sorted(remoteobs, reverse=True):
1540 if key.startswith('dump'):
1527 if key.startswith('dump'):
1541 data = util.b85decode(remoteobs[key])
1528 data = util.b85decode(remoteobs[key])
1542 version, newmarks = obsolete._readmarkers(data)
1529 version, newmarks = obsolete._readmarkers(data)
1543 markers += newmarks
1530 markers += newmarks
1544 if markers:
1531 if markers:
1545 pullop.repo.obsstore.add(tr, markers)
1532 pullop.repo.obsstore.add(tr, markers)
1546 pullop.repo.invalidatevolatilesets()
1533 pullop.repo.invalidatevolatilesets()
1547 return tr
1534 return tr
1548
1535
1549 def caps20to10(repo):
1536 def caps20to10(repo):
1550 """return a set with appropriate options to use bundle20 during getbundle"""
1537 """return a set with appropriate options to use bundle20 during getbundle"""
1551 caps = {'HG20'}
1538 caps = {'HG20'}
1552 capsblob = bundle2.encodecaps(bundle2.getrepocaps(repo))
1539 capsblob = bundle2.encodecaps(bundle2.getrepocaps(repo))
1553 caps.add('bundle2=' + urlreq.quote(capsblob))
1540 caps.add('bundle2=' + urlreq.quote(capsblob))
1554 return caps
1541 return caps
1555
1542
1556 # List of names of steps to perform for a bundle2 for getbundle, order matters.
1543 # List of names of steps to perform for a bundle2 for getbundle, order matters.
1557 getbundle2partsorder = []
1544 getbundle2partsorder = []
1558
1545
1559 # Mapping between step name and function
1546 # Mapping between step name and function
1560 #
1547 #
1561 # This exists to help extensions wrap steps if necessary
1548 # This exists to help extensions wrap steps if necessary
1562 getbundle2partsmapping = {}
1549 getbundle2partsmapping = {}
1563
1550
1564 def getbundle2partsgenerator(stepname, idx=None):
1551 def getbundle2partsgenerator(stepname, idx=None):
1565 """decorator for function generating bundle2 part for getbundle
1552 """decorator for function generating bundle2 part for getbundle
1566
1553
1567 The function is added to the step -> function mapping and appended to the
1554 The function is added to the step -> function mapping and appended to the
1568 list of steps. Beware that decorated functions will be added in order
1555 list of steps. Beware that decorated functions will be added in order
1569 (this may matter).
1556 (this may matter).
1570
1557
1571 You can only use this decorator for new steps, if you want to wrap a step
1558 You can only use this decorator for new steps, if you want to wrap a step
1572 from an extension, attack the getbundle2partsmapping dictionary directly."""
1559 from an extension, attack the getbundle2partsmapping dictionary directly."""
1573 def dec(func):
1560 def dec(func):
1574 assert stepname not in getbundle2partsmapping
1561 assert stepname not in getbundle2partsmapping
1575 getbundle2partsmapping[stepname] = func
1562 getbundle2partsmapping[stepname] = func
1576 if idx is None:
1563 if idx is None:
1577 getbundle2partsorder.append(stepname)
1564 getbundle2partsorder.append(stepname)
1578 else:
1565 else:
1579 getbundle2partsorder.insert(idx, stepname)
1566 getbundle2partsorder.insert(idx, stepname)
1580 return func
1567 return func
1581 return dec
1568 return dec
1582
1569
1583 def bundle2requested(bundlecaps):
1570 def bundle2requested(bundlecaps):
1584 if bundlecaps is not None:
1571 if bundlecaps is not None:
1585 return any(cap.startswith('HG2') for cap in bundlecaps)
1572 return any(cap.startswith('HG2') for cap in bundlecaps)
1586 return False
1573 return False
1587
1574
1588 def getbundlechunks(repo, source, heads=None, common=None, bundlecaps=None,
1575 def getbundlechunks(repo, source, heads=None, common=None, bundlecaps=None,
1589 **kwargs):
1576 **kwargs):
1590 """Return chunks constituting a bundle's raw data.
1577 """Return chunks constituting a bundle's raw data.
1591
1578
1592 Could be a bundle HG10 or a bundle HG20 depending on bundlecaps
1579 Could be a bundle HG10 or a bundle HG20 depending on bundlecaps
1593 passed.
1580 passed.
1594
1581
1595 Returns an iterator over raw chunks (of varying sizes).
1582 Returns an iterator over raw chunks (of varying sizes).
1596 """
1583 """
1597 kwargs = pycompat.byteskwargs(kwargs)
1584 kwargs = pycompat.byteskwargs(kwargs)
1598 usebundle2 = bundle2requested(bundlecaps)
1585 usebundle2 = bundle2requested(bundlecaps)
1599 # bundle10 case
1586 # bundle10 case
1600 if not usebundle2:
1587 if not usebundle2:
1601 if bundlecaps and not kwargs.get('cg', True):
1588 if bundlecaps and not kwargs.get('cg', True):
1602 raise ValueError(_('request for bundle10 must include changegroup'))
1589 raise ValueError(_('request for bundle10 must include changegroup'))
1603
1590
1604 if kwargs:
1591 if kwargs:
1605 raise ValueError(_('unsupported getbundle arguments: %s')
1592 raise ValueError(_('unsupported getbundle arguments: %s')
1606 % ', '.join(sorted(kwargs.keys())))
1593 % ', '.join(sorted(kwargs.keys())))
1607 outgoing = _computeoutgoing(repo, heads, common)
1594 outgoing = _computeoutgoing(repo, heads, common)
1608 bundler = changegroup.getbundler('01', repo, bundlecaps)
1595 bundler = changegroup.getbundler('01', repo, bundlecaps)
1609 return changegroup.getsubsetraw(repo, outgoing, bundler, source)
1596 return changegroup.getsubsetraw(repo, outgoing, bundler, source)
1610
1597
1611 # bundle20 case
1598 # bundle20 case
1612 b2caps = {}
1599 b2caps = {}
1613 for bcaps in bundlecaps:
1600 for bcaps in bundlecaps:
1614 if bcaps.startswith('bundle2='):
1601 if bcaps.startswith('bundle2='):
1615 blob = urlreq.unquote(bcaps[len('bundle2='):])
1602 blob = urlreq.unquote(bcaps[len('bundle2='):])
1616 b2caps.update(bundle2.decodecaps(blob))
1603 b2caps.update(bundle2.decodecaps(blob))
1617 bundler = bundle2.bundle20(repo.ui, b2caps)
1604 bundler = bundle2.bundle20(repo.ui, b2caps)
1618
1605
1619 kwargs['heads'] = heads
1606 kwargs['heads'] = heads
1620 kwargs['common'] = common
1607 kwargs['common'] = common
1621
1608
1622 for name in getbundle2partsorder:
1609 for name in getbundle2partsorder:
1623 func = getbundle2partsmapping[name]
1610 func = getbundle2partsmapping[name]
1624 func(bundler, repo, source, bundlecaps=bundlecaps, b2caps=b2caps,
1611 func(bundler, repo, source, bundlecaps=bundlecaps, b2caps=b2caps,
1625 **pycompat.strkwargs(kwargs))
1612 **pycompat.strkwargs(kwargs))
1626
1613
1627 return bundler.getchunks()
1614 return bundler.getchunks()
1628
1615
1629 @getbundle2partsgenerator('changegroup')
1616 @getbundle2partsgenerator('changegroup')
1630 def _getbundlechangegrouppart(bundler, repo, source, bundlecaps=None,
1617 def _getbundlechangegrouppart(bundler, repo, source, bundlecaps=None,
1631 b2caps=None, heads=None, common=None, **kwargs):
1618 b2caps=None, heads=None, common=None, **kwargs):
1632 """add a changegroup part to the requested bundle"""
1619 """add a changegroup part to the requested bundle"""
1633 cg = None
1620 cg = None
1634 if kwargs.get('cg', True):
1621 if kwargs.get('cg', True):
1635 # build changegroup bundle here.
1622 # build changegroup bundle here.
1636 version = '01'
1623 version = '01'
1637 cgversions = b2caps.get('changegroup')
1624 cgversions = b2caps.get('changegroup')
1638 if cgversions: # 3.1 and 3.2 ship with an empty value
1625 if cgversions: # 3.1 and 3.2 ship with an empty value
1639 cgversions = [v for v in cgversions
1626 cgversions = [v for v in cgversions
1640 if v in changegroup.supportedoutgoingversions(repo)]
1627 if v in changegroup.supportedoutgoingversions(repo)]
1641 if not cgversions:
1628 if not cgversions:
1642 raise ValueError(_('no common changegroup version'))
1629 raise ValueError(_('no common changegroup version'))
1643 version = max(cgversions)
1630 version = max(cgversions)
1644 outgoing = _computeoutgoing(repo, heads, common)
1631 outgoing = _computeoutgoing(repo, heads, common)
1645 cg = changegroup.getlocalchangegroupraw(repo, source, outgoing,
1632 cg = changegroup.getlocalchangegroupraw(repo, source, outgoing,
1646 bundlecaps=bundlecaps,
1633 bundlecaps=bundlecaps,
1647 version=version)
1634 version=version)
1648
1635
1649 if cg:
1636 if cg:
1650 part = bundler.newpart('changegroup', data=cg)
1637 part = bundler.newpart('changegroup', data=cg)
1651 if cgversions:
1638 if cgversions:
1652 part.addparam('version', version)
1639 part.addparam('version', version)
1653 part.addparam('nbchanges', str(len(outgoing.missing)), mandatory=False)
1640 part.addparam('nbchanges', str(len(outgoing.missing)), mandatory=False)
1654 if 'treemanifest' in repo.requirements:
1641 if 'treemanifest' in repo.requirements:
1655 part.addparam('treemanifest', '1')
1642 part.addparam('treemanifest', '1')
1656
1643
1657 @getbundle2partsgenerator('listkeys')
1644 @getbundle2partsgenerator('listkeys')
1658 def _getbundlelistkeysparts(bundler, repo, source, bundlecaps=None,
1645 def _getbundlelistkeysparts(bundler, repo, source, bundlecaps=None,
1659 b2caps=None, **kwargs):
1646 b2caps=None, **kwargs):
1660 """add parts containing listkeys namespaces to the requested bundle"""
1647 """add parts containing listkeys namespaces to the requested bundle"""
1661 listkeys = kwargs.get('listkeys', ())
1648 listkeys = kwargs.get('listkeys', ())
1662 for namespace in listkeys:
1649 for namespace in listkeys:
1663 part = bundler.newpart('listkeys')
1650 part = bundler.newpart('listkeys')
1664 part.addparam('namespace', namespace)
1651 part.addparam('namespace', namespace)
1665 keys = repo.listkeys(namespace).items()
1652 keys = repo.listkeys(namespace).items()
1666 part.data = pushkey.encodekeys(keys)
1653 part.data = pushkey.encodekeys(keys)
1667
1654
1668 @getbundle2partsgenerator('obsmarkers')
1655 @getbundle2partsgenerator('obsmarkers')
1669 def _getbundleobsmarkerpart(bundler, repo, source, bundlecaps=None,
1656 def _getbundleobsmarkerpart(bundler, repo, source, bundlecaps=None,
1670 b2caps=None, heads=None, **kwargs):
1657 b2caps=None, heads=None, **kwargs):
1671 """add an obsolescence markers part to the requested bundle"""
1658 """add an obsolescence markers part to the requested bundle"""
1672 if kwargs.get('obsmarkers', False):
1659 if kwargs.get('obsmarkers', False):
1673 if heads is None:
1660 if heads is None:
1674 heads = repo.heads()
1661 heads = repo.heads()
1675 subset = [c.node() for c in repo.set('::%ln', heads)]
1662 subset = [c.node() for c in repo.set('::%ln', heads)]
1676 markers = repo.obsstore.relevantmarkers(subset)
1663 markers = repo.obsstore.relevantmarkers(subset)
1677 markers = sorted(markers)
1664 markers = sorted(markers)
1678 bundle2.buildobsmarkerspart(bundler, markers)
1665 bundle2.buildobsmarkerspart(bundler, markers)
1679
1666
1680 @getbundle2partsgenerator('hgtagsfnodes')
1667 @getbundle2partsgenerator('hgtagsfnodes')
1681 def _getbundletagsfnodes(bundler, repo, source, bundlecaps=None,
1668 def _getbundletagsfnodes(bundler, repo, source, bundlecaps=None,
1682 b2caps=None, heads=None, common=None,
1669 b2caps=None, heads=None, common=None,
1683 **kwargs):
1670 **kwargs):
1684 """Transfer the .hgtags filenodes mapping.
1671 """Transfer the .hgtags filenodes mapping.
1685
1672
1686 Only values for heads in this bundle will be transferred.
1673 Only values for heads in this bundle will be transferred.
1687
1674
1688 The part data consists of pairs of 20 byte changeset node and .hgtags
1675 The part data consists of pairs of 20 byte changeset node and .hgtags
1689 filenodes raw values.
1676 filenodes raw values.
1690 """
1677 """
1691 # Don't send unless:
1678 # Don't send unless:
1692 # - changeset are being exchanged,
1679 # - changeset are being exchanged,
1693 # - the client supports it.
1680 # - the client supports it.
1694 if not (kwargs.get('cg', True) and 'hgtagsfnodes' in b2caps):
1681 if not (kwargs.get('cg', True) and 'hgtagsfnodes' in b2caps):
1695 return
1682 return
1696
1683
1697 outgoing = _computeoutgoing(repo, heads, common)
1684 outgoing = _computeoutgoing(repo, heads, common)
1698 bundle2.addparttagsfnodescache(repo, bundler, outgoing)
1685 bundle2.addparttagsfnodescache(repo, bundler, outgoing)
1699
1686
1700 def _getbookmarks(repo, **kwargs):
1687 def _getbookmarks(repo, **kwargs):
1701 """Returns bookmark to node mapping.
1688 """Returns bookmark to node mapping.
1702
1689
1703 This function is primarily used to generate `bookmarks` bundle2 part.
1690 This function is primarily used to generate `bookmarks` bundle2 part.
1704 It is a separate function in order to make it easy to wrap it
1691 It is a separate function in order to make it easy to wrap it
1705 in extensions. Passing `kwargs` to the function makes it easy to
1692 in extensions. Passing `kwargs` to the function makes it easy to
1706 add new parameters in extensions.
1693 add new parameters in extensions.
1707 """
1694 """
1708
1695
1709 return dict(bookmod.listbinbookmarks(repo))
1696 return dict(bookmod.listbinbookmarks(repo))
1710
1697
1711 def check_heads(repo, their_heads, context):
1698 def check_heads(repo, their_heads, context):
1712 """check if the heads of a repo have been modified
1699 """check if the heads of a repo have been modified
1713
1700
1714 Used by peer for unbundling.
1701 Used by peer for unbundling.
1715 """
1702 """
1716 heads = repo.heads()
1703 heads = repo.heads()
1717 heads_hash = hashlib.sha1(''.join(sorted(heads))).digest()
1704 heads_hash = hashlib.sha1(''.join(sorted(heads))).digest()
1718 if not (their_heads == ['force'] or their_heads == heads or
1705 if not (their_heads == ['force'] or their_heads == heads or
1719 their_heads == ['hashed', heads_hash]):
1706 their_heads == ['hashed', heads_hash]):
1720 # someone else committed/pushed/unbundled while we
1707 # someone else committed/pushed/unbundled while we
1721 # were transferring data
1708 # were transferring data
1722 raise error.PushRaced('repository changed while %s - '
1709 raise error.PushRaced('repository changed while %s - '
1723 'please try again' % context)
1710 'please try again' % context)
1724
1711
1725 def unbundle(repo, cg, heads, source, url):
1712 def unbundle(repo, cg, heads, source, url):
1726 """Apply a bundle to a repo.
1713 """Apply a bundle to a repo.
1727
1714
1728 this function makes sure the repo is locked during the application and have
1715 this function makes sure the repo is locked during the application and have
1729 mechanism to check that no push race occurred between the creation of the
1716 mechanism to check that no push race occurred between the creation of the
1730 bundle and its application.
1717 bundle and its application.
1731
1718
1732 If the push was raced as PushRaced exception is raised."""
1719 If the push was raced as PushRaced exception is raised."""
1733 r = 0
1720 r = 0
1734 # need a transaction when processing a bundle2 stream
1721 # need a transaction when processing a bundle2 stream
1735 # [wlock, lock, tr] - needs to be an array so nested functions can modify it
1722 # [wlock, lock, tr] - needs to be an array so nested functions can modify it
1736 lockandtr = [None, None, None]
1723 lockandtr = [None, None, None]
1737 recordout = None
1724 recordout = None
1738 # quick fix for output mismatch with bundle2 in 3.4
1725 # quick fix for output mismatch with bundle2 in 3.4
1739 captureoutput = repo.ui.configbool('experimental', 'bundle2-output-capture')
1726 captureoutput = repo.ui.configbool('experimental', 'bundle2-output-capture')
1740 if url.startswith('remote:http:') or url.startswith('remote:https:'):
1727 if url.startswith('remote:http:') or url.startswith('remote:https:'):
1741 captureoutput = True
1728 captureoutput = True
1742 try:
1729 try:
1743 # note: outside bundle1, 'heads' is expected to be empty and this
1730 # note: outside bundle1, 'heads' is expected to be empty and this
1744 # 'check_heads' call wil be a no-op
1731 # 'check_heads' call wil be a no-op
1745 check_heads(repo, heads, 'uploading changes')
1732 check_heads(repo, heads, 'uploading changes')
1746 # push can proceed
1733 # push can proceed
1747 if not isinstance(cg, bundle2.unbundle20):
1734 if not isinstance(cg, bundle2.unbundle20):
1748 # legacy case: bundle1 (changegroup 01)
1735 # legacy case: bundle1 (changegroup 01)
1749 txnname = "\n".join([source, util.hidepassword(url)])
1736 txnname = "\n".join([source, util.hidepassword(url)])
1750 with repo.lock(), repo.transaction(txnname) as tr:
1737 with repo.lock(), repo.transaction(txnname) as tr:
1751 op = bundle2.applybundle(repo, cg, tr, source, url)
1738 op = bundle2.applybundle(repo, cg, tr, source, url)
1752 r = bundle2.combinechangegroupresults(op)
1739 r = bundle2.combinechangegroupresults(op)
1753 else:
1740 else:
1754 r = None
1741 r = None
1755 try:
1742 try:
1756 def gettransaction():
1743 def gettransaction():
1757 if not lockandtr[2]:
1744 if not lockandtr[2]:
1758 lockandtr[0] = repo.wlock()
1745 lockandtr[0] = repo.wlock()
1759 lockandtr[1] = repo.lock()
1746 lockandtr[1] = repo.lock()
1760 lockandtr[2] = repo.transaction(source)
1747 lockandtr[2] = repo.transaction(source)
1761 lockandtr[2].hookargs['source'] = source
1748 lockandtr[2].hookargs['source'] = source
1762 lockandtr[2].hookargs['url'] = url
1749 lockandtr[2].hookargs['url'] = url
1763 lockandtr[2].hookargs['bundle2'] = '1'
1750 lockandtr[2].hookargs['bundle2'] = '1'
1764 return lockandtr[2]
1751 return lockandtr[2]
1765
1752
1766 # Do greedy locking by default until we're satisfied with lazy
1753 # Do greedy locking by default until we're satisfied with lazy
1767 # locking.
1754 # locking.
1768 if not repo.ui.configbool('experimental', 'bundle2lazylocking'):
1755 if not repo.ui.configbool('experimental', 'bundle2lazylocking'):
1769 gettransaction()
1756 gettransaction()
1770
1757
1771 op = bundle2.bundleoperation(repo, gettransaction,
1758 op = bundle2.bundleoperation(repo, gettransaction,
1772 captureoutput=captureoutput)
1759 captureoutput=captureoutput)
1773 try:
1760 try:
1774 op = bundle2.processbundle(repo, cg, op=op)
1761 op = bundle2.processbundle(repo, cg, op=op)
1775 finally:
1762 finally:
1776 r = op.reply
1763 r = op.reply
1777 if captureoutput and r is not None:
1764 if captureoutput and r is not None:
1778 repo.ui.pushbuffer(error=True, subproc=True)
1765 repo.ui.pushbuffer(error=True, subproc=True)
1779 def recordout(output):
1766 def recordout(output):
1780 r.newpart('output', data=output, mandatory=False)
1767 r.newpart('output', data=output, mandatory=False)
1781 if lockandtr[2] is not None:
1768 if lockandtr[2] is not None:
1782 lockandtr[2].close()
1769 lockandtr[2].close()
1783 except BaseException as exc:
1770 except BaseException as exc:
1784 exc.duringunbundle2 = True
1771 exc.duringunbundle2 = True
1785 if captureoutput and r is not None:
1772 if captureoutput and r is not None:
1786 parts = exc._bundle2salvagedoutput = r.salvageoutput()
1773 parts = exc._bundle2salvagedoutput = r.salvageoutput()
1787 def recordout(output):
1774 def recordout(output):
1788 part = bundle2.bundlepart('output', data=output,
1775 part = bundle2.bundlepart('output', data=output,
1789 mandatory=False)
1776 mandatory=False)
1790 parts.append(part)
1777 parts.append(part)
1791 raise
1778 raise
1792 finally:
1779 finally:
1793 lockmod.release(lockandtr[2], lockandtr[1], lockandtr[0])
1780 lockmod.release(lockandtr[2], lockandtr[1], lockandtr[0])
1794 if recordout is not None:
1781 if recordout is not None:
1795 recordout(repo.ui.popbuffer())
1782 recordout(repo.ui.popbuffer())
1796 return r
1783 return r
1797
1784
1798 def _maybeapplyclonebundle(pullop):
1785 def _maybeapplyclonebundle(pullop):
1799 """Apply a clone bundle from a remote, if possible."""
1786 """Apply a clone bundle from a remote, if possible."""
1800
1787
1801 repo = pullop.repo
1788 repo = pullop.repo
1802 remote = pullop.remote
1789 remote = pullop.remote
1803
1790
1804 if not repo.ui.configbool('ui', 'clonebundles'):
1791 if not repo.ui.configbool('ui', 'clonebundles'):
1805 return
1792 return
1806
1793
1807 # Only run if local repo is empty.
1794 # Only run if local repo is empty.
1808 if len(repo):
1795 if len(repo):
1809 return
1796 return
1810
1797
1811 if pullop.heads:
1798 if pullop.heads:
1812 return
1799 return
1813
1800
1814 if not remote.capable('clonebundles'):
1801 if not remote.capable('clonebundles'):
1815 return
1802 return
1816
1803
1817 res = remote._call('clonebundles')
1804 res = remote._call('clonebundles')
1818
1805
1819 # If we call the wire protocol command, that's good enough to record the
1806 # If we call the wire protocol command, that's good enough to record the
1820 # attempt.
1807 # attempt.
1821 pullop.clonebundleattempted = True
1808 pullop.clonebundleattempted = True
1822
1809
1823 entries = parseclonebundlesmanifest(repo, res)
1810 entries = parseclonebundlesmanifest(repo, res)
1824 if not entries:
1811 if not entries:
1825 repo.ui.note(_('no clone bundles available on remote; '
1812 repo.ui.note(_('no clone bundles available on remote; '
1826 'falling back to regular clone\n'))
1813 'falling back to regular clone\n'))
1827 return
1814 return
1828
1815
1829 entries = filterclonebundleentries(repo, entries)
1816 entries = filterclonebundleentries(repo, entries)
1830 if not entries:
1817 if not entries:
1831 # There is a thundering herd concern here. However, if a server
1818 # There is a thundering herd concern here. However, if a server
1832 # operator doesn't advertise bundles appropriate for its clients,
1819 # operator doesn't advertise bundles appropriate for its clients,
1833 # they deserve what's coming. Furthermore, from a client's
1820 # they deserve what's coming. Furthermore, from a client's
1834 # perspective, no automatic fallback would mean not being able to
1821 # perspective, no automatic fallback would mean not being able to
1835 # clone!
1822 # clone!
1836 repo.ui.warn(_('no compatible clone bundles available on server; '
1823 repo.ui.warn(_('no compatible clone bundles available on server; '
1837 'falling back to regular clone\n'))
1824 'falling back to regular clone\n'))
1838 repo.ui.warn(_('(you may want to report this to the server '
1825 repo.ui.warn(_('(you may want to report this to the server '
1839 'operator)\n'))
1826 'operator)\n'))
1840 return
1827 return
1841
1828
1842 entries = sortclonebundleentries(repo.ui, entries)
1829 entries = sortclonebundleentries(repo.ui, entries)
1843
1830
1844 url = entries[0]['URL']
1831 url = entries[0]['URL']
1845 repo.ui.status(_('applying clone bundle from %s\n') % url)
1832 repo.ui.status(_('applying clone bundle from %s\n') % url)
1846 if trypullbundlefromurl(repo.ui, repo, url):
1833 if trypullbundlefromurl(repo.ui, repo, url):
1847 repo.ui.status(_('finished applying clone bundle\n'))
1834 repo.ui.status(_('finished applying clone bundle\n'))
1848 # Bundle failed.
1835 # Bundle failed.
1849 #
1836 #
1850 # We abort by default to avoid the thundering herd of
1837 # We abort by default to avoid the thundering herd of
1851 # clients flooding a server that was expecting expensive
1838 # clients flooding a server that was expecting expensive
1852 # clone load to be offloaded.
1839 # clone load to be offloaded.
1853 elif repo.ui.configbool('ui', 'clonebundlefallback'):
1840 elif repo.ui.configbool('ui', 'clonebundlefallback'):
1854 repo.ui.warn(_('falling back to normal clone\n'))
1841 repo.ui.warn(_('falling back to normal clone\n'))
1855 else:
1842 else:
1856 raise error.Abort(_('error applying bundle'),
1843 raise error.Abort(_('error applying bundle'),
1857 hint=_('if this error persists, consider contacting '
1844 hint=_('if this error persists, consider contacting '
1858 'the server operator or disable clone '
1845 'the server operator or disable clone '
1859 'bundles via '
1846 'bundles via '
1860 '"--config ui.clonebundles=false"'))
1847 '"--config ui.clonebundles=false"'))
1861
1848
1862 def parseclonebundlesmanifest(repo, s):
1849 def parseclonebundlesmanifest(repo, s):
1863 """Parses the raw text of a clone bundles manifest.
1850 """Parses the raw text of a clone bundles manifest.
1864
1851
1865 Returns a list of dicts. The dicts have a ``URL`` key corresponding
1852 Returns a list of dicts. The dicts have a ``URL`` key corresponding
1866 to the URL and other keys are the attributes for the entry.
1853 to the URL and other keys are the attributes for the entry.
1867 """
1854 """
1868 m = []
1855 m = []
1869 for line in s.splitlines():
1856 for line in s.splitlines():
1870 fields = line.split()
1857 fields = line.split()
1871 if not fields:
1858 if not fields:
1872 continue
1859 continue
1873 attrs = {'URL': fields[0]}
1860 attrs = {'URL': fields[0]}
1874 for rawattr in fields[1:]:
1861 for rawattr in fields[1:]:
1875 key, value = rawattr.split('=', 1)
1862 key, value = rawattr.split('=', 1)
1876 key = urlreq.unquote(key)
1863 key = urlreq.unquote(key)
1877 value = urlreq.unquote(value)
1864 value = urlreq.unquote(value)
1878 attrs[key] = value
1865 attrs[key] = value
1879
1866
1880 # Parse BUNDLESPEC into components. This makes client-side
1867 # Parse BUNDLESPEC into components. This makes client-side
1881 # preferences easier to specify since you can prefer a single
1868 # preferences easier to specify since you can prefer a single
1882 # component of the BUNDLESPEC.
1869 # component of the BUNDLESPEC.
1883 if key == 'BUNDLESPEC':
1870 if key == 'BUNDLESPEC':
1884 try:
1871 try:
1885 comp, version, params = parsebundlespec(repo, value,
1872 comp, version, params = parsebundlespec(repo, value,
1886 externalnames=True)
1873 externalnames=True)
1887 attrs['COMPRESSION'] = comp
1874 attrs['COMPRESSION'] = comp
1888 attrs['VERSION'] = version
1875 attrs['VERSION'] = version
1889 except error.InvalidBundleSpecification:
1876 except error.InvalidBundleSpecification:
1890 pass
1877 pass
1891 except error.UnsupportedBundleSpecification:
1878 except error.UnsupportedBundleSpecification:
1892 pass
1879 pass
1893
1880
1894 m.append(attrs)
1881 m.append(attrs)
1895
1882
1896 return m
1883 return m
1897
1884
1898 def filterclonebundleentries(repo, entries):
1885 def filterclonebundleentries(repo, entries):
1899 """Remove incompatible clone bundle manifest entries.
1886 """Remove incompatible clone bundle manifest entries.
1900
1887
1901 Accepts a list of entries parsed with ``parseclonebundlesmanifest``
1888 Accepts a list of entries parsed with ``parseclonebundlesmanifest``
1902 and returns a new list consisting of only the entries that this client
1889 and returns a new list consisting of only the entries that this client
1903 should be able to apply.
1890 should be able to apply.
1904
1891
1905 There is no guarantee we'll be able to apply all returned entries because
1892 There is no guarantee we'll be able to apply all returned entries because
1906 the metadata we use to filter on may be missing or wrong.
1893 the metadata we use to filter on may be missing or wrong.
1907 """
1894 """
1908 newentries = []
1895 newentries = []
1909 for entry in entries:
1896 for entry in entries:
1910 spec = entry.get('BUNDLESPEC')
1897 spec = entry.get('BUNDLESPEC')
1911 if spec:
1898 if spec:
1912 try:
1899 try:
1913 parsebundlespec(repo, spec, strict=True)
1900 parsebundlespec(repo, spec, strict=True)
1914 except error.InvalidBundleSpecification as e:
1901 except error.InvalidBundleSpecification as e:
1915 repo.ui.debug(str(e) + '\n')
1902 repo.ui.debug(str(e) + '\n')
1916 continue
1903 continue
1917 except error.UnsupportedBundleSpecification as e:
1904 except error.UnsupportedBundleSpecification as e:
1918 repo.ui.debug('filtering %s because unsupported bundle '
1905 repo.ui.debug('filtering %s because unsupported bundle '
1919 'spec: %s\n' % (entry['URL'], str(e)))
1906 'spec: %s\n' % (entry['URL'], str(e)))
1920 continue
1907 continue
1921
1908
1922 if 'REQUIRESNI' in entry and not sslutil.hassni:
1909 if 'REQUIRESNI' in entry and not sslutil.hassni:
1923 repo.ui.debug('filtering %s because SNI not supported\n' %
1910 repo.ui.debug('filtering %s because SNI not supported\n' %
1924 entry['URL'])
1911 entry['URL'])
1925 continue
1912 continue
1926
1913
1927 newentries.append(entry)
1914 newentries.append(entry)
1928
1915
1929 return newentries
1916 return newentries
1930
1917
1931 class clonebundleentry(object):
1918 class clonebundleentry(object):
1932 """Represents an item in a clone bundles manifest.
1919 """Represents an item in a clone bundles manifest.
1933
1920
1934 This rich class is needed to support sorting since sorted() in Python 3
1921 This rich class is needed to support sorting since sorted() in Python 3
1935 doesn't support ``cmp`` and our comparison is complex enough that ``key=``
1922 doesn't support ``cmp`` and our comparison is complex enough that ``key=``
1936 won't work.
1923 won't work.
1937 """
1924 """
1938
1925
1939 def __init__(self, value, prefers):
1926 def __init__(self, value, prefers):
1940 self.value = value
1927 self.value = value
1941 self.prefers = prefers
1928 self.prefers = prefers
1942
1929
1943 def _cmp(self, other):
1930 def _cmp(self, other):
1944 for prefkey, prefvalue in self.prefers:
1931 for prefkey, prefvalue in self.prefers:
1945 avalue = self.value.get(prefkey)
1932 avalue = self.value.get(prefkey)
1946 bvalue = other.value.get(prefkey)
1933 bvalue = other.value.get(prefkey)
1947
1934
1948 # Special case for b missing attribute and a matches exactly.
1935 # Special case for b missing attribute and a matches exactly.
1949 if avalue is not None and bvalue is None and avalue == prefvalue:
1936 if avalue is not None and bvalue is None and avalue == prefvalue:
1950 return -1
1937 return -1
1951
1938
1952 # Special case for a missing attribute and b matches exactly.
1939 # Special case for a missing attribute and b matches exactly.
1953 if bvalue is not None and avalue is None and bvalue == prefvalue:
1940 if bvalue is not None and avalue is None and bvalue == prefvalue:
1954 return 1
1941 return 1
1955
1942
1956 # We can't compare unless attribute present on both.
1943 # We can't compare unless attribute present on both.
1957 if avalue is None or bvalue is None:
1944 if avalue is None or bvalue is None:
1958 continue
1945 continue
1959
1946
1960 # Same values should fall back to next attribute.
1947 # Same values should fall back to next attribute.
1961 if avalue == bvalue:
1948 if avalue == bvalue:
1962 continue
1949 continue
1963
1950
1964 # Exact matches come first.
1951 # Exact matches come first.
1965 if avalue == prefvalue:
1952 if avalue == prefvalue:
1966 return -1
1953 return -1
1967 if bvalue == prefvalue:
1954 if bvalue == prefvalue:
1968 return 1
1955 return 1
1969
1956
1970 # Fall back to next attribute.
1957 # Fall back to next attribute.
1971 continue
1958 continue
1972
1959
1973 # If we got here we couldn't sort by attributes and prefers. Fall
1960 # If we got here we couldn't sort by attributes and prefers. Fall
1974 # back to index order.
1961 # back to index order.
1975 return 0
1962 return 0
1976
1963
1977 def __lt__(self, other):
1964 def __lt__(self, other):
1978 return self._cmp(other) < 0
1965 return self._cmp(other) < 0
1979
1966
1980 def __gt__(self, other):
1967 def __gt__(self, other):
1981 return self._cmp(other) > 0
1968 return self._cmp(other) > 0
1982
1969
1983 def __eq__(self, other):
1970 def __eq__(self, other):
1984 return self._cmp(other) == 0
1971 return self._cmp(other) == 0
1985
1972
1986 def __le__(self, other):
1973 def __le__(self, other):
1987 return self._cmp(other) <= 0
1974 return self._cmp(other) <= 0
1988
1975
1989 def __ge__(self, other):
1976 def __ge__(self, other):
1990 return self._cmp(other) >= 0
1977 return self._cmp(other) >= 0
1991
1978
1992 def __ne__(self, other):
1979 def __ne__(self, other):
1993 return self._cmp(other) != 0
1980 return self._cmp(other) != 0
1994
1981
1995 def sortclonebundleentries(ui, entries):
1982 def sortclonebundleentries(ui, entries):
1996 prefers = ui.configlist('ui', 'clonebundleprefers')
1983 prefers = ui.configlist('ui', 'clonebundleprefers')
1997 if not prefers:
1984 if not prefers:
1998 return list(entries)
1985 return list(entries)
1999
1986
2000 prefers = [p.split('=', 1) for p in prefers]
1987 prefers = [p.split('=', 1) for p in prefers]
2001
1988
2002 items = sorted(clonebundleentry(v, prefers) for v in entries)
1989 items = sorted(clonebundleentry(v, prefers) for v in entries)
2003 return [i.value for i in items]
1990 return [i.value for i in items]
2004
1991
2005 def trypullbundlefromurl(ui, repo, url):
1992 def trypullbundlefromurl(ui, repo, url):
2006 """Attempt to apply a bundle from a URL."""
1993 """Attempt to apply a bundle from a URL."""
2007 with repo.lock(), repo.transaction('bundleurl') as tr:
1994 with repo.lock(), repo.transaction('bundleurl') as tr:
2008 try:
1995 try:
2009 fh = urlmod.open(ui, url)
1996 fh = urlmod.open(ui, url)
2010 cg = readbundle(ui, fh, 'stream')
1997 cg = readbundle(ui, fh, 'stream')
2011
1998
2012 if isinstance(cg, streamclone.streamcloneapplier):
1999 if isinstance(cg, streamclone.streamcloneapplier):
2013 cg.apply(repo)
2000 cg.apply(repo)
2014 else:
2001 else:
2015 bundle2.applybundle(repo, cg, tr, 'clonebundles', url)
2002 bundle2.applybundle(repo, cg, tr, 'clonebundles', url)
2016 return True
2003 return True
2017 except urlerr.httperror as e:
2004 except urlerr.httperror as e:
2018 ui.warn(_('HTTP error fetching bundle: %s\n') % str(e))
2005 ui.warn(_('HTTP error fetching bundle: %s\n') % str(e))
2019 except urlerr.urlerror as e:
2006 except urlerr.urlerror as e:
2020 ui.warn(_('error fetching bundle: %s\n') % e.reason)
2007 ui.warn(_('error fetching bundle: %s\n') % e.reason)
2021
2008
2022 return False
2009 return False
@@ -1,402 +1,399 b''
1 # httppeer.py - HTTP repository proxy classes for mercurial
1 # httppeer.py - HTTP repository proxy classes for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import errno
11 import errno
12 import os
12 import os
13 import socket
13 import socket
14 import struct
14 import struct
15 import tempfile
15 import tempfile
16
16
17 from .i18n import _
17 from .i18n import _
18 from .node import nullid
18 from .node import nullid
19 from . import (
19 from . import (
20 bundle2,
20 bundle2,
21 error,
21 error,
22 httpconnection,
22 httpconnection,
23 pycompat,
23 pycompat,
24 statichttprepo,
24 statichttprepo,
25 url,
25 url,
26 util,
26 util,
27 wireproto,
27 wireproto,
28 )
28 )
29
29
30 httplib = util.httplib
30 httplib = util.httplib
31 urlerr = util.urlerr
31 urlerr = util.urlerr
32 urlreq = util.urlreq
32 urlreq = util.urlreq
33
33
34 def encodevalueinheaders(value, header, limit):
34 def encodevalueinheaders(value, header, limit):
35 """Encode a string value into multiple HTTP headers.
35 """Encode a string value into multiple HTTP headers.
36
36
37 ``value`` will be encoded into 1 or more HTTP headers with the names
37 ``value`` will be encoded into 1 or more HTTP headers with the names
38 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
38 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
39 name + value will be at most ``limit`` bytes long.
39 name + value will be at most ``limit`` bytes long.
40
40
41 Returns an iterable of 2-tuples consisting of header names and values.
41 Returns an iterable of 2-tuples consisting of header names and values.
42 """
42 """
43 fmt = header + '-%s'
43 fmt = header + '-%s'
44 valuelen = limit - len(fmt % '000') - len(': \r\n')
44 valuelen = limit - len(fmt % '000') - len(': \r\n')
45 result = []
45 result = []
46
46
47 n = 0
47 n = 0
48 for i in xrange(0, len(value), valuelen):
48 for i in xrange(0, len(value), valuelen):
49 n += 1
49 n += 1
50 result.append((fmt % str(n), value[i:i + valuelen]))
50 result.append((fmt % str(n), value[i:i + valuelen]))
51
51
52 return result
52 return result
53
53
54 def _wraphttpresponse(resp):
54 def _wraphttpresponse(resp):
55 """Wrap an HTTPResponse with common error handlers.
55 """Wrap an HTTPResponse with common error handlers.
56
56
57 This ensures that any I/O from any consumer raises the appropriate
57 This ensures that any I/O from any consumer raises the appropriate
58 error and messaging.
58 error and messaging.
59 """
59 """
60 origread = resp.read
60 origread = resp.read
61
61
62 class readerproxy(resp.__class__):
62 class readerproxy(resp.__class__):
63 def read(self, size=None):
63 def read(self, size=None):
64 try:
64 try:
65 return origread(size)
65 return origread(size)
66 except httplib.IncompleteRead as e:
66 except httplib.IncompleteRead as e:
67 # e.expected is an integer if length known or None otherwise.
67 # e.expected is an integer if length known or None otherwise.
68 if e.expected:
68 if e.expected:
69 msg = _('HTTP request error (incomplete response; '
69 msg = _('HTTP request error (incomplete response; '
70 'expected %d bytes got %d)') % (e.expected,
70 'expected %d bytes got %d)') % (e.expected,
71 len(e.partial))
71 len(e.partial))
72 else:
72 else:
73 msg = _('HTTP request error (incomplete response)')
73 msg = _('HTTP request error (incomplete response)')
74
74
75 raise error.PeerTransportError(
75 raise error.PeerTransportError(
76 msg,
76 msg,
77 hint=_('this may be an intermittent network failure; '
77 hint=_('this may be an intermittent network failure; '
78 'if the error persists, consider contacting the '
78 'if the error persists, consider contacting the '
79 'network or server operator'))
79 'network or server operator'))
80 except httplib.HTTPException as e:
80 except httplib.HTTPException as e:
81 raise error.PeerTransportError(
81 raise error.PeerTransportError(
82 _('HTTP request error (%s)') % e,
82 _('HTTP request error (%s)') % e,
83 hint=_('this may be an intermittent network failure; '
83 hint=_('this may be an intermittent network failure; '
84 'if the error persists, consider contacting the '
84 'if the error persists, consider contacting the '
85 'network or server operator'))
85 'network or server operator'))
86
86
87 resp.__class__ = readerproxy
87 resp.__class__ = readerproxy
88
88
89 class httppeer(wireproto.wirepeer):
89 class httppeer(wireproto.wirepeer):
90 def __init__(self, ui, path):
90 def __init__(self, ui, path):
91 self.path = path
91 self.path = path
92 self.caps = None
92 self.caps = None
93 self.handler = None
93 self.handler = None
94 self.urlopener = None
94 self.urlopener = None
95 self.requestbuilder = None
95 self.requestbuilder = None
96 u = util.url(path)
96 u = util.url(path)
97 if u.query or u.fragment:
97 if u.query or u.fragment:
98 raise error.Abort(_('unsupported URL component: "%s"') %
98 raise error.Abort(_('unsupported URL component: "%s"') %
99 (u.query or u.fragment))
99 (u.query or u.fragment))
100
100
101 # urllib cannot handle URLs with embedded user or passwd
101 # urllib cannot handle URLs with embedded user or passwd
102 self._url, authinfo = u.authinfo()
102 self._url, authinfo = u.authinfo()
103
103
104 self.ui = ui
104 self.ui = ui
105 self.ui.debug('using %s\n' % self._url)
105 self.ui.debug('using %s\n' % self._url)
106
106
107 self.urlopener = url.opener(ui, authinfo)
107 self.urlopener = url.opener(ui, authinfo)
108 self.requestbuilder = urlreq.request
108 self.requestbuilder = urlreq.request
109
109
110 def __del__(self):
110 def __del__(self):
111 urlopener = getattr(self, 'urlopener', None)
111 urlopener = getattr(self, 'urlopener', None)
112 if urlopener:
112 if urlopener:
113 for h in urlopener.handlers:
113 for h in urlopener.handlers:
114 h.close()
114 h.close()
115 getattr(h, "close_all", lambda : None)()
115 getattr(h, "close_all", lambda : None)()
116
116
117 def url(self):
117 def url(self):
118 return self.path
118 return self.path
119
119
120 # look up capabilities only when needed
120 # look up capabilities only when needed
121
121
122 def _fetchcaps(self):
122 def _fetchcaps(self):
123 self.caps = set(self._call('capabilities').split())
123 self.caps = set(self._call('capabilities').split())
124
124
125 def _capabilities(self):
125 def _capabilities(self):
126 if self.caps is None:
126 if self.caps is None:
127 try:
127 try:
128 self._fetchcaps()
128 self._fetchcaps()
129 except error.RepoError:
129 except error.RepoError:
130 self.caps = set()
130 self.caps = set()
131 self.ui.debug('capabilities: %s\n' %
131 self.ui.debug('capabilities: %s\n' %
132 (' '.join(self.caps or ['none'])))
132 (' '.join(self.caps or ['none'])))
133 return self.caps
133 return self.caps
134
134
135 def lock(self):
136 raise error.Abort(_('operation not supported over http'))
137
138 def _callstream(self, cmd, _compressible=False, **args):
135 def _callstream(self, cmd, _compressible=False, **args):
139 if cmd == 'pushkey':
136 if cmd == 'pushkey':
140 args['data'] = ''
137 args['data'] = ''
141 data = args.pop('data', None)
138 data = args.pop('data', None)
142 headers = args.pop('headers', {})
139 headers = args.pop('headers', {})
143
140
144 self.ui.debug("sending %s command\n" % cmd)
141 self.ui.debug("sending %s command\n" % cmd)
145 q = [('cmd', cmd)]
142 q = [('cmd', cmd)]
146 headersize = 0
143 headersize = 0
147 varyheaders = []
144 varyheaders = []
148 # Important: don't use self.capable() here or else you end up
145 # Important: don't use self.capable() here or else you end up
149 # with infinite recursion when trying to look up capabilities
146 # with infinite recursion when trying to look up capabilities
150 # for the first time.
147 # for the first time.
151 postargsok = self.caps is not None and 'httppostargs' in self.caps
148 postargsok = self.caps is not None and 'httppostargs' in self.caps
152 # TODO: support for httppostargs when data is a file-like
149 # TODO: support for httppostargs when data is a file-like
153 # object rather than a basestring
150 # object rather than a basestring
154 canmungedata = not data or isinstance(data, basestring)
151 canmungedata = not data or isinstance(data, basestring)
155 if postargsok and canmungedata:
152 if postargsok and canmungedata:
156 strargs = urlreq.urlencode(sorted(args.items()))
153 strargs = urlreq.urlencode(sorted(args.items()))
157 if strargs:
154 if strargs:
158 if not data:
155 if not data:
159 data = strargs
156 data = strargs
160 elif isinstance(data, basestring):
157 elif isinstance(data, basestring):
161 data = strargs + data
158 data = strargs + data
162 headers['X-HgArgs-Post'] = len(strargs)
159 headers['X-HgArgs-Post'] = len(strargs)
163 else:
160 else:
164 if len(args) > 0:
161 if len(args) > 0:
165 httpheader = self.capable('httpheader')
162 httpheader = self.capable('httpheader')
166 if httpheader:
163 if httpheader:
167 headersize = int(httpheader.split(',', 1)[0])
164 headersize = int(httpheader.split(',', 1)[0])
168 if headersize > 0:
165 if headersize > 0:
169 # The headers can typically carry more data than the URL.
166 # The headers can typically carry more data than the URL.
170 encargs = urlreq.urlencode(sorted(args.items()))
167 encargs = urlreq.urlencode(sorted(args.items()))
171 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
168 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
172 headersize):
169 headersize):
173 headers[header] = value
170 headers[header] = value
174 varyheaders.append(header)
171 varyheaders.append(header)
175 else:
172 else:
176 q += sorted(args.items())
173 q += sorted(args.items())
177 qs = '?%s' % urlreq.urlencode(q)
174 qs = '?%s' % urlreq.urlencode(q)
178 cu = "%s%s" % (self._url, qs)
175 cu = "%s%s" % (self._url, qs)
179 size = 0
176 size = 0
180 if util.safehasattr(data, 'length'):
177 if util.safehasattr(data, 'length'):
181 size = data.length
178 size = data.length
182 elif data is not None:
179 elif data is not None:
183 size = len(data)
180 size = len(data)
184 if size and self.ui.configbool('ui', 'usehttp2'):
181 if size and self.ui.configbool('ui', 'usehttp2'):
185 headers['Expect'] = '100-Continue'
182 headers['Expect'] = '100-Continue'
186 headers['X-HgHttp2'] = '1'
183 headers['X-HgHttp2'] = '1'
187 if data is not None and 'Content-Type' not in headers:
184 if data is not None and 'Content-Type' not in headers:
188 headers['Content-Type'] = 'application/mercurial-0.1'
185 headers['Content-Type'] = 'application/mercurial-0.1'
189
186
190 # Tell the server we accept application/mercurial-0.2 and multiple
187 # Tell the server we accept application/mercurial-0.2 and multiple
191 # compression formats if the server is capable of emitting those
188 # compression formats if the server is capable of emitting those
192 # payloads.
189 # payloads.
193 protoparams = []
190 protoparams = []
194
191
195 mediatypes = set()
192 mediatypes = set()
196 if self.caps is not None:
193 if self.caps is not None:
197 mt = self.capable('httpmediatype')
194 mt = self.capable('httpmediatype')
198 if mt:
195 if mt:
199 protoparams.append('0.1')
196 protoparams.append('0.1')
200 mediatypes = set(mt.split(','))
197 mediatypes = set(mt.split(','))
201
198
202 if '0.2tx' in mediatypes:
199 if '0.2tx' in mediatypes:
203 protoparams.append('0.2')
200 protoparams.append('0.2')
204
201
205 if '0.2tx' in mediatypes and self.capable('compression'):
202 if '0.2tx' in mediatypes and self.capable('compression'):
206 # We /could/ compare supported compression formats and prune
203 # We /could/ compare supported compression formats and prune
207 # non-mutually supported or error if nothing is mutually supported.
204 # non-mutually supported or error if nothing is mutually supported.
208 # For now, send the full list to the server and have it error.
205 # For now, send the full list to the server and have it error.
209 comps = [e.wireprotosupport().name for e in
206 comps = [e.wireprotosupport().name for e in
210 util.compengines.supportedwireengines(util.CLIENTROLE)]
207 util.compengines.supportedwireengines(util.CLIENTROLE)]
211 protoparams.append('comp=%s' % ','.join(comps))
208 protoparams.append('comp=%s' % ','.join(comps))
212
209
213 if protoparams:
210 if protoparams:
214 protoheaders = encodevalueinheaders(' '.join(protoparams),
211 protoheaders = encodevalueinheaders(' '.join(protoparams),
215 'X-HgProto',
212 'X-HgProto',
216 headersize or 1024)
213 headersize or 1024)
217 for header, value in protoheaders:
214 for header, value in protoheaders:
218 headers[header] = value
215 headers[header] = value
219 varyheaders.append(header)
216 varyheaders.append(header)
220
217
221 if varyheaders:
218 if varyheaders:
222 headers['Vary'] = ','.join(varyheaders)
219 headers['Vary'] = ','.join(varyheaders)
223
220
224 req = self.requestbuilder(cu, data, headers)
221 req = self.requestbuilder(cu, data, headers)
225
222
226 if data is not None:
223 if data is not None:
227 self.ui.debug("sending %s bytes\n" % size)
224 self.ui.debug("sending %s bytes\n" % size)
228 req.add_unredirected_header('Content-Length', '%d' % size)
225 req.add_unredirected_header('Content-Length', '%d' % size)
229 try:
226 try:
230 resp = self.urlopener.open(req)
227 resp = self.urlopener.open(req)
231 except urlerr.httperror as inst:
228 except urlerr.httperror as inst:
232 if inst.code == 401:
229 if inst.code == 401:
233 raise error.Abort(_('authorization failed'))
230 raise error.Abort(_('authorization failed'))
234 raise
231 raise
235 except httplib.HTTPException as inst:
232 except httplib.HTTPException as inst:
236 self.ui.debug('http error while sending %s command\n' % cmd)
233 self.ui.debug('http error while sending %s command\n' % cmd)
237 self.ui.traceback()
234 self.ui.traceback()
238 raise IOError(None, inst)
235 raise IOError(None, inst)
239
236
240 # Insert error handlers for common I/O failures.
237 # Insert error handlers for common I/O failures.
241 _wraphttpresponse(resp)
238 _wraphttpresponse(resp)
242
239
243 # record the url we got redirected to
240 # record the url we got redirected to
244 resp_url = resp.geturl()
241 resp_url = resp.geturl()
245 if resp_url.endswith(qs):
242 if resp_url.endswith(qs):
246 resp_url = resp_url[:-len(qs)]
243 resp_url = resp_url[:-len(qs)]
247 if self._url.rstrip('/') != resp_url.rstrip('/'):
244 if self._url.rstrip('/') != resp_url.rstrip('/'):
248 if not self.ui.quiet:
245 if not self.ui.quiet:
249 self.ui.warn(_('real URL is %s\n') % resp_url)
246 self.ui.warn(_('real URL is %s\n') % resp_url)
250 self._url = resp_url
247 self._url = resp_url
251 try:
248 try:
252 proto = resp.getheader('content-type')
249 proto = resp.getheader('content-type')
253 except AttributeError:
250 except AttributeError:
254 proto = resp.headers.get('content-type', '')
251 proto = resp.headers.get('content-type', '')
255
252
256 safeurl = util.hidepassword(self._url)
253 safeurl = util.hidepassword(self._url)
257 if proto.startswith('application/hg-error'):
254 if proto.startswith('application/hg-error'):
258 raise error.OutOfBandError(resp.read())
255 raise error.OutOfBandError(resp.read())
259 # accept old "text/plain" and "application/hg-changegroup" for now
256 # accept old "text/plain" and "application/hg-changegroup" for now
260 if not (proto.startswith('application/mercurial-') or
257 if not (proto.startswith('application/mercurial-') or
261 (proto.startswith('text/plain')
258 (proto.startswith('text/plain')
262 and not resp.headers.get('content-length')) or
259 and not resp.headers.get('content-length')) or
263 proto.startswith('application/hg-changegroup')):
260 proto.startswith('application/hg-changegroup')):
264 self.ui.debug("requested URL: '%s'\n" % util.hidepassword(cu))
261 self.ui.debug("requested URL: '%s'\n" % util.hidepassword(cu))
265 raise error.RepoError(
262 raise error.RepoError(
266 _("'%s' does not appear to be an hg repository:\n"
263 _("'%s' does not appear to be an hg repository:\n"
267 "---%%<--- (%s)\n%s\n---%%<---\n")
264 "---%%<--- (%s)\n%s\n---%%<---\n")
268 % (safeurl, proto or 'no content-type', resp.read(1024)))
265 % (safeurl, proto or 'no content-type', resp.read(1024)))
269
266
270 if proto.startswith('application/mercurial-'):
267 if proto.startswith('application/mercurial-'):
271 try:
268 try:
272 version = proto.split('-', 1)[1]
269 version = proto.split('-', 1)[1]
273 version_info = tuple([int(n) for n in version.split('.')])
270 version_info = tuple([int(n) for n in version.split('.')])
274 except ValueError:
271 except ValueError:
275 raise error.RepoError(_("'%s' sent a broken Content-Type "
272 raise error.RepoError(_("'%s' sent a broken Content-Type "
276 "header (%s)") % (safeurl, proto))
273 "header (%s)") % (safeurl, proto))
277
274
278 # TODO consider switching to a decompression reader that uses
275 # TODO consider switching to a decompression reader that uses
279 # generators.
276 # generators.
280 if version_info == (0, 1):
277 if version_info == (0, 1):
281 if _compressible:
278 if _compressible:
282 return util.compengines['zlib'].decompressorreader(resp)
279 return util.compengines['zlib'].decompressorreader(resp)
283 return resp
280 return resp
284 elif version_info == (0, 2):
281 elif version_info == (0, 2):
285 # application/mercurial-0.2 always identifies the compression
282 # application/mercurial-0.2 always identifies the compression
286 # engine in the payload header.
283 # engine in the payload header.
287 elen = struct.unpack('B', resp.read(1))[0]
284 elen = struct.unpack('B', resp.read(1))[0]
288 ename = resp.read(elen)
285 ename = resp.read(elen)
289 engine = util.compengines.forwiretype(ename)
286 engine = util.compengines.forwiretype(ename)
290 return engine.decompressorreader(resp)
287 return engine.decompressorreader(resp)
291 else:
288 else:
292 raise error.RepoError(_("'%s' uses newer protocol %s") %
289 raise error.RepoError(_("'%s' uses newer protocol %s") %
293 (safeurl, version))
290 (safeurl, version))
294
291
295 if _compressible:
292 if _compressible:
296 return util.compengines['zlib'].decompressorreader(resp)
293 return util.compengines['zlib'].decompressorreader(resp)
297
294
298 return resp
295 return resp
299
296
300 def _call(self, cmd, **args):
297 def _call(self, cmd, **args):
301 fp = self._callstream(cmd, **args)
298 fp = self._callstream(cmd, **args)
302 try:
299 try:
303 return fp.read()
300 return fp.read()
304 finally:
301 finally:
305 # if using keepalive, allow connection to be reused
302 # if using keepalive, allow connection to be reused
306 fp.close()
303 fp.close()
307
304
308 def _callpush(self, cmd, cg, **args):
305 def _callpush(self, cmd, cg, **args):
309 # have to stream bundle to a temp file because we do not have
306 # have to stream bundle to a temp file because we do not have
310 # http 1.1 chunked transfer.
307 # http 1.1 chunked transfer.
311
308
312 types = self.capable('unbundle')
309 types = self.capable('unbundle')
313 try:
310 try:
314 types = types.split(',')
311 types = types.split(',')
315 except AttributeError:
312 except AttributeError:
316 # servers older than d1b16a746db6 will send 'unbundle' as a
313 # servers older than d1b16a746db6 will send 'unbundle' as a
317 # boolean capability. They only support headerless/uncompressed
314 # boolean capability. They only support headerless/uncompressed
318 # bundles.
315 # bundles.
319 types = [""]
316 types = [""]
320 for x in types:
317 for x in types:
321 if x in bundle2.bundletypes:
318 if x in bundle2.bundletypes:
322 type = x
319 type = x
323 break
320 break
324
321
325 tempname = bundle2.writebundle(self.ui, cg, None, type)
322 tempname = bundle2.writebundle(self.ui, cg, None, type)
326 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
323 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
327 headers = {'Content-Type': 'application/mercurial-0.1'}
324 headers = {'Content-Type': 'application/mercurial-0.1'}
328
325
329 try:
326 try:
330 r = self._call(cmd, data=fp, headers=headers, **args)
327 r = self._call(cmd, data=fp, headers=headers, **args)
331 vals = r.split('\n', 1)
328 vals = r.split('\n', 1)
332 if len(vals) < 2:
329 if len(vals) < 2:
333 raise error.ResponseError(_("unexpected response:"), r)
330 raise error.ResponseError(_("unexpected response:"), r)
334 return vals
331 return vals
335 except socket.error as err:
332 except socket.error as err:
336 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
333 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
337 raise error.Abort(_('push failed: %s') % err.args[1])
334 raise error.Abort(_('push failed: %s') % err.args[1])
338 raise error.Abort(err.args[1])
335 raise error.Abort(err.args[1])
339 finally:
336 finally:
340 fp.close()
337 fp.close()
341 os.unlink(tempname)
338 os.unlink(tempname)
342
339
343 def _calltwowaystream(self, cmd, fp, **args):
340 def _calltwowaystream(self, cmd, fp, **args):
344 fh = None
341 fh = None
345 fp_ = None
342 fp_ = None
346 filename = None
343 filename = None
347 try:
344 try:
348 # dump bundle to disk
345 # dump bundle to disk
349 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
346 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
350 fh = os.fdopen(fd, pycompat.sysstr("wb"))
347 fh = os.fdopen(fd, pycompat.sysstr("wb"))
351 d = fp.read(4096)
348 d = fp.read(4096)
352 while d:
349 while d:
353 fh.write(d)
350 fh.write(d)
354 d = fp.read(4096)
351 d = fp.read(4096)
355 fh.close()
352 fh.close()
356 # start http push
353 # start http push
357 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
354 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
358 headers = {'Content-Type': 'application/mercurial-0.1'}
355 headers = {'Content-Type': 'application/mercurial-0.1'}
359 return self._callstream(cmd, data=fp_, headers=headers, **args)
356 return self._callstream(cmd, data=fp_, headers=headers, **args)
360 finally:
357 finally:
361 if fp_ is not None:
358 if fp_ is not None:
362 fp_.close()
359 fp_.close()
363 if fh is not None:
360 if fh is not None:
364 fh.close()
361 fh.close()
365 os.unlink(filename)
362 os.unlink(filename)
366
363
367 def _callcompressable(self, cmd, **args):
364 def _callcompressable(self, cmd, **args):
368 return self._callstream(cmd, _compressible=True, **args)
365 return self._callstream(cmd, _compressible=True, **args)
369
366
370 def _abort(self, exception):
367 def _abort(self, exception):
371 raise exception
368 raise exception
372
369
373 class httpspeer(httppeer):
370 class httpspeer(httppeer):
374 def __init__(self, ui, path):
371 def __init__(self, ui, path):
375 if not url.has_https:
372 if not url.has_https:
376 raise error.Abort(_('Python support for SSL and HTTPS '
373 raise error.Abort(_('Python support for SSL and HTTPS '
377 'is not installed'))
374 'is not installed'))
378 httppeer.__init__(self, ui, path)
375 httppeer.__init__(self, ui, path)
379
376
380 def instance(ui, path, create):
377 def instance(ui, path, create):
381 if create:
378 if create:
382 raise error.Abort(_('cannot create new http repository'))
379 raise error.Abort(_('cannot create new http repository'))
383 try:
380 try:
384 if path.startswith('https:'):
381 if path.startswith('https:'):
385 inst = httpspeer(ui, path)
382 inst = httpspeer(ui, path)
386 else:
383 else:
387 inst = httppeer(ui, path)
384 inst = httppeer(ui, path)
388 try:
385 try:
389 # Try to do useful work when checking compatibility.
386 # Try to do useful work when checking compatibility.
390 # Usually saves a roundtrip since we want the caps anyway.
387 # Usually saves a roundtrip since we want the caps anyway.
391 inst._fetchcaps()
388 inst._fetchcaps()
392 except error.RepoError:
389 except error.RepoError:
393 # No luck, try older compatibility check.
390 # No luck, try older compatibility check.
394 inst.between([(nullid, nullid)])
391 inst.between([(nullid, nullid)])
395 return inst
392 return inst
396 except error.RepoError as httpexception:
393 except error.RepoError as httpexception:
397 try:
394 try:
398 r = statichttprepo.instance(ui, "static-" + path, create)
395 r = statichttprepo.instance(ui, "static-" + path, create)
399 ui.note(_('(falling back to static-http)\n'))
396 ui.note(_('(falling back to static-http)\n'))
400 return r
397 return r
401 except error.RepoError:
398 except error.RepoError:
402 raise httpexception # use the original http RepoError instead
399 raise httpexception # use the original http RepoError instead
@@ -1,2262 +1,2259 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 sparse,
56 sparse,
57 store,
57 store,
58 subrepo,
58 subrepo,
59 tags as tagsmod,
59 tags as tagsmod,
60 transaction,
60 transaction,
61 txnutil,
61 txnutil,
62 util,
62 util,
63 vfs as vfsmod,
63 vfs as vfsmod,
64 )
64 )
65
65
66 release = lockmod.release
66 release = lockmod.release
67 urlerr = util.urlerr
67 urlerr = util.urlerr
68 urlreq = util.urlreq
68 urlreq = util.urlreq
69
69
70 # set of (path, vfs-location) tuples. vfs-location is:
70 # set of (path, vfs-location) tuples. vfs-location is:
71 # - 'plain for vfs relative paths
71 # - 'plain for vfs relative paths
72 # - '' for svfs relative paths
72 # - '' for svfs relative paths
73 _cachedfiles = set()
73 _cachedfiles = set()
74
74
75 class _basefilecache(scmutil.filecache):
75 class _basefilecache(scmutil.filecache):
76 """All filecache usage on repo are done for logic that should be unfiltered
76 """All filecache usage on repo are done for logic that should be unfiltered
77 """
77 """
78 def __get__(self, repo, type=None):
78 def __get__(self, repo, type=None):
79 if repo is None:
79 if repo is None:
80 return self
80 return self
81 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
81 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
82 def __set__(self, repo, value):
82 def __set__(self, repo, value):
83 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
83 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
84 def __delete__(self, repo):
84 def __delete__(self, repo):
85 return super(_basefilecache, self).__delete__(repo.unfiltered())
85 return super(_basefilecache, self).__delete__(repo.unfiltered())
86
86
87 class repofilecache(_basefilecache):
87 class repofilecache(_basefilecache):
88 """filecache for files in .hg but outside of .hg/store"""
88 """filecache for files in .hg but outside of .hg/store"""
89 def __init__(self, *paths):
89 def __init__(self, *paths):
90 super(repofilecache, self).__init__(*paths)
90 super(repofilecache, self).__init__(*paths)
91 for path in paths:
91 for path in paths:
92 _cachedfiles.add((path, 'plain'))
92 _cachedfiles.add((path, 'plain'))
93
93
94 def join(self, obj, fname):
94 def join(self, obj, fname):
95 return obj.vfs.join(fname)
95 return obj.vfs.join(fname)
96
96
97 class storecache(_basefilecache):
97 class storecache(_basefilecache):
98 """filecache for files in the store"""
98 """filecache for files in the store"""
99 def __init__(self, *paths):
99 def __init__(self, *paths):
100 super(storecache, self).__init__(*paths)
100 super(storecache, self).__init__(*paths)
101 for path in paths:
101 for path in paths:
102 _cachedfiles.add((path, ''))
102 _cachedfiles.add((path, ''))
103
103
104 def join(self, obj, fname):
104 def join(self, obj, fname):
105 return obj.sjoin(fname)
105 return obj.sjoin(fname)
106
106
107 def isfilecached(repo, name):
107 def isfilecached(repo, name):
108 """check if a repo has already cached "name" filecache-ed property
108 """check if a repo has already cached "name" filecache-ed property
109
109
110 This returns (cachedobj-or-None, iscached) tuple.
110 This returns (cachedobj-or-None, iscached) tuple.
111 """
111 """
112 cacheentry = repo.unfiltered()._filecache.get(name, None)
112 cacheentry = repo.unfiltered()._filecache.get(name, None)
113 if not cacheentry:
113 if not cacheentry:
114 return None, False
114 return None, False
115 return cacheentry.obj, True
115 return cacheentry.obj, True
116
116
117 class unfilteredpropertycache(util.propertycache):
117 class unfilteredpropertycache(util.propertycache):
118 """propertycache that apply to unfiltered repo only"""
118 """propertycache that apply to unfiltered repo only"""
119
119
120 def __get__(self, repo, type=None):
120 def __get__(self, repo, type=None):
121 unfi = repo.unfiltered()
121 unfi = repo.unfiltered()
122 if unfi is repo:
122 if unfi is repo:
123 return super(unfilteredpropertycache, self).__get__(unfi)
123 return super(unfilteredpropertycache, self).__get__(unfi)
124 return getattr(unfi, self.name)
124 return getattr(unfi, self.name)
125
125
126 class filteredpropertycache(util.propertycache):
126 class filteredpropertycache(util.propertycache):
127 """propertycache that must take filtering in account"""
127 """propertycache that must take filtering in account"""
128
128
129 def cachevalue(self, obj, value):
129 def cachevalue(self, obj, value):
130 object.__setattr__(obj, self.name, value)
130 object.__setattr__(obj, self.name, value)
131
131
132
132
133 def hasunfilteredcache(repo, name):
133 def hasunfilteredcache(repo, name):
134 """check if a repo has an unfilteredpropertycache value for <name>"""
134 """check if a repo has an unfilteredpropertycache value for <name>"""
135 return name in vars(repo.unfiltered())
135 return name in vars(repo.unfiltered())
136
136
137 def unfilteredmethod(orig):
137 def unfilteredmethod(orig):
138 """decorate method that always need to be run on unfiltered version"""
138 """decorate method that always need to be run on unfiltered version"""
139 def wrapper(repo, *args, **kwargs):
139 def wrapper(repo, *args, **kwargs):
140 return orig(repo.unfiltered(), *args, **kwargs)
140 return orig(repo.unfiltered(), *args, **kwargs)
141 return wrapper
141 return wrapper
142
142
143 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
143 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
144 'unbundle'}
144 'unbundle'}
145 legacycaps = moderncaps.union({'changegroupsubset'})
145 legacycaps = moderncaps.union({'changegroupsubset'})
146
146
147 class localpeer(peer.peerrepository):
147 class localpeer(peer.peerrepository):
148 '''peer for a local repo; reflects only the most recent API'''
148 '''peer for a local repo; reflects only the most recent API'''
149
149
150 def __init__(self, repo, caps=None):
150 def __init__(self, repo, caps=None):
151 if caps is None:
151 if caps is None:
152 caps = moderncaps.copy()
152 caps = moderncaps.copy()
153 peer.peerrepository.__init__(self)
153 peer.peerrepository.__init__(self)
154 self._repo = repo.filtered('served')
154 self._repo = repo.filtered('served')
155 self.ui = repo.ui
155 self.ui = repo.ui
156 self._caps = repo._restrictcapabilities(caps)
156 self._caps = repo._restrictcapabilities(caps)
157 self.requirements = repo.requirements
157 self.requirements = repo.requirements
158 self.supportedformats = repo.supportedformats
158 self.supportedformats = repo.supportedformats
159
159
160 def close(self):
160 def close(self):
161 self._repo.close()
161 self._repo.close()
162
162
163 def _capabilities(self):
163 def _capabilities(self):
164 return self._caps
164 return self._caps
165
165
166 def local(self):
166 def local(self):
167 return self._repo
167 return self._repo
168
168
169 def canpush(self):
169 def canpush(self):
170 return True
170 return True
171
171
172 def url(self):
172 def url(self):
173 return self._repo.url()
173 return self._repo.url()
174
174
175 def lookup(self, key):
175 def lookup(self, key):
176 return self._repo.lookup(key)
176 return self._repo.lookup(key)
177
177
178 def branchmap(self):
178 def branchmap(self):
179 return self._repo.branchmap()
179 return self._repo.branchmap()
180
180
181 def heads(self):
181 def heads(self):
182 return self._repo.heads()
182 return self._repo.heads()
183
183
184 def known(self, nodes):
184 def known(self, nodes):
185 return self._repo.known(nodes)
185 return self._repo.known(nodes)
186
186
187 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
187 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
188 **kwargs):
188 **kwargs):
189 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
189 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
190 common=common, bundlecaps=bundlecaps,
190 common=common, bundlecaps=bundlecaps,
191 **kwargs)
191 **kwargs)
192 cb = util.chunkbuffer(chunks)
192 cb = util.chunkbuffer(chunks)
193
193
194 if exchange.bundle2requested(bundlecaps):
194 if exchange.bundle2requested(bundlecaps):
195 # When requesting a bundle2, getbundle returns a stream to make the
195 # When requesting a bundle2, getbundle returns a stream to make the
196 # wire level function happier. We need to build a proper object
196 # wire level function happier. We need to build a proper object
197 # from it in local peer.
197 # from it in local peer.
198 return bundle2.getunbundler(self.ui, cb)
198 return bundle2.getunbundler(self.ui, cb)
199 else:
199 else:
200 return changegroup.getunbundler('01', cb, None)
200 return changegroup.getunbundler('01', cb, None)
201
201
202 # TODO We might want to move the next two calls into legacypeer and add
202 # TODO We might want to move the next two calls into legacypeer and add
203 # unbundle instead.
203 # unbundle instead.
204
204
205 def unbundle(self, cg, heads, url):
205 def unbundle(self, cg, heads, url):
206 """apply a bundle on a repo
206 """apply a bundle on a repo
207
207
208 This function handles the repo locking itself."""
208 This function handles the repo locking itself."""
209 try:
209 try:
210 try:
210 try:
211 cg = exchange.readbundle(self.ui, cg, None)
211 cg = exchange.readbundle(self.ui, cg, None)
212 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
212 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
213 if util.safehasattr(ret, 'getchunks'):
213 if util.safehasattr(ret, 'getchunks'):
214 # This is a bundle20 object, turn it into an unbundler.
214 # This is a bundle20 object, turn it into an unbundler.
215 # This little dance should be dropped eventually when the
215 # This little dance should be dropped eventually when the
216 # API is finally improved.
216 # API is finally improved.
217 stream = util.chunkbuffer(ret.getchunks())
217 stream = util.chunkbuffer(ret.getchunks())
218 ret = bundle2.getunbundler(self.ui, stream)
218 ret = bundle2.getunbundler(self.ui, stream)
219 return ret
219 return ret
220 except Exception as exc:
220 except Exception as exc:
221 # If the exception contains output salvaged from a bundle2
221 # If the exception contains output salvaged from a bundle2
222 # reply, we need to make sure it is printed before continuing
222 # reply, we need to make sure it is printed before continuing
223 # to fail. So we build a bundle2 with such output and consume
223 # to fail. So we build a bundle2 with such output and consume
224 # it directly.
224 # it directly.
225 #
225 #
226 # This is not very elegant but allows a "simple" solution for
226 # This is not very elegant but allows a "simple" solution for
227 # issue4594
227 # issue4594
228 output = getattr(exc, '_bundle2salvagedoutput', ())
228 output = getattr(exc, '_bundle2salvagedoutput', ())
229 if output:
229 if output:
230 bundler = bundle2.bundle20(self._repo.ui)
230 bundler = bundle2.bundle20(self._repo.ui)
231 for out in output:
231 for out in output:
232 bundler.addpart(out)
232 bundler.addpart(out)
233 stream = util.chunkbuffer(bundler.getchunks())
233 stream = util.chunkbuffer(bundler.getchunks())
234 b = bundle2.getunbundler(self.ui, stream)
234 b = bundle2.getunbundler(self.ui, stream)
235 bundle2.processbundle(self._repo, b)
235 bundle2.processbundle(self._repo, b)
236 raise
236 raise
237 except error.PushRaced as exc:
237 except error.PushRaced as exc:
238 raise error.ResponseError(_('push failed:'), str(exc))
238 raise error.ResponseError(_('push failed:'), str(exc))
239
239
240 def lock(self):
241 return self._repo.lock()
242
243 def pushkey(self, namespace, key, old, new):
240 def pushkey(self, namespace, key, old, new):
244 return self._repo.pushkey(namespace, key, old, new)
241 return self._repo.pushkey(namespace, key, old, new)
245
242
246 def listkeys(self, namespace):
243 def listkeys(self, namespace):
247 return self._repo.listkeys(namespace)
244 return self._repo.listkeys(namespace)
248
245
249 def debugwireargs(self, one, two, three=None, four=None, five=None):
246 def debugwireargs(self, one, two, three=None, four=None, five=None):
250 '''used to test argument passing over the wire'''
247 '''used to test argument passing over the wire'''
251 return "%s %s %s %s %s" % (one, two, three, four, five)
248 return "%s %s %s %s %s" % (one, two, three, four, five)
252
249
253 class locallegacypeer(localpeer):
250 class locallegacypeer(localpeer):
254 '''peer extension which implements legacy methods too; used for tests with
251 '''peer extension which implements legacy methods too; used for tests with
255 restricted capabilities'''
252 restricted capabilities'''
256
253
257 def __init__(self, repo):
254 def __init__(self, repo):
258 localpeer.__init__(self, repo, caps=legacycaps)
255 localpeer.__init__(self, repo, caps=legacycaps)
259
256
260 def branches(self, nodes):
257 def branches(self, nodes):
261 return self._repo.branches(nodes)
258 return self._repo.branches(nodes)
262
259
263 def between(self, pairs):
260 def between(self, pairs):
264 return self._repo.between(pairs)
261 return self._repo.between(pairs)
265
262
266 def changegroup(self, basenodes, source):
263 def changegroup(self, basenodes, source):
267 return changegroup.changegroup(self._repo, basenodes, source)
264 return changegroup.changegroup(self._repo, basenodes, source)
268
265
269 def changegroupsubset(self, bases, heads, source):
266 def changegroupsubset(self, bases, heads, source):
270 return changegroup.changegroupsubset(self._repo, bases, heads, source)
267 return changegroup.changegroupsubset(self._repo, bases, heads, source)
271
268
272 # Increment the sub-version when the revlog v2 format changes to lock out old
269 # Increment the sub-version when the revlog v2 format changes to lock out old
273 # clients.
270 # clients.
274 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
271 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
275
272
276 class localrepository(object):
273 class localrepository(object):
277
274
278 supportedformats = {
275 supportedformats = {
279 'revlogv1',
276 'revlogv1',
280 'generaldelta',
277 'generaldelta',
281 'treemanifest',
278 'treemanifest',
282 'manifestv2',
279 'manifestv2',
283 REVLOGV2_REQUIREMENT,
280 REVLOGV2_REQUIREMENT,
284 }
281 }
285 _basesupported = supportedformats | {
282 _basesupported = supportedformats | {
286 'store',
283 'store',
287 'fncache',
284 'fncache',
288 'shared',
285 'shared',
289 'relshared',
286 'relshared',
290 'dotencode',
287 'dotencode',
291 'exp-sparse',
288 'exp-sparse',
292 }
289 }
293 openerreqs = {
290 openerreqs = {
294 'revlogv1',
291 'revlogv1',
295 'generaldelta',
292 'generaldelta',
296 'treemanifest',
293 'treemanifest',
297 'manifestv2',
294 'manifestv2',
298 }
295 }
299
296
300 # a list of (ui, featureset) functions.
297 # a list of (ui, featureset) functions.
301 # only functions defined in module of enabled extensions are invoked
298 # only functions defined in module of enabled extensions are invoked
302 featuresetupfuncs = set()
299 featuresetupfuncs = set()
303
300
304 # list of prefix for file which can be written without 'wlock'
301 # list of prefix for file which can be written without 'wlock'
305 # Extensions should extend this list when needed
302 # Extensions should extend this list when needed
306 _wlockfreeprefix = {
303 _wlockfreeprefix = {
307 # We migh consider requiring 'wlock' for the next
304 # We migh consider requiring 'wlock' for the next
308 # two, but pretty much all the existing code assume
305 # two, but pretty much all the existing code assume
309 # wlock is not needed so we keep them excluded for
306 # wlock is not needed so we keep them excluded for
310 # now.
307 # now.
311 'hgrc',
308 'hgrc',
312 'requires',
309 'requires',
313 # XXX cache is a complicatged business someone
310 # XXX cache is a complicatged business someone
314 # should investigate this in depth at some point
311 # should investigate this in depth at some point
315 'cache/',
312 'cache/',
316 # XXX shouldn't be dirstate covered by the wlock?
313 # XXX shouldn't be dirstate covered by the wlock?
317 'dirstate',
314 'dirstate',
318 # XXX bisect was still a bit too messy at the time
315 # XXX bisect was still a bit too messy at the time
319 # this changeset was introduced. Someone should fix
316 # this changeset was introduced. Someone should fix
320 # the remainig bit and drop this line
317 # the remainig bit and drop this line
321 'bisect.state',
318 'bisect.state',
322 }
319 }
323
320
324 def __init__(self, baseui, path, create=False):
321 def __init__(self, baseui, path, create=False):
325 self.requirements = set()
322 self.requirements = set()
326 self.filtername = None
323 self.filtername = None
327 # wvfs: rooted at the repository root, used to access the working copy
324 # wvfs: rooted at the repository root, used to access the working copy
328 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
325 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
329 # vfs: rooted at .hg, used to access repo files outside of .hg/store
326 # vfs: rooted at .hg, used to access repo files outside of .hg/store
330 self.vfs = None
327 self.vfs = None
331 # svfs: usually rooted at .hg/store, used to access repository history
328 # svfs: usually rooted at .hg/store, used to access repository history
332 # If this is a shared repository, this vfs may point to another
329 # If this is a shared repository, this vfs may point to another
333 # repository's .hg/store directory.
330 # repository's .hg/store directory.
334 self.svfs = None
331 self.svfs = None
335 self.root = self.wvfs.base
332 self.root = self.wvfs.base
336 self.path = self.wvfs.join(".hg")
333 self.path = self.wvfs.join(".hg")
337 self.origroot = path
334 self.origroot = path
338 # These auditor are not used by the vfs,
335 # These auditor are not used by the vfs,
339 # only used when writing this comment: basectx.match
336 # only used when writing this comment: basectx.match
340 self.auditor = pathutil.pathauditor(self.root, self._checknested)
337 self.auditor = pathutil.pathauditor(self.root, self._checknested)
341 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
338 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
342 realfs=False)
339 realfs=False)
343 self.baseui = baseui
340 self.baseui = baseui
344 self.ui = baseui.copy()
341 self.ui = baseui.copy()
345 self.ui.copy = baseui.copy # prevent copying repo configuration
342 self.ui.copy = baseui.copy # prevent copying repo configuration
346 self.vfs = vfsmod.vfs(self.path)
343 self.vfs = vfsmod.vfs(self.path)
347 if (self.ui.configbool('devel', 'all-warnings') or
344 if (self.ui.configbool('devel', 'all-warnings') or
348 self.ui.configbool('devel', 'check-locks')):
345 self.ui.configbool('devel', 'check-locks')):
349 self.vfs.audit = self._getvfsward(self.vfs.audit)
346 self.vfs.audit = self._getvfsward(self.vfs.audit)
350 # A list of callback to shape the phase if no data were found.
347 # A list of callback to shape the phase if no data were found.
351 # Callback are in the form: func(repo, roots) --> processed root.
348 # Callback are in the form: func(repo, roots) --> processed root.
352 # This list it to be filled by extension during repo setup
349 # This list it to be filled by extension during repo setup
353 self._phasedefaults = []
350 self._phasedefaults = []
354 try:
351 try:
355 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
352 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
356 self._loadextensions()
353 self._loadextensions()
357 except IOError:
354 except IOError:
358 pass
355 pass
359
356
360 if self.featuresetupfuncs:
357 if self.featuresetupfuncs:
361 self.supported = set(self._basesupported) # use private copy
358 self.supported = set(self._basesupported) # use private copy
362 extmods = set(m.__name__ for n, m
359 extmods = set(m.__name__ for n, m
363 in extensions.extensions(self.ui))
360 in extensions.extensions(self.ui))
364 for setupfunc in self.featuresetupfuncs:
361 for setupfunc in self.featuresetupfuncs:
365 if setupfunc.__module__ in extmods:
362 if setupfunc.__module__ in extmods:
366 setupfunc(self.ui, self.supported)
363 setupfunc(self.ui, self.supported)
367 else:
364 else:
368 self.supported = self._basesupported
365 self.supported = self._basesupported
369 color.setup(self.ui)
366 color.setup(self.ui)
370
367
371 # Add compression engines.
368 # Add compression engines.
372 for name in util.compengines:
369 for name in util.compengines:
373 engine = util.compengines[name]
370 engine = util.compengines[name]
374 if engine.revlogheader():
371 if engine.revlogheader():
375 self.supported.add('exp-compression-%s' % name)
372 self.supported.add('exp-compression-%s' % name)
376
373
377 if not self.vfs.isdir():
374 if not self.vfs.isdir():
378 if create:
375 if create:
379 self.requirements = newreporequirements(self)
376 self.requirements = newreporequirements(self)
380
377
381 if not self.wvfs.exists():
378 if not self.wvfs.exists():
382 self.wvfs.makedirs()
379 self.wvfs.makedirs()
383 self.vfs.makedir(notindexed=True)
380 self.vfs.makedir(notindexed=True)
384
381
385 if 'store' in self.requirements:
382 if 'store' in self.requirements:
386 self.vfs.mkdir("store")
383 self.vfs.mkdir("store")
387
384
388 # create an invalid changelog
385 # create an invalid changelog
389 self.vfs.append(
386 self.vfs.append(
390 "00changelog.i",
387 "00changelog.i",
391 '\0\0\0\2' # represents revlogv2
388 '\0\0\0\2' # represents revlogv2
392 ' dummy changelog to prevent using the old repo layout'
389 ' dummy changelog to prevent using the old repo layout'
393 )
390 )
394 else:
391 else:
395 raise error.RepoError(_("repository %s not found") % path)
392 raise error.RepoError(_("repository %s not found") % path)
396 elif create:
393 elif create:
397 raise error.RepoError(_("repository %s already exists") % path)
394 raise error.RepoError(_("repository %s already exists") % path)
398 else:
395 else:
399 try:
396 try:
400 self.requirements = scmutil.readrequires(
397 self.requirements = scmutil.readrequires(
401 self.vfs, self.supported)
398 self.vfs, self.supported)
402 except IOError as inst:
399 except IOError as inst:
403 if inst.errno != errno.ENOENT:
400 if inst.errno != errno.ENOENT:
404 raise
401 raise
405
402
406 cachepath = self.vfs.join('cache')
403 cachepath = self.vfs.join('cache')
407 self.sharedpath = self.path
404 self.sharedpath = self.path
408 try:
405 try:
409 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
406 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
410 if 'relshared' in self.requirements:
407 if 'relshared' in self.requirements:
411 sharedpath = self.vfs.join(sharedpath)
408 sharedpath = self.vfs.join(sharedpath)
412 vfs = vfsmod.vfs(sharedpath, realpath=True)
409 vfs = vfsmod.vfs(sharedpath, realpath=True)
413 cachepath = vfs.join('cache')
410 cachepath = vfs.join('cache')
414 s = vfs.base
411 s = vfs.base
415 if not vfs.exists():
412 if not vfs.exists():
416 raise error.RepoError(
413 raise error.RepoError(
417 _('.hg/sharedpath points to nonexistent directory %s') % s)
414 _('.hg/sharedpath points to nonexistent directory %s') % s)
418 self.sharedpath = s
415 self.sharedpath = s
419 except IOError as inst:
416 except IOError as inst:
420 if inst.errno != errno.ENOENT:
417 if inst.errno != errno.ENOENT:
421 raise
418 raise
422
419
423 if 'exp-sparse' in self.requirements and not sparse.enabled:
420 if 'exp-sparse' in self.requirements and not sparse.enabled:
424 raise error.RepoError(_('repository is using sparse feature but '
421 raise error.RepoError(_('repository is using sparse feature but '
425 'sparse is not enabled; enable the '
422 'sparse is not enabled; enable the '
426 '"sparse" extensions to access'))
423 '"sparse" extensions to access'))
427
424
428 self.store = store.store(
425 self.store = store.store(
429 self.requirements, self.sharedpath, vfsmod.vfs)
426 self.requirements, self.sharedpath, vfsmod.vfs)
430 self.spath = self.store.path
427 self.spath = self.store.path
431 self.svfs = self.store.vfs
428 self.svfs = self.store.vfs
432 self.sjoin = self.store.join
429 self.sjoin = self.store.join
433 self.vfs.createmode = self.store.createmode
430 self.vfs.createmode = self.store.createmode
434 self.cachevfs = vfsmod.vfs(cachepath)
431 self.cachevfs = vfsmod.vfs(cachepath)
435 self.cachevfs.createmode = self.store.createmode
432 self.cachevfs.createmode = self.store.createmode
436 if (self.ui.configbool('devel', 'all-warnings') or
433 if (self.ui.configbool('devel', 'all-warnings') or
437 self.ui.configbool('devel', 'check-locks')):
434 self.ui.configbool('devel', 'check-locks')):
438 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
435 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
439 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
436 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
440 else: # standard vfs
437 else: # standard vfs
441 self.svfs.audit = self._getsvfsward(self.svfs.audit)
438 self.svfs.audit = self._getsvfsward(self.svfs.audit)
442 self._applyopenerreqs()
439 self._applyopenerreqs()
443 if create:
440 if create:
444 self._writerequirements()
441 self._writerequirements()
445
442
446 self._dirstatevalidatewarned = False
443 self._dirstatevalidatewarned = False
447
444
448 self._branchcaches = {}
445 self._branchcaches = {}
449 self._revbranchcache = None
446 self._revbranchcache = None
450 self.filterpats = {}
447 self.filterpats = {}
451 self._datafilters = {}
448 self._datafilters = {}
452 self._transref = self._lockref = self._wlockref = None
449 self._transref = self._lockref = self._wlockref = None
453
450
454 # A cache for various files under .hg/ that tracks file changes,
451 # A cache for various files under .hg/ that tracks file changes,
455 # (used by the filecache decorator)
452 # (used by the filecache decorator)
456 #
453 #
457 # Maps a property name to its util.filecacheentry
454 # Maps a property name to its util.filecacheentry
458 self._filecache = {}
455 self._filecache = {}
459
456
460 # hold sets of revision to be filtered
457 # hold sets of revision to be filtered
461 # should be cleared when something might have changed the filter value:
458 # should be cleared when something might have changed the filter value:
462 # - new changesets,
459 # - new changesets,
463 # - phase change,
460 # - phase change,
464 # - new obsolescence marker,
461 # - new obsolescence marker,
465 # - working directory parent change,
462 # - working directory parent change,
466 # - bookmark changes
463 # - bookmark changes
467 self.filteredrevcache = {}
464 self.filteredrevcache = {}
468
465
469 # post-dirstate-status hooks
466 # post-dirstate-status hooks
470 self._postdsstatus = []
467 self._postdsstatus = []
471
468
472 # Cache of types representing filtered repos.
469 # Cache of types representing filtered repos.
473 self._filteredrepotypes = weakref.WeakKeyDictionary()
470 self._filteredrepotypes = weakref.WeakKeyDictionary()
474
471
475 # generic mapping between names and nodes
472 # generic mapping between names and nodes
476 self.names = namespaces.namespaces()
473 self.names = namespaces.namespaces()
477
474
478 # Key to signature value.
475 # Key to signature value.
479 self._sparsesignaturecache = {}
476 self._sparsesignaturecache = {}
480 # Signature to cached matcher instance.
477 # Signature to cached matcher instance.
481 self._sparsematchercache = {}
478 self._sparsematchercache = {}
482
479
483 def _getvfsward(self, origfunc):
480 def _getvfsward(self, origfunc):
484 """build a ward for self.vfs"""
481 """build a ward for self.vfs"""
485 rref = weakref.ref(self)
482 rref = weakref.ref(self)
486 def checkvfs(path, mode=None):
483 def checkvfs(path, mode=None):
487 ret = origfunc(path, mode=mode)
484 ret = origfunc(path, mode=mode)
488 repo = rref()
485 repo = rref()
489 if (repo is None
486 if (repo is None
490 or not util.safehasattr(repo, '_wlockref')
487 or not util.safehasattr(repo, '_wlockref')
491 or not util.safehasattr(repo, '_lockref')):
488 or not util.safehasattr(repo, '_lockref')):
492 return
489 return
493 if mode in (None, 'r', 'rb'):
490 if mode in (None, 'r', 'rb'):
494 return
491 return
495 if path.startswith(repo.path):
492 if path.startswith(repo.path):
496 # truncate name relative to the repository (.hg)
493 # truncate name relative to the repository (.hg)
497 path = path[len(repo.path) + 1:]
494 path = path[len(repo.path) + 1:]
498 if path.startswith('cache/'):
495 if path.startswith('cache/'):
499 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
496 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
500 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
497 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
501 if path.startswith('journal.'):
498 if path.startswith('journal.'):
502 # journal is covered by 'lock'
499 # journal is covered by 'lock'
503 if repo._currentlock(repo._lockref) is None:
500 if repo._currentlock(repo._lockref) is None:
504 repo.ui.develwarn('write with no lock: "%s"' % path,
501 repo.ui.develwarn('write with no lock: "%s"' % path,
505 stacklevel=2, config='check-locks')
502 stacklevel=2, config='check-locks')
506 elif repo._currentlock(repo._wlockref) is None:
503 elif repo._currentlock(repo._wlockref) is None:
507 # rest of vfs files are covered by 'wlock'
504 # rest of vfs files are covered by 'wlock'
508 #
505 #
509 # exclude special files
506 # exclude special files
510 for prefix in self._wlockfreeprefix:
507 for prefix in self._wlockfreeprefix:
511 if path.startswith(prefix):
508 if path.startswith(prefix):
512 return
509 return
513 repo.ui.develwarn('write with no wlock: "%s"' % path,
510 repo.ui.develwarn('write with no wlock: "%s"' % path,
514 stacklevel=2, config='check-locks')
511 stacklevel=2, config='check-locks')
515 return ret
512 return ret
516 return checkvfs
513 return checkvfs
517
514
518 def _getsvfsward(self, origfunc):
515 def _getsvfsward(self, origfunc):
519 """build a ward for self.svfs"""
516 """build a ward for self.svfs"""
520 rref = weakref.ref(self)
517 rref = weakref.ref(self)
521 def checksvfs(path, mode=None):
518 def checksvfs(path, mode=None):
522 ret = origfunc(path, mode=mode)
519 ret = origfunc(path, mode=mode)
523 repo = rref()
520 repo = rref()
524 if repo is None or not util.safehasattr(repo, '_lockref'):
521 if repo is None or not util.safehasattr(repo, '_lockref'):
525 return
522 return
526 if mode in (None, 'r', 'rb'):
523 if mode in (None, 'r', 'rb'):
527 return
524 return
528 if path.startswith(repo.sharedpath):
525 if path.startswith(repo.sharedpath):
529 # truncate name relative to the repository (.hg)
526 # truncate name relative to the repository (.hg)
530 path = path[len(repo.sharedpath) + 1:]
527 path = path[len(repo.sharedpath) + 1:]
531 if repo._currentlock(repo._lockref) is None:
528 if repo._currentlock(repo._lockref) is None:
532 repo.ui.develwarn('write with no lock: "%s"' % path,
529 repo.ui.develwarn('write with no lock: "%s"' % path,
533 stacklevel=3)
530 stacklevel=3)
534 return ret
531 return ret
535 return checksvfs
532 return checksvfs
536
533
537 def close(self):
534 def close(self):
538 self._writecaches()
535 self._writecaches()
539
536
540 def _loadextensions(self):
537 def _loadextensions(self):
541 extensions.loadall(self.ui)
538 extensions.loadall(self.ui)
542
539
543 def _writecaches(self):
540 def _writecaches(self):
544 if self._revbranchcache:
541 if self._revbranchcache:
545 self._revbranchcache.write()
542 self._revbranchcache.write()
546
543
547 def _restrictcapabilities(self, caps):
544 def _restrictcapabilities(self, caps):
548 if self.ui.configbool('experimental', 'bundle2-advertise'):
545 if self.ui.configbool('experimental', 'bundle2-advertise'):
549 caps = set(caps)
546 caps = set(caps)
550 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
547 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
551 caps.add('bundle2=' + urlreq.quote(capsblob))
548 caps.add('bundle2=' + urlreq.quote(capsblob))
552 return caps
549 return caps
553
550
554 def _applyopenerreqs(self):
551 def _applyopenerreqs(self):
555 self.svfs.options = dict((r, 1) for r in self.requirements
552 self.svfs.options = dict((r, 1) for r in self.requirements
556 if r in self.openerreqs)
553 if r in self.openerreqs)
557 # experimental config: format.chunkcachesize
554 # experimental config: format.chunkcachesize
558 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
555 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
559 if chunkcachesize is not None:
556 if chunkcachesize is not None:
560 self.svfs.options['chunkcachesize'] = chunkcachesize
557 self.svfs.options['chunkcachesize'] = chunkcachesize
561 # experimental config: format.maxchainlen
558 # experimental config: format.maxchainlen
562 maxchainlen = self.ui.configint('format', 'maxchainlen')
559 maxchainlen = self.ui.configint('format', 'maxchainlen')
563 if maxchainlen is not None:
560 if maxchainlen is not None:
564 self.svfs.options['maxchainlen'] = maxchainlen
561 self.svfs.options['maxchainlen'] = maxchainlen
565 # experimental config: format.manifestcachesize
562 # experimental config: format.manifestcachesize
566 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
563 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
567 if manifestcachesize is not None:
564 if manifestcachesize is not None:
568 self.svfs.options['manifestcachesize'] = manifestcachesize
565 self.svfs.options['manifestcachesize'] = manifestcachesize
569 # experimental config: format.aggressivemergedeltas
566 # experimental config: format.aggressivemergedeltas
570 aggressivemergedeltas = self.ui.configbool('format',
567 aggressivemergedeltas = self.ui.configbool('format',
571 'aggressivemergedeltas')
568 'aggressivemergedeltas')
572 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
569 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
573 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
570 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
574 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
571 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
575 if 0 <= chainspan:
572 if 0 <= chainspan:
576 self.svfs.options['maxdeltachainspan'] = chainspan
573 self.svfs.options['maxdeltachainspan'] = chainspan
577
574
578 for r in self.requirements:
575 for r in self.requirements:
579 if r.startswith('exp-compression-'):
576 if r.startswith('exp-compression-'):
580 self.svfs.options['compengine'] = r[len('exp-compression-'):]
577 self.svfs.options['compengine'] = r[len('exp-compression-'):]
581
578
582 # TODO move "revlogv2" to openerreqs once finalized.
579 # TODO move "revlogv2" to openerreqs once finalized.
583 if REVLOGV2_REQUIREMENT in self.requirements:
580 if REVLOGV2_REQUIREMENT in self.requirements:
584 self.svfs.options['revlogv2'] = True
581 self.svfs.options['revlogv2'] = True
585
582
586 def _writerequirements(self):
583 def _writerequirements(self):
587 scmutil.writerequires(self.vfs, self.requirements)
584 scmutil.writerequires(self.vfs, self.requirements)
588
585
589 def _checknested(self, path):
586 def _checknested(self, path):
590 """Determine if path is a legal nested repository."""
587 """Determine if path is a legal nested repository."""
591 if not path.startswith(self.root):
588 if not path.startswith(self.root):
592 return False
589 return False
593 subpath = path[len(self.root) + 1:]
590 subpath = path[len(self.root) + 1:]
594 normsubpath = util.pconvert(subpath)
591 normsubpath = util.pconvert(subpath)
595
592
596 # XXX: Checking against the current working copy is wrong in
593 # XXX: Checking against the current working copy is wrong in
597 # the sense that it can reject things like
594 # the sense that it can reject things like
598 #
595 #
599 # $ hg cat -r 10 sub/x.txt
596 # $ hg cat -r 10 sub/x.txt
600 #
597 #
601 # if sub/ is no longer a subrepository in the working copy
598 # if sub/ is no longer a subrepository in the working copy
602 # parent revision.
599 # parent revision.
603 #
600 #
604 # However, it can of course also allow things that would have
601 # However, it can of course also allow things that would have
605 # been rejected before, such as the above cat command if sub/
602 # been rejected before, such as the above cat command if sub/
606 # is a subrepository now, but was a normal directory before.
603 # is a subrepository now, but was a normal directory before.
607 # The old path auditor would have rejected by mistake since it
604 # The old path auditor would have rejected by mistake since it
608 # panics when it sees sub/.hg/.
605 # panics when it sees sub/.hg/.
609 #
606 #
610 # All in all, checking against the working copy seems sensible
607 # All in all, checking against the working copy seems sensible
611 # since we want to prevent access to nested repositories on
608 # since we want to prevent access to nested repositories on
612 # the filesystem *now*.
609 # the filesystem *now*.
613 ctx = self[None]
610 ctx = self[None]
614 parts = util.splitpath(subpath)
611 parts = util.splitpath(subpath)
615 while parts:
612 while parts:
616 prefix = '/'.join(parts)
613 prefix = '/'.join(parts)
617 if prefix in ctx.substate:
614 if prefix in ctx.substate:
618 if prefix == normsubpath:
615 if prefix == normsubpath:
619 return True
616 return True
620 else:
617 else:
621 sub = ctx.sub(prefix)
618 sub = ctx.sub(prefix)
622 return sub.checknested(subpath[len(prefix) + 1:])
619 return sub.checknested(subpath[len(prefix) + 1:])
623 else:
620 else:
624 parts.pop()
621 parts.pop()
625 return False
622 return False
626
623
627 def peer(self):
624 def peer(self):
628 return localpeer(self) # not cached to avoid reference cycle
625 return localpeer(self) # not cached to avoid reference cycle
629
626
630 def unfiltered(self):
627 def unfiltered(self):
631 """Return unfiltered version of the repository
628 """Return unfiltered version of the repository
632
629
633 Intended to be overwritten by filtered repo."""
630 Intended to be overwritten by filtered repo."""
634 return self
631 return self
635
632
636 def filtered(self, name):
633 def filtered(self, name):
637 """Return a filtered version of a repository"""
634 """Return a filtered version of a repository"""
638 # Python <3.4 easily leaks types via __mro__. See
635 # Python <3.4 easily leaks types via __mro__. See
639 # https://bugs.python.org/issue17950. We cache dynamically
636 # https://bugs.python.org/issue17950. We cache dynamically
640 # created types so this method doesn't leak on every
637 # created types so this method doesn't leak on every
641 # invocation.
638 # invocation.
642
639
643 key = self.unfiltered().__class__
640 key = self.unfiltered().__class__
644 if key not in self._filteredrepotypes:
641 if key not in self._filteredrepotypes:
645 # Build a new type with the repoview mixin and the base
642 # Build a new type with the repoview mixin and the base
646 # class of this repo. Give it a name containing the
643 # class of this repo. Give it a name containing the
647 # filter name to aid debugging.
644 # filter name to aid debugging.
648 bases = (repoview.repoview, key)
645 bases = (repoview.repoview, key)
649 cls = type(r'%sfilteredrepo' % name, bases, {})
646 cls = type(r'%sfilteredrepo' % name, bases, {})
650 self._filteredrepotypes[key] = cls
647 self._filteredrepotypes[key] = cls
651
648
652 return self._filteredrepotypes[key](self, name)
649 return self._filteredrepotypes[key](self, name)
653
650
654 @repofilecache('bookmarks', 'bookmarks.current')
651 @repofilecache('bookmarks', 'bookmarks.current')
655 def _bookmarks(self):
652 def _bookmarks(self):
656 return bookmarks.bmstore(self)
653 return bookmarks.bmstore(self)
657
654
658 @property
655 @property
659 def _activebookmark(self):
656 def _activebookmark(self):
660 return self._bookmarks.active
657 return self._bookmarks.active
661
658
662 # _phaserevs and _phasesets depend on changelog. what we need is to
659 # _phaserevs and _phasesets depend on changelog. what we need is to
663 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
660 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
664 # can't be easily expressed in filecache mechanism.
661 # can't be easily expressed in filecache mechanism.
665 @storecache('phaseroots', '00changelog.i')
662 @storecache('phaseroots', '00changelog.i')
666 def _phasecache(self):
663 def _phasecache(self):
667 return phases.phasecache(self, self._phasedefaults)
664 return phases.phasecache(self, self._phasedefaults)
668
665
669 @storecache('obsstore')
666 @storecache('obsstore')
670 def obsstore(self):
667 def obsstore(self):
671 return obsolete.makestore(self.ui, self)
668 return obsolete.makestore(self.ui, self)
672
669
673 @storecache('00changelog.i')
670 @storecache('00changelog.i')
674 def changelog(self):
671 def changelog(self):
675 return changelog.changelog(self.svfs,
672 return changelog.changelog(self.svfs,
676 trypending=txnutil.mayhavepending(self.root))
673 trypending=txnutil.mayhavepending(self.root))
677
674
678 def _constructmanifest(self):
675 def _constructmanifest(self):
679 # This is a temporary function while we migrate from manifest to
676 # This is a temporary function while we migrate from manifest to
680 # manifestlog. It allows bundlerepo and unionrepo to intercept the
677 # manifestlog. It allows bundlerepo and unionrepo to intercept the
681 # manifest creation.
678 # manifest creation.
682 return manifest.manifestrevlog(self.svfs)
679 return manifest.manifestrevlog(self.svfs)
683
680
684 @storecache('00manifest.i')
681 @storecache('00manifest.i')
685 def manifestlog(self):
682 def manifestlog(self):
686 return manifest.manifestlog(self.svfs, self)
683 return manifest.manifestlog(self.svfs, self)
687
684
688 @repofilecache('dirstate')
685 @repofilecache('dirstate')
689 def dirstate(self):
686 def dirstate(self):
690 sparsematchfn = lambda: sparse.matcher(self)
687 sparsematchfn = lambda: sparse.matcher(self)
691
688
692 return dirstate.dirstate(self.vfs, self.ui, self.root,
689 return dirstate.dirstate(self.vfs, self.ui, self.root,
693 self._dirstatevalidate, sparsematchfn)
690 self._dirstatevalidate, sparsematchfn)
694
691
695 def _dirstatevalidate(self, node):
692 def _dirstatevalidate(self, node):
696 try:
693 try:
697 self.changelog.rev(node)
694 self.changelog.rev(node)
698 return node
695 return node
699 except error.LookupError:
696 except error.LookupError:
700 if not self._dirstatevalidatewarned:
697 if not self._dirstatevalidatewarned:
701 self._dirstatevalidatewarned = True
698 self._dirstatevalidatewarned = True
702 self.ui.warn(_("warning: ignoring unknown"
699 self.ui.warn(_("warning: ignoring unknown"
703 " working parent %s!\n") % short(node))
700 " working parent %s!\n") % short(node))
704 return nullid
701 return nullid
705
702
706 def __getitem__(self, changeid):
703 def __getitem__(self, changeid):
707 if changeid is None:
704 if changeid is None:
708 return context.workingctx(self)
705 return context.workingctx(self)
709 if isinstance(changeid, slice):
706 if isinstance(changeid, slice):
710 # wdirrev isn't contiguous so the slice shouldn't include it
707 # wdirrev isn't contiguous so the slice shouldn't include it
711 return [context.changectx(self, i)
708 return [context.changectx(self, i)
712 for i in xrange(*changeid.indices(len(self)))
709 for i in xrange(*changeid.indices(len(self)))
713 if i not in self.changelog.filteredrevs]
710 if i not in self.changelog.filteredrevs]
714 try:
711 try:
715 return context.changectx(self, changeid)
712 return context.changectx(self, changeid)
716 except error.WdirUnsupported:
713 except error.WdirUnsupported:
717 return context.workingctx(self)
714 return context.workingctx(self)
718
715
719 def __contains__(self, changeid):
716 def __contains__(self, changeid):
720 """True if the given changeid exists
717 """True if the given changeid exists
721
718
722 error.LookupError is raised if an ambiguous node specified.
719 error.LookupError is raised if an ambiguous node specified.
723 """
720 """
724 try:
721 try:
725 self[changeid]
722 self[changeid]
726 return True
723 return True
727 except error.RepoLookupError:
724 except error.RepoLookupError:
728 return False
725 return False
729
726
730 def __nonzero__(self):
727 def __nonzero__(self):
731 return True
728 return True
732
729
733 __bool__ = __nonzero__
730 __bool__ = __nonzero__
734
731
735 def __len__(self):
732 def __len__(self):
736 return len(self.changelog)
733 return len(self.changelog)
737
734
738 def __iter__(self):
735 def __iter__(self):
739 return iter(self.changelog)
736 return iter(self.changelog)
740
737
741 def revs(self, expr, *args):
738 def revs(self, expr, *args):
742 '''Find revisions matching a revset.
739 '''Find revisions matching a revset.
743
740
744 The revset is specified as a string ``expr`` that may contain
741 The revset is specified as a string ``expr`` that may contain
745 %-formatting to escape certain types. See ``revsetlang.formatspec``.
742 %-formatting to escape certain types. See ``revsetlang.formatspec``.
746
743
747 Revset aliases from the configuration are not expanded. To expand
744 Revset aliases from the configuration are not expanded. To expand
748 user aliases, consider calling ``scmutil.revrange()`` or
745 user aliases, consider calling ``scmutil.revrange()`` or
749 ``repo.anyrevs([expr], user=True)``.
746 ``repo.anyrevs([expr], user=True)``.
750
747
751 Returns a revset.abstractsmartset, which is a list-like interface
748 Returns a revset.abstractsmartset, which is a list-like interface
752 that contains integer revisions.
749 that contains integer revisions.
753 '''
750 '''
754 expr = revsetlang.formatspec(expr, *args)
751 expr = revsetlang.formatspec(expr, *args)
755 m = revset.match(None, expr)
752 m = revset.match(None, expr)
756 return m(self)
753 return m(self)
757
754
758 def set(self, expr, *args):
755 def set(self, expr, *args):
759 '''Find revisions matching a revset and emit changectx instances.
756 '''Find revisions matching a revset and emit changectx instances.
760
757
761 This is a convenience wrapper around ``revs()`` that iterates the
758 This is a convenience wrapper around ``revs()`` that iterates the
762 result and is a generator of changectx instances.
759 result and is a generator of changectx instances.
763
760
764 Revset aliases from the configuration are not expanded. To expand
761 Revset aliases from the configuration are not expanded. To expand
765 user aliases, consider calling ``scmutil.revrange()``.
762 user aliases, consider calling ``scmutil.revrange()``.
766 '''
763 '''
767 for r in self.revs(expr, *args):
764 for r in self.revs(expr, *args):
768 yield self[r]
765 yield self[r]
769
766
770 def anyrevs(self, specs, user=False, localalias=None):
767 def anyrevs(self, specs, user=False, localalias=None):
771 '''Find revisions matching one of the given revsets.
768 '''Find revisions matching one of the given revsets.
772
769
773 Revset aliases from the configuration are not expanded by default. To
770 Revset aliases from the configuration are not expanded by default. To
774 expand user aliases, specify ``user=True``. To provide some local
771 expand user aliases, specify ``user=True``. To provide some local
775 definitions overriding user aliases, set ``localalias`` to
772 definitions overriding user aliases, set ``localalias`` to
776 ``{name: definitionstring}``.
773 ``{name: definitionstring}``.
777 '''
774 '''
778 if user:
775 if user:
779 m = revset.matchany(self.ui, specs, repo=self,
776 m = revset.matchany(self.ui, specs, repo=self,
780 localalias=localalias)
777 localalias=localalias)
781 else:
778 else:
782 m = revset.matchany(None, specs, localalias=localalias)
779 m = revset.matchany(None, specs, localalias=localalias)
783 return m(self)
780 return m(self)
784
781
785 def url(self):
782 def url(self):
786 return 'file:' + self.root
783 return 'file:' + self.root
787
784
788 def hook(self, name, throw=False, **args):
785 def hook(self, name, throw=False, **args):
789 """Call a hook, passing this repo instance.
786 """Call a hook, passing this repo instance.
790
787
791 This a convenience method to aid invoking hooks. Extensions likely
788 This a convenience method to aid invoking hooks. Extensions likely
792 won't call this unless they have registered a custom hook or are
789 won't call this unless they have registered a custom hook or are
793 replacing code that is expected to call a hook.
790 replacing code that is expected to call a hook.
794 """
791 """
795 return hook.hook(self.ui, self, name, throw, **args)
792 return hook.hook(self.ui, self, name, throw, **args)
796
793
797 @filteredpropertycache
794 @filteredpropertycache
798 def _tagscache(self):
795 def _tagscache(self):
799 '''Returns a tagscache object that contains various tags related
796 '''Returns a tagscache object that contains various tags related
800 caches.'''
797 caches.'''
801
798
802 # This simplifies its cache management by having one decorated
799 # This simplifies its cache management by having one decorated
803 # function (this one) and the rest simply fetch things from it.
800 # function (this one) and the rest simply fetch things from it.
804 class tagscache(object):
801 class tagscache(object):
805 def __init__(self):
802 def __init__(self):
806 # These two define the set of tags for this repository. tags
803 # These two define the set of tags for this repository. tags
807 # maps tag name to node; tagtypes maps tag name to 'global' or
804 # maps tag name to node; tagtypes maps tag name to 'global' or
808 # 'local'. (Global tags are defined by .hgtags across all
805 # 'local'. (Global tags are defined by .hgtags across all
809 # heads, and local tags are defined in .hg/localtags.)
806 # heads, and local tags are defined in .hg/localtags.)
810 # They constitute the in-memory cache of tags.
807 # They constitute the in-memory cache of tags.
811 self.tags = self.tagtypes = None
808 self.tags = self.tagtypes = None
812
809
813 self.nodetagscache = self.tagslist = None
810 self.nodetagscache = self.tagslist = None
814
811
815 cache = tagscache()
812 cache = tagscache()
816 cache.tags, cache.tagtypes = self._findtags()
813 cache.tags, cache.tagtypes = self._findtags()
817
814
818 return cache
815 return cache
819
816
820 def tags(self):
817 def tags(self):
821 '''return a mapping of tag to node'''
818 '''return a mapping of tag to node'''
822 t = {}
819 t = {}
823 if self.changelog.filteredrevs:
820 if self.changelog.filteredrevs:
824 tags, tt = self._findtags()
821 tags, tt = self._findtags()
825 else:
822 else:
826 tags = self._tagscache.tags
823 tags = self._tagscache.tags
827 for k, v in tags.iteritems():
824 for k, v in tags.iteritems():
828 try:
825 try:
829 # ignore tags to unknown nodes
826 # ignore tags to unknown nodes
830 self.changelog.rev(v)
827 self.changelog.rev(v)
831 t[k] = v
828 t[k] = v
832 except (error.LookupError, ValueError):
829 except (error.LookupError, ValueError):
833 pass
830 pass
834 return t
831 return t
835
832
836 def _findtags(self):
833 def _findtags(self):
837 '''Do the hard work of finding tags. Return a pair of dicts
834 '''Do the hard work of finding tags. Return a pair of dicts
838 (tags, tagtypes) where tags maps tag name to node, and tagtypes
835 (tags, tagtypes) where tags maps tag name to node, and tagtypes
839 maps tag name to a string like \'global\' or \'local\'.
836 maps tag name to a string like \'global\' or \'local\'.
840 Subclasses or extensions are free to add their own tags, but
837 Subclasses or extensions are free to add their own tags, but
841 should be aware that the returned dicts will be retained for the
838 should be aware that the returned dicts will be retained for the
842 duration of the localrepo object.'''
839 duration of the localrepo object.'''
843
840
844 # XXX what tagtype should subclasses/extensions use? Currently
841 # XXX what tagtype should subclasses/extensions use? Currently
845 # mq and bookmarks add tags, but do not set the tagtype at all.
842 # mq and bookmarks add tags, but do not set the tagtype at all.
846 # Should each extension invent its own tag type? Should there
843 # Should each extension invent its own tag type? Should there
847 # be one tagtype for all such "virtual" tags? Or is the status
844 # be one tagtype for all such "virtual" tags? Or is the status
848 # quo fine?
845 # quo fine?
849
846
850
847
851 # map tag name to (node, hist)
848 # map tag name to (node, hist)
852 alltags = tagsmod.findglobaltags(self.ui, self)
849 alltags = tagsmod.findglobaltags(self.ui, self)
853 # map tag name to tag type
850 # map tag name to tag type
854 tagtypes = dict((tag, 'global') for tag in alltags)
851 tagtypes = dict((tag, 'global') for tag in alltags)
855
852
856 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
853 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
857
854
858 # Build the return dicts. Have to re-encode tag names because
855 # Build the return dicts. Have to re-encode tag names because
859 # the tags module always uses UTF-8 (in order not to lose info
856 # the tags module always uses UTF-8 (in order not to lose info
860 # writing to the cache), but the rest of Mercurial wants them in
857 # writing to the cache), but the rest of Mercurial wants them in
861 # local encoding.
858 # local encoding.
862 tags = {}
859 tags = {}
863 for (name, (node, hist)) in alltags.iteritems():
860 for (name, (node, hist)) in alltags.iteritems():
864 if node != nullid:
861 if node != nullid:
865 tags[encoding.tolocal(name)] = node
862 tags[encoding.tolocal(name)] = node
866 tags['tip'] = self.changelog.tip()
863 tags['tip'] = self.changelog.tip()
867 tagtypes = dict([(encoding.tolocal(name), value)
864 tagtypes = dict([(encoding.tolocal(name), value)
868 for (name, value) in tagtypes.iteritems()])
865 for (name, value) in tagtypes.iteritems()])
869 return (tags, tagtypes)
866 return (tags, tagtypes)
870
867
871 def tagtype(self, tagname):
868 def tagtype(self, tagname):
872 '''
869 '''
873 return the type of the given tag. result can be:
870 return the type of the given tag. result can be:
874
871
875 'local' : a local tag
872 'local' : a local tag
876 'global' : a global tag
873 'global' : a global tag
877 None : tag does not exist
874 None : tag does not exist
878 '''
875 '''
879
876
880 return self._tagscache.tagtypes.get(tagname)
877 return self._tagscache.tagtypes.get(tagname)
881
878
882 def tagslist(self):
879 def tagslist(self):
883 '''return a list of tags ordered by revision'''
880 '''return a list of tags ordered by revision'''
884 if not self._tagscache.tagslist:
881 if not self._tagscache.tagslist:
885 l = []
882 l = []
886 for t, n in self.tags().iteritems():
883 for t, n in self.tags().iteritems():
887 l.append((self.changelog.rev(n), t, n))
884 l.append((self.changelog.rev(n), t, n))
888 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
885 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
889
886
890 return self._tagscache.tagslist
887 return self._tagscache.tagslist
891
888
892 def nodetags(self, node):
889 def nodetags(self, node):
893 '''return the tags associated with a node'''
890 '''return the tags associated with a node'''
894 if not self._tagscache.nodetagscache:
891 if not self._tagscache.nodetagscache:
895 nodetagscache = {}
892 nodetagscache = {}
896 for t, n in self._tagscache.tags.iteritems():
893 for t, n in self._tagscache.tags.iteritems():
897 nodetagscache.setdefault(n, []).append(t)
894 nodetagscache.setdefault(n, []).append(t)
898 for tags in nodetagscache.itervalues():
895 for tags in nodetagscache.itervalues():
899 tags.sort()
896 tags.sort()
900 self._tagscache.nodetagscache = nodetagscache
897 self._tagscache.nodetagscache = nodetagscache
901 return self._tagscache.nodetagscache.get(node, [])
898 return self._tagscache.nodetagscache.get(node, [])
902
899
903 def nodebookmarks(self, node):
900 def nodebookmarks(self, node):
904 """return the list of bookmarks pointing to the specified node"""
901 """return the list of bookmarks pointing to the specified node"""
905 marks = []
902 marks = []
906 for bookmark, n in self._bookmarks.iteritems():
903 for bookmark, n in self._bookmarks.iteritems():
907 if n == node:
904 if n == node:
908 marks.append(bookmark)
905 marks.append(bookmark)
909 return sorted(marks)
906 return sorted(marks)
910
907
911 def branchmap(self):
908 def branchmap(self):
912 '''returns a dictionary {branch: [branchheads]} with branchheads
909 '''returns a dictionary {branch: [branchheads]} with branchheads
913 ordered by increasing revision number'''
910 ordered by increasing revision number'''
914 branchmap.updatecache(self)
911 branchmap.updatecache(self)
915 return self._branchcaches[self.filtername]
912 return self._branchcaches[self.filtername]
916
913
917 @unfilteredmethod
914 @unfilteredmethod
918 def revbranchcache(self):
915 def revbranchcache(self):
919 if not self._revbranchcache:
916 if not self._revbranchcache:
920 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
917 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
921 return self._revbranchcache
918 return self._revbranchcache
922
919
923 def branchtip(self, branch, ignoremissing=False):
920 def branchtip(self, branch, ignoremissing=False):
924 '''return the tip node for a given branch
921 '''return the tip node for a given branch
925
922
926 If ignoremissing is True, then this method will not raise an error.
923 If ignoremissing is True, then this method will not raise an error.
927 This is helpful for callers that only expect None for a missing branch
924 This is helpful for callers that only expect None for a missing branch
928 (e.g. namespace).
925 (e.g. namespace).
929
926
930 '''
927 '''
931 try:
928 try:
932 return self.branchmap().branchtip(branch)
929 return self.branchmap().branchtip(branch)
933 except KeyError:
930 except KeyError:
934 if not ignoremissing:
931 if not ignoremissing:
935 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
932 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
936 else:
933 else:
937 pass
934 pass
938
935
939 def lookup(self, key):
936 def lookup(self, key):
940 return self[key].node()
937 return self[key].node()
941
938
942 def lookupbranch(self, key, remote=None):
939 def lookupbranch(self, key, remote=None):
943 repo = remote or self
940 repo = remote or self
944 if key in repo.branchmap():
941 if key in repo.branchmap():
945 return key
942 return key
946
943
947 repo = (remote and remote.local()) and remote or self
944 repo = (remote and remote.local()) and remote or self
948 return repo[key].branch()
945 return repo[key].branch()
949
946
950 def known(self, nodes):
947 def known(self, nodes):
951 cl = self.changelog
948 cl = self.changelog
952 nm = cl.nodemap
949 nm = cl.nodemap
953 filtered = cl.filteredrevs
950 filtered = cl.filteredrevs
954 result = []
951 result = []
955 for n in nodes:
952 for n in nodes:
956 r = nm.get(n)
953 r = nm.get(n)
957 resp = not (r is None or r in filtered)
954 resp = not (r is None or r in filtered)
958 result.append(resp)
955 result.append(resp)
959 return result
956 return result
960
957
961 def local(self):
958 def local(self):
962 return self
959 return self
963
960
964 def publishing(self):
961 def publishing(self):
965 # it's safe (and desirable) to trust the publish flag unconditionally
962 # it's safe (and desirable) to trust the publish flag unconditionally
966 # so that we don't finalize changes shared between users via ssh or nfs
963 # so that we don't finalize changes shared between users via ssh or nfs
967 return self.ui.configbool('phases', 'publish', untrusted=True)
964 return self.ui.configbool('phases', 'publish', untrusted=True)
968
965
969 def cancopy(self):
966 def cancopy(self):
970 # so statichttprepo's override of local() works
967 # so statichttprepo's override of local() works
971 if not self.local():
968 if not self.local():
972 return False
969 return False
973 if not self.publishing():
970 if not self.publishing():
974 return True
971 return True
975 # if publishing we can't copy if there is filtered content
972 # if publishing we can't copy if there is filtered content
976 return not self.filtered('visible').changelog.filteredrevs
973 return not self.filtered('visible').changelog.filteredrevs
977
974
978 def shared(self):
975 def shared(self):
979 '''the type of shared repository (None if not shared)'''
976 '''the type of shared repository (None if not shared)'''
980 if self.sharedpath != self.path:
977 if self.sharedpath != self.path:
981 return 'store'
978 return 'store'
982 return None
979 return None
983
980
984 def wjoin(self, f, *insidef):
981 def wjoin(self, f, *insidef):
985 return self.vfs.reljoin(self.root, f, *insidef)
982 return self.vfs.reljoin(self.root, f, *insidef)
986
983
987 def file(self, f):
984 def file(self, f):
988 if f[0] == '/':
985 if f[0] == '/':
989 f = f[1:]
986 f = f[1:]
990 return filelog.filelog(self.svfs, f)
987 return filelog.filelog(self.svfs, f)
991
988
992 def changectx(self, changeid):
989 def changectx(self, changeid):
993 return self[changeid]
990 return self[changeid]
994
991
995 def setparents(self, p1, p2=nullid):
992 def setparents(self, p1, p2=nullid):
996 with self.dirstate.parentchange():
993 with self.dirstate.parentchange():
997 copies = self.dirstate.setparents(p1, p2)
994 copies = self.dirstate.setparents(p1, p2)
998 pctx = self[p1]
995 pctx = self[p1]
999 if copies:
996 if copies:
1000 # Adjust copy records, the dirstate cannot do it, it
997 # Adjust copy records, the dirstate cannot do it, it
1001 # requires access to parents manifests. Preserve them
998 # requires access to parents manifests. Preserve them
1002 # only for entries added to first parent.
999 # only for entries added to first parent.
1003 for f in copies:
1000 for f in copies:
1004 if f not in pctx and copies[f] in pctx:
1001 if f not in pctx and copies[f] in pctx:
1005 self.dirstate.copy(copies[f], f)
1002 self.dirstate.copy(copies[f], f)
1006 if p2 == nullid:
1003 if p2 == nullid:
1007 for f, s in sorted(self.dirstate.copies().items()):
1004 for f, s in sorted(self.dirstate.copies().items()):
1008 if f not in pctx and s not in pctx:
1005 if f not in pctx and s not in pctx:
1009 self.dirstate.copy(None, f)
1006 self.dirstate.copy(None, f)
1010
1007
1011 def filectx(self, path, changeid=None, fileid=None):
1008 def filectx(self, path, changeid=None, fileid=None):
1012 """changeid can be a changeset revision, node, or tag.
1009 """changeid can be a changeset revision, node, or tag.
1013 fileid can be a file revision or node."""
1010 fileid can be a file revision or node."""
1014 return context.filectx(self, path, changeid, fileid)
1011 return context.filectx(self, path, changeid, fileid)
1015
1012
1016 def getcwd(self):
1013 def getcwd(self):
1017 return self.dirstate.getcwd()
1014 return self.dirstate.getcwd()
1018
1015
1019 def pathto(self, f, cwd=None):
1016 def pathto(self, f, cwd=None):
1020 return self.dirstate.pathto(f, cwd)
1017 return self.dirstate.pathto(f, cwd)
1021
1018
1022 def _loadfilter(self, filter):
1019 def _loadfilter(self, filter):
1023 if filter not in self.filterpats:
1020 if filter not in self.filterpats:
1024 l = []
1021 l = []
1025 for pat, cmd in self.ui.configitems(filter):
1022 for pat, cmd in self.ui.configitems(filter):
1026 if cmd == '!':
1023 if cmd == '!':
1027 continue
1024 continue
1028 mf = matchmod.match(self.root, '', [pat])
1025 mf = matchmod.match(self.root, '', [pat])
1029 fn = None
1026 fn = None
1030 params = cmd
1027 params = cmd
1031 for name, filterfn in self._datafilters.iteritems():
1028 for name, filterfn in self._datafilters.iteritems():
1032 if cmd.startswith(name):
1029 if cmd.startswith(name):
1033 fn = filterfn
1030 fn = filterfn
1034 params = cmd[len(name):].lstrip()
1031 params = cmd[len(name):].lstrip()
1035 break
1032 break
1036 if not fn:
1033 if not fn:
1037 fn = lambda s, c, **kwargs: util.filter(s, c)
1034 fn = lambda s, c, **kwargs: util.filter(s, c)
1038 # Wrap old filters not supporting keyword arguments
1035 # Wrap old filters not supporting keyword arguments
1039 if not inspect.getargspec(fn)[2]:
1036 if not inspect.getargspec(fn)[2]:
1040 oldfn = fn
1037 oldfn = fn
1041 fn = lambda s, c, **kwargs: oldfn(s, c)
1038 fn = lambda s, c, **kwargs: oldfn(s, c)
1042 l.append((mf, fn, params))
1039 l.append((mf, fn, params))
1043 self.filterpats[filter] = l
1040 self.filterpats[filter] = l
1044 return self.filterpats[filter]
1041 return self.filterpats[filter]
1045
1042
1046 def _filter(self, filterpats, filename, data):
1043 def _filter(self, filterpats, filename, data):
1047 for mf, fn, cmd in filterpats:
1044 for mf, fn, cmd in filterpats:
1048 if mf(filename):
1045 if mf(filename):
1049 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1046 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1050 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1047 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1051 break
1048 break
1052
1049
1053 return data
1050 return data
1054
1051
1055 @unfilteredpropertycache
1052 @unfilteredpropertycache
1056 def _encodefilterpats(self):
1053 def _encodefilterpats(self):
1057 return self._loadfilter('encode')
1054 return self._loadfilter('encode')
1058
1055
1059 @unfilteredpropertycache
1056 @unfilteredpropertycache
1060 def _decodefilterpats(self):
1057 def _decodefilterpats(self):
1061 return self._loadfilter('decode')
1058 return self._loadfilter('decode')
1062
1059
1063 def adddatafilter(self, name, filter):
1060 def adddatafilter(self, name, filter):
1064 self._datafilters[name] = filter
1061 self._datafilters[name] = filter
1065
1062
1066 def wread(self, filename):
1063 def wread(self, filename):
1067 if self.wvfs.islink(filename):
1064 if self.wvfs.islink(filename):
1068 data = self.wvfs.readlink(filename)
1065 data = self.wvfs.readlink(filename)
1069 else:
1066 else:
1070 data = self.wvfs.read(filename)
1067 data = self.wvfs.read(filename)
1071 return self._filter(self._encodefilterpats, filename, data)
1068 return self._filter(self._encodefilterpats, filename, data)
1072
1069
1073 def wwrite(self, filename, data, flags, backgroundclose=False):
1070 def wwrite(self, filename, data, flags, backgroundclose=False):
1074 """write ``data`` into ``filename`` in the working directory
1071 """write ``data`` into ``filename`` in the working directory
1075
1072
1076 This returns length of written (maybe decoded) data.
1073 This returns length of written (maybe decoded) data.
1077 """
1074 """
1078 data = self._filter(self._decodefilterpats, filename, data)
1075 data = self._filter(self._decodefilterpats, filename, data)
1079 if 'l' in flags:
1076 if 'l' in flags:
1080 self.wvfs.symlink(data, filename)
1077 self.wvfs.symlink(data, filename)
1081 else:
1078 else:
1082 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1079 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1083 if 'x' in flags:
1080 if 'x' in flags:
1084 self.wvfs.setflags(filename, False, True)
1081 self.wvfs.setflags(filename, False, True)
1085 return len(data)
1082 return len(data)
1086
1083
1087 def wwritedata(self, filename, data):
1084 def wwritedata(self, filename, data):
1088 return self._filter(self._decodefilterpats, filename, data)
1085 return self._filter(self._decodefilterpats, filename, data)
1089
1086
1090 def currenttransaction(self):
1087 def currenttransaction(self):
1091 """return the current transaction or None if non exists"""
1088 """return the current transaction or None if non exists"""
1092 if self._transref:
1089 if self._transref:
1093 tr = self._transref()
1090 tr = self._transref()
1094 else:
1091 else:
1095 tr = None
1092 tr = None
1096
1093
1097 if tr and tr.running():
1094 if tr and tr.running():
1098 return tr
1095 return tr
1099 return None
1096 return None
1100
1097
1101 def transaction(self, desc, report=None):
1098 def transaction(self, desc, report=None):
1102 if (self.ui.configbool('devel', 'all-warnings')
1099 if (self.ui.configbool('devel', 'all-warnings')
1103 or self.ui.configbool('devel', 'check-locks')):
1100 or self.ui.configbool('devel', 'check-locks')):
1104 if self._currentlock(self._lockref) is None:
1101 if self._currentlock(self._lockref) is None:
1105 raise error.ProgrammingError('transaction requires locking')
1102 raise error.ProgrammingError('transaction requires locking')
1106 tr = self.currenttransaction()
1103 tr = self.currenttransaction()
1107 if tr is not None:
1104 if tr is not None:
1108 scmutil.registersummarycallback(self, tr, desc)
1105 scmutil.registersummarycallback(self, tr, desc)
1109 return tr.nest()
1106 return tr.nest()
1110
1107
1111 # abort here if the journal already exists
1108 # abort here if the journal already exists
1112 if self.svfs.exists("journal"):
1109 if self.svfs.exists("journal"):
1113 raise error.RepoError(
1110 raise error.RepoError(
1114 _("abandoned transaction found"),
1111 _("abandoned transaction found"),
1115 hint=_("run 'hg recover' to clean up transaction"))
1112 hint=_("run 'hg recover' to clean up transaction"))
1116
1113
1117 idbase = "%.40f#%f" % (random.random(), time.time())
1114 idbase = "%.40f#%f" % (random.random(), time.time())
1118 ha = hex(hashlib.sha1(idbase).digest())
1115 ha = hex(hashlib.sha1(idbase).digest())
1119 txnid = 'TXN:' + ha
1116 txnid = 'TXN:' + ha
1120 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1117 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1121
1118
1122 self._writejournal(desc)
1119 self._writejournal(desc)
1123 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1120 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1124 if report:
1121 if report:
1125 rp = report
1122 rp = report
1126 else:
1123 else:
1127 rp = self.ui.warn
1124 rp = self.ui.warn
1128 vfsmap = {'plain': self.vfs} # root of .hg/
1125 vfsmap = {'plain': self.vfs} # root of .hg/
1129 # we must avoid cyclic reference between repo and transaction.
1126 # we must avoid cyclic reference between repo and transaction.
1130 reporef = weakref.ref(self)
1127 reporef = weakref.ref(self)
1131 # Code to track tag movement
1128 # Code to track tag movement
1132 #
1129 #
1133 # Since tags are all handled as file content, it is actually quite hard
1130 # Since tags are all handled as file content, it is actually quite hard
1134 # to track these movement from a code perspective. So we fallback to a
1131 # to track these movement from a code perspective. So we fallback to a
1135 # tracking at the repository level. One could envision to track changes
1132 # tracking at the repository level. One could envision to track changes
1136 # to the '.hgtags' file through changegroup apply but that fails to
1133 # to the '.hgtags' file through changegroup apply but that fails to
1137 # cope with case where transaction expose new heads without changegroup
1134 # cope with case where transaction expose new heads without changegroup
1138 # being involved (eg: phase movement).
1135 # being involved (eg: phase movement).
1139 #
1136 #
1140 # For now, We gate the feature behind a flag since this likely comes
1137 # For now, We gate the feature behind a flag since this likely comes
1141 # with performance impacts. The current code run more often than needed
1138 # with performance impacts. The current code run more often than needed
1142 # and do not use caches as much as it could. The current focus is on
1139 # and do not use caches as much as it could. The current focus is on
1143 # the behavior of the feature so we disable it by default. The flag
1140 # the behavior of the feature so we disable it by default. The flag
1144 # will be removed when we are happy with the performance impact.
1141 # will be removed when we are happy with the performance impact.
1145 #
1142 #
1146 # Once this feature is no longer experimental move the following
1143 # Once this feature is no longer experimental move the following
1147 # documentation to the appropriate help section:
1144 # documentation to the appropriate help section:
1148 #
1145 #
1149 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1146 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1150 # tags (new or changed or deleted tags). In addition the details of
1147 # tags (new or changed or deleted tags). In addition the details of
1151 # these changes are made available in a file at:
1148 # these changes are made available in a file at:
1152 # ``REPOROOT/.hg/changes/tags.changes``.
1149 # ``REPOROOT/.hg/changes/tags.changes``.
1153 # Make sure you check for HG_TAG_MOVED before reading that file as it
1150 # Make sure you check for HG_TAG_MOVED before reading that file as it
1154 # might exist from a previous transaction even if no tag were touched
1151 # might exist from a previous transaction even if no tag were touched
1155 # in this one. Changes are recorded in a line base format::
1152 # in this one. Changes are recorded in a line base format::
1156 #
1153 #
1157 # <action> <hex-node> <tag-name>\n
1154 # <action> <hex-node> <tag-name>\n
1158 #
1155 #
1159 # Actions are defined as follow:
1156 # Actions are defined as follow:
1160 # "-R": tag is removed,
1157 # "-R": tag is removed,
1161 # "+A": tag is added,
1158 # "+A": tag is added,
1162 # "-M": tag is moved (old value),
1159 # "-M": tag is moved (old value),
1163 # "+M": tag is moved (new value),
1160 # "+M": tag is moved (new value),
1164 tracktags = lambda x: None
1161 tracktags = lambda x: None
1165 # experimental config: experimental.hook-track-tags
1162 # experimental config: experimental.hook-track-tags
1166 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1163 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1167 if desc != 'strip' and shouldtracktags:
1164 if desc != 'strip' and shouldtracktags:
1168 oldheads = self.changelog.headrevs()
1165 oldheads = self.changelog.headrevs()
1169 def tracktags(tr2):
1166 def tracktags(tr2):
1170 repo = reporef()
1167 repo = reporef()
1171 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1168 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1172 newheads = repo.changelog.headrevs()
1169 newheads = repo.changelog.headrevs()
1173 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1170 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1174 # notes: we compare lists here.
1171 # notes: we compare lists here.
1175 # As we do it only once buiding set would not be cheaper
1172 # As we do it only once buiding set would not be cheaper
1176 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1173 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1177 if changes:
1174 if changes:
1178 tr2.hookargs['tag_moved'] = '1'
1175 tr2.hookargs['tag_moved'] = '1'
1179 with repo.vfs('changes/tags.changes', 'w',
1176 with repo.vfs('changes/tags.changes', 'w',
1180 atomictemp=True) as changesfile:
1177 atomictemp=True) as changesfile:
1181 # note: we do not register the file to the transaction
1178 # note: we do not register the file to the transaction
1182 # because we needs it to still exist on the transaction
1179 # because we needs it to still exist on the transaction
1183 # is close (for txnclose hooks)
1180 # is close (for txnclose hooks)
1184 tagsmod.writediff(changesfile, changes)
1181 tagsmod.writediff(changesfile, changes)
1185 def validate(tr2):
1182 def validate(tr2):
1186 """will run pre-closing hooks"""
1183 """will run pre-closing hooks"""
1187 # XXX the transaction API is a bit lacking here so we take a hacky
1184 # XXX the transaction API is a bit lacking here so we take a hacky
1188 # path for now
1185 # path for now
1189 #
1186 #
1190 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1187 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1191 # dict is copied before these run. In addition we needs the data
1188 # dict is copied before these run. In addition we needs the data
1192 # available to in memory hooks too.
1189 # available to in memory hooks too.
1193 #
1190 #
1194 # Moreover, we also need to make sure this runs before txnclose
1191 # Moreover, we also need to make sure this runs before txnclose
1195 # hooks and there is no "pending" mechanism that would execute
1192 # hooks and there is no "pending" mechanism that would execute
1196 # logic only if hooks are about to run.
1193 # logic only if hooks are about to run.
1197 #
1194 #
1198 # Fixing this limitation of the transaction is also needed to track
1195 # Fixing this limitation of the transaction is also needed to track
1199 # other families of changes (bookmarks, phases, obsolescence).
1196 # other families of changes (bookmarks, phases, obsolescence).
1200 #
1197 #
1201 # This will have to be fixed before we remove the experimental
1198 # This will have to be fixed before we remove the experimental
1202 # gating.
1199 # gating.
1203 tracktags(tr2)
1200 tracktags(tr2)
1204 reporef().hook('pretxnclose', throw=True,
1201 reporef().hook('pretxnclose', throw=True,
1205 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1202 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1206 def releasefn(tr, success):
1203 def releasefn(tr, success):
1207 repo = reporef()
1204 repo = reporef()
1208 if success:
1205 if success:
1209 # this should be explicitly invoked here, because
1206 # this should be explicitly invoked here, because
1210 # in-memory changes aren't written out at closing
1207 # in-memory changes aren't written out at closing
1211 # transaction, if tr.addfilegenerator (via
1208 # transaction, if tr.addfilegenerator (via
1212 # dirstate.write or so) isn't invoked while
1209 # dirstate.write or so) isn't invoked while
1213 # transaction running
1210 # transaction running
1214 repo.dirstate.write(None)
1211 repo.dirstate.write(None)
1215 else:
1212 else:
1216 # discard all changes (including ones already written
1213 # discard all changes (including ones already written
1217 # out) in this transaction
1214 # out) in this transaction
1218 repo.dirstate.restorebackup(None, 'journal.dirstate')
1215 repo.dirstate.restorebackup(None, 'journal.dirstate')
1219
1216
1220 repo.invalidate(clearfilecache=True)
1217 repo.invalidate(clearfilecache=True)
1221
1218
1222 tr = transaction.transaction(rp, self.svfs, vfsmap,
1219 tr = transaction.transaction(rp, self.svfs, vfsmap,
1223 "journal",
1220 "journal",
1224 "undo",
1221 "undo",
1225 aftertrans(renames),
1222 aftertrans(renames),
1226 self.store.createmode,
1223 self.store.createmode,
1227 validator=validate,
1224 validator=validate,
1228 releasefn=releasefn,
1225 releasefn=releasefn,
1229 checkambigfiles=_cachedfiles)
1226 checkambigfiles=_cachedfiles)
1230 tr.changes['revs'] = set()
1227 tr.changes['revs'] = set()
1231 tr.changes['obsmarkers'] = set()
1228 tr.changes['obsmarkers'] = set()
1232 tr.changes['phases'] = {}
1229 tr.changes['phases'] = {}
1233 tr.changes['bookmarks'] = {}
1230 tr.changes['bookmarks'] = {}
1234
1231
1235 tr.hookargs['txnid'] = txnid
1232 tr.hookargs['txnid'] = txnid
1236 # note: writing the fncache only during finalize mean that the file is
1233 # note: writing the fncache only during finalize mean that the file is
1237 # outdated when running hooks. As fncache is used for streaming clone,
1234 # outdated when running hooks. As fncache is used for streaming clone,
1238 # this is not expected to break anything that happen during the hooks.
1235 # this is not expected to break anything that happen during the hooks.
1239 tr.addfinalize('flush-fncache', self.store.write)
1236 tr.addfinalize('flush-fncache', self.store.write)
1240 def txnclosehook(tr2):
1237 def txnclosehook(tr2):
1241 """To be run if transaction is successful, will schedule a hook run
1238 """To be run if transaction is successful, will schedule a hook run
1242 """
1239 """
1243 # Don't reference tr2 in hook() so we don't hold a reference.
1240 # Don't reference tr2 in hook() so we don't hold a reference.
1244 # This reduces memory consumption when there are multiple
1241 # This reduces memory consumption when there are multiple
1245 # transactions per lock. This can likely go away if issue5045
1242 # transactions per lock. This can likely go away if issue5045
1246 # fixes the function accumulation.
1243 # fixes the function accumulation.
1247 hookargs = tr2.hookargs
1244 hookargs = tr2.hookargs
1248
1245
1249 def hook():
1246 def hook():
1250 reporef().hook('txnclose', throw=False, txnname=desc,
1247 reporef().hook('txnclose', throw=False, txnname=desc,
1251 **pycompat.strkwargs(hookargs))
1248 **pycompat.strkwargs(hookargs))
1252 reporef()._afterlock(hook)
1249 reporef()._afterlock(hook)
1253 tr.addfinalize('txnclose-hook', txnclosehook)
1250 tr.addfinalize('txnclose-hook', txnclosehook)
1254 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1251 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1255 def txnaborthook(tr2):
1252 def txnaborthook(tr2):
1256 """To be run if transaction is aborted
1253 """To be run if transaction is aborted
1257 """
1254 """
1258 reporef().hook('txnabort', throw=False, txnname=desc,
1255 reporef().hook('txnabort', throw=False, txnname=desc,
1259 **tr2.hookargs)
1256 **tr2.hookargs)
1260 tr.addabort('txnabort-hook', txnaborthook)
1257 tr.addabort('txnabort-hook', txnaborthook)
1261 # avoid eager cache invalidation. in-memory data should be identical
1258 # avoid eager cache invalidation. in-memory data should be identical
1262 # to stored data if transaction has no error.
1259 # to stored data if transaction has no error.
1263 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1260 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1264 self._transref = weakref.ref(tr)
1261 self._transref = weakref.ref(tr)
1265 scmutil.registersummarycallback(self, tr, desc)
1262 scmutil.registersummarycallback(self, tr, desc)
1266 return tr
1263 return tr
1267
1264
1268 def _journalfiles(self):
1265 def _journalfiles(self):
1269 return ((self.svfs, 'journal'),
1266 return ((self.svfs, 'journal'),
1270 (self.vfs, 'journal.dirstate'),
1267 (self.vfs, 'journal.dirstate'),
1271 (self.vfs, 'journal.branch'),
1268 (self.vfs, 'journal.branch'),
1272 (self.vfs, 'journal.desc'),
1269 (self.vfs, 'journal.desc'),
1273 (self.vfs, 'journal.bookmarks'),
1270 (self.vfs, 'journal.bookmarks'),
1274 (self.svfs, 'journal.phaseroots'))
1271 (self.svfs, 'journal.phaseroots'))
1275
1272
1276 def undofiles(self):
1273 def undofiles(self):
1277 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1274 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1278
1275
1279 @unfilteredmethod
1276 @unfilteredmethod
1280 def _writejournal(self, desc):
1277 def _writejournal(self, desc):
1281 self.dirstate.savebackup(None, 'journal.dirstate')
1278 self.dirstate.savebackup(None, 'journal.dirstate')
1282 self.vfs.write("journal.branch",
1279 self.vfs.write("journal.branch",
1283 encoding.fromlocal(self.dirstate.branch()))
1280 encoding.fromlocal(self.dirstate.branch()))
1284 self.vfs.write("journal.desc",
1281 self.vfs.write("journal.desc",
1285 "%d\n%s\n" % (len(self), desc))
1282 "%d\n%s\n" % (len(self), desc))
1286 self.vfs.write("journal.bookmarks",
1283 self.vfs.write("journal.bookmarks",
1287 self.vfs.tryread("bookmarks"))
1284 self.vfs.tryread("bookmarks"))
1288 self.svfs.write("journal.phaseroots",
1285 self.svfs.write("journal.phaseroots",
1289 self.svfs.tryread("phaseroots"))
1286 self.svfs.tryread("phaseroots"))
1290
1287
1291 def recover(self):
1288 def recover(self):
1292 with self.lock():
1289 with self.lock():
1293 if self.svfs.exists("journal"):
1290 if self.svfs.exists("journal"):
1294 self.ui.status(_("rolling back interrupted transaction\n"))
1291 self.ui.status(_("rolling back interrupted transaction\n"))
1295 vfsmap = {'': self.svfs,
1292 vfsmap = {'': self.svfs,
1296 'plain': self.vfs,}
1293 'plain': self.vfs,}
1297 transaction.rollback(self.svfs, vfsmap, "journal",
1294 transaction.rollback(self.svfs, vfsmap, "journal",
1298 self.ui.warn,
1295 self.ui.warn,
1299 checkambigfiles=_cachedfiles)
1296 checkambigfiles=_cachedfiles)
1300 self.invalidate()
1297 self.invalidate()
1301 return True
1298 return True
1302 else:
1299 else:
1303 self.ui.warn(_("no interrupted transaction available\n"))
1300 self.ui.warn(_("no interrupted transaction available\n"))
1304 return False
1301 return False
1305
1302
1306 def rollback(self, dryrun=False, force=False):
1303 def rollback(self, dryrun=False, force=False):
1307 wlock = lock = dsguard = None
1304 wlock = lock = dsguard = None
1308 try:
1305 try:
1309 wlock = self.wlock()
1306 wlock = self.wlock()
1310 lock = self.lock()
1307 lock = self.lock()
1311 if self.svfs.exists("undo"):
1308 if self.svfs.exists("undo"):
1312 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1309 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1313
1310
1314 return self._rollback(dryrun, force, dsguard)
1311 return self._rollback(dryrun, force, dsguard)
1315 else:
1312 else:
1316 self.ui.warn(_("no rollback information available\n"))
1313 self.ui.warn(_("no rollback information available\n"))
1317 return 1
1314 return 1
1318 finally:
1315 finally:
1319 release(dsguard, lock, wlock)
1316 release(dsguard, lock, wlock)
1320
1317
1321 @unfilteredmethod # Until we get smarter cache management
1318 @unfilteredmethod # Until we get smarter cache management
1322 def _rollback(self, dryrun, force, dsguard):
1319 def _rollback(self, dryrun, force, dsguard):
1323 ui = self.ui
1320 ui = self.ui
1324 try:
1321 try:
1325 args = self.vfs.read('undo.desc').splitlines()
1322 args = self.vfs.read('undo.desc').splitlines()
1326 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1323 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1327 if len(args) >= 3:
1324 if len(args) >= 3:
1328 detail = args[2]
1325 detail = args[2]
1329 oldtip = oldlen - 1
1326 oldtip = oldlen - 1
1330
1327
1331 if detail and ui.verbose:
1328 if detail and ui.verbose:
1332 msg = (_('repository tip rolled back to revision %d'
1329 msg = (_('repository tip rolled back to revision %d'
1333 ' (undo %s: %s)\n')
1330 ' (undo %s: %s)\n')
1334 % (oldtip, desc, detail))
1331 % (oldtip, desc, detail))
1335 else:
1332 else:
1336 msg = (_('repository tip rolled back to revision %d'
1333 msg = (_('repository tip rolled back to revision %d'
1337 ' (undo %s)\n')
1334 ' (undo %s)\n')
1338 % (oldtip, desc))
1335 % (oldtip, desc))
1339 except IOError:
1336 except IOError:
1340 msg = _('rolling back unknown transaction\n')
1337 msg = _('rolling back unknown transaction\n')
1341 desc = None
1338 desc = None
1342
1339
1343 if not force and self['.'] != self['tip'] and desc == 'commit':
1340 if not force and self['.'] != self['tip'] and desc == 'commit':
1344 raise error.Abort(
1341 raise error.Abort(
1345 _('rollback of last commit while not checked out '
1342 _('rollback of last commit while not checked out '
1346 'may lose data'), hint=_('use -f to force'))
1343 'may lose data'), hint=_('use -f to force'))
1347
1344
1348 ui.status(msg)
1345 ui.status(msg)
1349 if dryrun:
1346 if dryrun:
1350 return 0
1347 return 0
1351
1348
1352 parents = self.dirstate.parents()
1349 parents = self.dirstate.parents()
1353 self.destroying()
1350 self.destroying()
1354 vfsmap = {'plain': self.vfs, '': self.svfs}
1351 vfsmap = {'plain': self.vfs, '': self.svfs}
1355 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1352 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1356 checkambigfiles=_cachedfiles)
1353 checkambigfiles=_cachedfiles)
1357 if self.vfs.exists('undo.bookmarks'):
1354 if self.vfs.exists('undo.bookmarks'):
1358 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1355 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1359 if self.svfs.exists('undo.phaseroots'):
1356 if self.svfs.exists('undo.phaseroots'):
1360 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1357 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1361 self.invalidate()
1358 self.invalidate()
1362
1359
1363 parentgone = (parents[0] not in self.changelog.nodemap or
1360 parentgone = (parents[0] not in self.changelog.nodemap or
1364 parents[1] not in self.changelog.nodemap)
1361 parents[1] not in self.changelog.nodemap)
1365 if parentgone:
1362 if parentgone:
1366 # prevent dirstateguard from overwriting already restored one
1363 # prevent dirstateguard from overwriting already restored one
1367 dsguard.close()
1364 dsguard.close()
1368
1365
1369 self.dirstate.restorebackup(None, 'undo.dirstate')
1366 self.dirstate.restorebackup(None, 'undo.dirstate')
1370 try:
1367 try:
1371 branch = self.vfs.read('undo.branch')
1368 branch = self.vfs.read('undo.branch')
1372 self.dirstate.setbranch(encoding.tolocal(branch))
1369 self.dirstate.setbranch(encoding.tolocal(branch))
1373 except IOError:
1370 except IOError:
1374 ui.warn(_('named branch could not be reset: '
1371 ui.warn(_('named branch could not be reset: '
1375 'current branch is still \'%s\'\n')
1372 'current branch is still \'%s\'\n')
1376 % self.dirstate.branch())
1373 % self.dirstate.branch())
1377
1374
1378 parents = tuple([p.rev() for p in self[None].parents()])
1375 parents = tuple([p.rev() for p in self[None].parents()])
1379 if len(parents) > 1:
1376 if len(parents) > 1:
1380 ui.status(_('working directory now based on '
1377 ui.status(_('working directory now based on '
1381 'revisions %d and %d\n') % parents)
1378 'revisions %d and %d\n') % parents)
1382 else:
1379 else:
1383 ui.status(_('working directory now based on '
1380 ui.status(_('working directory now based on '
1384 'revision %d\n') % parents)
1381 'revision %d\n') % parents)
1385 mergemod.mergestate.clean(self, self['.'].node())
1382 mergemod.mergestate.clean(self, self['.'].node())
1386
1383
1387 # TODO: if we know which new heads may result from this rollback, pass
1384 # TODO: if we know which new heads may result from this rollback, pass
1388 # them to destroy(), which will prevent the branchhead cache from being
1385 # them to destroy(), which will prevent the branchhead cache from being
1389 # invalidated.
1386 # invalidated.
1390 self.destroyed()
1387 self.destroyed()
1391 return 0
1388 return 0
1392
1389
1393 def _buildcacheupdater(self, newtransaction):
1390 def _buildcacheupdater(self, newtransaction):
1394 """called during transaction to build the callback updating cache
1391 """called during transaction to build the callback updating cache
1395
1392
1396 Lives on the repository to help extension who might want to augment
1393 Lives on the repository to help extension who might want to augment
1397 this logic. For this purpose, the created transaction is passed to the
1394 this logic. For this purpose, the created transaction is passed to the
1398 method.
1395 method.
1399 """
1396 """
1400 # we must avoid cyclic reference between repo and transaction.
1397 # we must avoid cyclic reference between repo and transaction.
1401 reporef = weakref.ref(self)
1398 reporef = weakref.ref(self)
1402 def updater(tr):
1399 def updater(tr):
1403 repo = reporef()
1400 repo = reporef()
1404 repo.updatecaches(tr)
1401 repo.updatecaches(tr)
1405 return updater
1402 return updater
1406
1403
1407 @unfilteredmethod
1404 @unfilteredmethod
1408 def updatecaches(self, tr=None):
1405 def updatecaches(self, tr=None):
1409 """warm appropriate caches
1406 """warm appropriate caches
1410
1407
1411 If this function is called after a transaction closed. The transaction
1408 If this function is called after a transaction closed. The transaction
1412 will be available in the 'tr' argument. This can be used to selectively
1409 will be available in the 'tr' argument. This can be used to selectively
1413 update caches relevant to the changes in that transaction.
1410 update caches relevant to the changes in that transaction.
1414 """
1411 """
1415 if tr is not None and tr.hookargs.get('source') == 'strip':
1412 if tr is not None and tr.hookargs.get('source') == 'strip':
1416 # During strip, many caches are invalid but
1413 # During strip, many caches are invalid but
1417 # later call to `destroyed` will refresh them.
1414 # later call to `destroyed` will refresh them.
1418 return
1415 return
1419
1416
1420 if tr is None or tr.changes['revs']:
1417 if tr is None or tr.changes['revs']:
1421 # updating the unfiltered branchmap should refresh all the others,
1418 # updating the unfiltered branchmap should refresh all the others,
1422 self.ui.debug('updating the branch cache\n')
1419 self.ui.debug('updating the branch cache\n')
1423 branchmap.updatecache(self.filtered('served'))
1420 branchmap.updatecache(self.filtered('served'))
1424
1421
1425 def invalidatecaches(self):
1422 def invalidatecaches(self):
1426
1423
1427 if '_tagscache' in vars(self):
1424 if '_tagscache' in vars(self):
1428 # can't use delattr on proxy
1425 # can't use delattr on proxy
1429 del self.__dict__['_tagscache']
1426 del self.__dict__['_tagscache']
1430
1427
1431 self.unfiltered()._branchcaches.clear()
1428 self.unfiltered()._branchcaches.clear()
1432 self.invalidatevolatilesets()
1429 self.invalidatevolatilesets()
1433 self._sparsesignaturecache.clear()
1430 self._sparsesignaturecache.clear()
1434
1431
1435 def invalidatevolatilesets(self):
1432 def invalidatevolatilesets(self):
1436 self.filteredrevcache.clear()
1433 self.filteredrevcache.clear()
1437 obsolete.clearobscaches(self)
1434 obsolete.clearobscaches(self)
1438
1435
1439 def invalidatedirstate(self):
1436 def invalidatedirstate(self):
1440 '''Invalidates the dirstate, causing the next call to dirstate
1437 '''Invalidates the dirstate, causing the next call to dirstate
1441 to check if it was modified since the last time it was read,
1438 to check if it was modified since the last time it was read,
1442 rereading it if it has.
1439 rereading it if it has.
1443
1440
1444 This is different to dirstate.invalidate() that it doesn't always
1441 This is different to dirstate.invalidate() that it doesn't always
1445 rereads the dirstate. Use dirstate.invalidate() if you want to
1442 rereads the dirstate. Use dirstate.invalidate() if you want to
1446 explicitly read the dirstate again (i.e. restoring it to a previous
1443 explicitly read the dirstate again (i.e. restoring it to a previous
1447 known good state).'''
1444 known good state).'''
1448 if hasunfilteredcache(self, 'dirstate'):
1445 if hasunfilteredcache(self, 'dirstate'):
1449 for k in self.dirstate._filecache:
1446 for k in self.dirstate._filecache:
1450 try:
1447 try:
1451 delattr(self.dirstate, k)
1448 delattr(self.dirstate, k)
1452 except AttributeError:
1449 except AttributeError:
1453 pass
1450 pass
1454 delattr(self.unfiltered(), 'dirstate')
1451 delattr(self.unfiltered(), 'dirstate')
1455
1452
1456 def invalidate(self, clearfilecache=False):
1453 def invalidate(self, clearfilecache=False):
1457 '''Invalidates both store and non-store parts other than dirstate
1454 '''Invalidates both store and non-store parts other than dirstate
1458
1455
1459 If a transaction is running, invalidation of store is omitted,
1456 If a transaction is running, invalidation of store is omitted,
1460 because discarding in-memory changes might cause inconsistency
1457 because discarding in-memory changes might cause inconsistency
1461 (e.g. incomplete fncache causes unintentional failure, but
1458 (e.g. incomplete fncache causes unintentional failure, but
1462 redundant one doesn't).
1459 redundant one doesn't).
1463 '''
1460 '''
1464 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1461 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1465 for k in list(self._filecache.keys()):
1462 for k in list(self._filecache.keys()):
1466 # dirstate is invalidated separately in invalidatedirstate()
1463 # dirstate is invalidated separately in invalidatedirstate()
1467 if k == 'dirstate':
1464 if k == 'dirstate':
1468 continue
1465 continue
1469
1466
1470 if clearfilecache:
1467 if clearfilecache:
1471 del self._filecache[k]
1468 del self._filecache[k]
1472 try:
1469 try:
1473 delattr(unfiltered, k)
1470 delattr(unfiltered, k)
1474 except AttributeError:
1471 except AttributeError:
1475 pass
1472 pass
1476 self.invalidatecaches()
1473 self.invalidatecaches()
1477 if not self.currenttransaction():
1474 if not self.currenttransaction():
1478 # TODO: Changing contents of store outside transaction
1475 # TODO: Changing contents of store outside transaction
1479 # causes inconsistency. We should make in-memory store
1476 # causes inconsistency. We should make in-memory store
1480 # changes detectable, and abort if changed.
1477 # changes detectable, and abort if changed.
1481 self.store.invalidatecaches()
1478 self.store.invalidatecaches()
1482
1479
1483 def invalidateall(self):
1480 def invalidateall(self):
1484 '''Fully invalidates both store and non-store parts, causing the
1481 '''Fully invalidates both store and non-store parts, causing the
1485 subsequent operation to reread any outside changes.'''
1482 subsequent operation to reread any outside changes.'''
1486 # extension should hook this to invalidate its caches
1483 # extension should hook this to invalidate its caches
1487 self.invalidate()
1484 self.invalidate()
1488 self.invalidatedirstate()
1485 self.invalidatedirstate()
1489
1486
1490 @unfilteredmethod
1487 @unfilteredmethod
1491 def _refreshfilecachestats(self, tr):
1488 def _refreshfilecachestats(self, tr):
1492 """Reload stats of cached files so that they are flagged as valid"""
1489 """Reload stats of cached files so that they are flagged as valid"""
1493 for k, ce in self._filecache.items():
1490 for k, ce in self._filecache.items():
1494 if k == 'dirstate' or k not in self.__dict__:
1491 if k == 'dirstate' or k not in self.__dict__:
1495 continue
1492 continue
1496 ce.refresh()
1493 ce.refresh()
1497
1494
1498 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1495 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1499 inheritchecker=None, parentenvvar=None):
1496 inheritchecker=None, parentenvvar=None):
1500 parentlock = None
1497 parentlock = None
1501 # the contents of parentenvvar are used by the underlying lock to
1498 # the contents of parentenvvar are used by the underlying lock to
1502 # determine whether it can be inherited
1499 # determine whether it can be inherited
1503 if parentenvvar is not None:
1500 if parentenvvar is not None:
1504 parentlock = encoding.environ.get(parentenvvar)
1501 parentlock = encoding.environ.get(parentenvvar)
1505 try:
1502 try:
1506 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1503 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1507 acquirefn=acquirefn, desc=desc,
1504 acquirefn=acquirefn, desc=desc,
1508 inheritchecker=inheritchecker,
1505 inheritchecker=inheritchecker,
1509 parentlock=parentlock)
1506 parentlock=parentlock)
1510 except error.LockHeld as inst:
1507 except error.LockHeld as inst:
1511 if not wait:
1508 if not wait:
1512 raise
1509 raise
1513 # show more details for new-style locks
1510 # show more details for new-style locks
1514 if ':' in inst.locker:
1511 if ':' in inst.locker:
1515 host, pid = inst.locker.split(":", 1)
1512 host, pid = inst.locker.split(":", 1)
1516 self.ui.warn(
1513 self.ui.warn(
1517 _("waiting for lock on %s held by process %r "
1514 _("waiting for lock on %s held by process %r "
1518 "on host %r\n") % (desc, pid, host))
1515 "on host %r\n") % (desc, pid, host))
1519 else:
1516 else:
1520 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1517 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1521 (desc, inst.locker))
1518 (desc, inst.locker))
1522 # default to 600 seconds timeout
1519 # default to 600 seconds timeout
1523 l = lockmod.lock(vfs, lockname,
1520 l = lockmod.lock(vfs, lockname,
1524 int(self.ui.config("ui", "timeout")),
1521 int(self.ui.config("ui", "timeout")),
1525 releasefn=releasefn, acquirefn=acquirefn,
1522 releasefn=releasefn, acquirefn=acquirefn,
1526 desc=desc)
1523 desc=desc)
1527 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1524 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1528 return l
1525 return l
1529
1526
1530 def _afterlock(self, callback):
1527 def _afterlock(self, callback):
1531 """add a callback to be run when the repository is fully unlocked
1528 """add a callback to be run when the repository is fully unlocked
1532
1529
1533 The callback will be executed when the outermost lock is released
1530 The callback will be executed when the outermost lock is released
1534 (with wlock being higher level than 'lock')."""
1531 (with wlock being higher level than 'lock')."""
1535 for ref in (self._wlockref, self._lockref):
1532 for ref in (self._wlockref, self._lockref):
1536 l = ref and ref()
1533 l = ref and ref()
1537 if l and l.held:
1534 if l and l.held:
1538 l.postrelease.append(callback)
1535 l.postrelease.append(callback)
1539 break
1536 break
1540 else: # no lock have been found.
1537 else: # no lock have been found.
1541 callback()
1538 callback()
1542
1539
1543 def lock(self, wait=True):
1540 def lock(self, wait=True):
1544 '''Lock the repository store (.hg/store) and return a weak reference
1541 '''Lock the repository store (.hg/store) and return a weak reference
1545 to the lock. Use this before modifying the store (e.g. committing or
1542 to the lock. Use this before modifying the store (e.g. committing or
1546 stripping). If you are opening a transaction, get a lock as well.)
1543 stripping). If you are opening a transaction, get a lock as well.)
1547
1544
1548 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1545 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1549 'wlock' first to avoid a dead-lock hazard.'''
1546 'wlock' first to avoid a dead-lock hazard.'''
1550 l = self._currentlock(self._lockref)
1547 l = self._currentlock(self._lockref)
1551 if l is not None:
1548 if l is not None:
1552 l.lock()
1549 l.lock()
1553 return l
1550 return l
1554
1551
1555 l = self._lock(self.svfs, "lock", wait, None,
1552 l = self._lock(self.svfs, "lock", wait, None,
1556 self.invalidate, _('repository %s') % self.origroot)
1553 self.invalidate, _('repository %s') % self.origroot)
1557 self._lockref = weakref.ref(l)
1554 self._lockref = weakref.ref(l)
1558 return l
1555 return l
1559
1556
1560 def _wlockchecktransaction(self):
1557 def _wlockchecktransaction(self):
1561 if self.currenttransaction() is not None:
1558 if self.currenttransaction() is not None:
1562 raise error.LockInheritanceContractViolation(
1559 raise error.LockInheritanceContractViolation(
1563 'wlock cannot be inherited in the middle of a transaction')
1560 'wlock cannot be inherited in the middle of a transaction')
1564
1561
1565 def wlock(self, wait=True):
1562 def wlock(self, wait=True):
1566 '''Lock the non-store parts of the repository (everything under
1563 '''Lock the non-store parts of the repository (everything under
1567 .hg except .hg/store) and return a weak reference to the lock.
1564 .hg except .hg/store) and return a weak reference to the lock.
1568
1565
1569 Use this before modifying files in .hg.
1566 Use this before modifying files in .hg.
1570
1567
1571 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1568 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1572 'wlock' first to avoid a dead-lock hazard.'''
1569 'wlock' first to avoid a dead-lock hazard.'''
1573 l = self._wlockref and self._wlockref()
1570 l = self._wlockref and self._wlockref()
1574 if l is not None and l.held:
1571 if l is not None and l.held:
1575 l.lock()
1572 l.lock()
1576 return l
1573 return l
1577
1574
1578 # We do not need to check for non-waiting lock acquisition. Such
1575 # We do not need to check for non-waiting lock acquisition. Such
1579 # acquisition would not cause dead-lock as they would just fail.
1576 # acquisition would not cause dead-lock as they would just fail.
1580 if wait and (self.ui.configbool('devel', 'all-warnings')
1577 if wait and (self.ui.configbool('devel', 'all-warnings')
1581 or self.ui.configbool('devel', 'check-locks')):
1578 or self.ui.configbool('devel', 'check-locks')):
1582 if self._currentlock(self._lockref) is not None:
1579 if self._currentlock(self._lockref) is not None:
1583 self.ui.develwarn('"wlock" acquired after "lock"')
1580 self.ui.develwarn('"wlock" acquired after "lock"')
1584
1581
1585 def unlock():
1582 def unlock():
1586 if self.dirstate.pendingparentchange():
1583 if self.dirstate.pendingparentchange():
1587 self.dirstate.invalidate()
1584 self.dirstate.invalidate()
1588 else:
1585 else:
1589 self.dirstate.write(None)
1586 self.dirstate.write(None)
1590
1587
1591 self._filecache['dirstate'].refresh()
1588 self._filecache['dirstate'].refresh()
1592
1589
1593 l = self._lock(self.vfs, "wlock", wait, unlock,
1590 l = self._lock(self.vfs, "wlock", wait, unlock,
1594 self.invalidatedirstate, _('working directory of %s') %
1591 self.invalidatedirstate, _('working directory of %s') %
1595 self.origroot,
1592 self.origroot,
1596 inheritchecker=self._wlockchecktransaction,
1593 inheritchecker=self._wlockchecktransaction,
1597 parentenvvar='HG_WLOCK_LOCKER')
1594 parentenvvar='HG_WLOCK_LOCKER')
1598 self._wlockref = weakref.ref(l)
1595 self._wlockref = weakref.ref(l)
1599 return l
1596 return l
1600
1597
1601 def _currentlock(self, lockref):
1598 def _currentlock(self, lockref):
1602 """Returns the lock if it's held, or None if it's not."""
1599 """Returns the lock if it's held, or None if it's not."""
1603 if lockref is None:
1600 if lockref is None:
1604 return None
1601 return None
1605 l = lockref()
1602 l = lockref()
1606 if l is None or not l.held:
1603 if l is None or not l.held:
1607 return None
1604 return None
1608 return l
1605 return l
1609
1606
1610 def currentwlock(self):
1607 def currentwlock(self):
1611 """Returns the wlock if it's held, or None if it's not."""
1608 """Returns the wlock if it's held, or None if it's not."""
1612 return self._currentlock(self._wlockref)
1609 return self._currentlock(self._wlockref)
1613
1610
1614 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1611 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1615 """
1612 """
1616 commit an individual file as part of a larger transaction
1613 commit an individual file as part of a larger transaction
1617 """
1614 """
1618
1615
1619 fname = fctx.path()
1616 fname = fctx.path()
1620 fparent1 = manifest1.get(fname, nullid)
1617 fparent1 = manifest1.get(fname, nullid)
1621 fparent2 = manifest2.get(fname, nullid)
1618 fparent2 = manifest2.get(fname, nullid)
1622 if isinstance(fctx, context.filectx):
1619 if isinstance(fctx, context.filectx):
1623 node = fctx.filenode()
1620 node = fctx.filenode()
1624 if node in [fparent1, fparent2]:
1621 if node in [fparent1, fparent2]:
1625 self.ui.debug('reusing %s filelog entry\n' % fname)
1622 self.ui.debug('reusing %s filelog entry\n' % fname)
1626 if manifest1.flags(fname) != fctx.flags():
1623 if manifest1.flags(fname) != fctx.flags():
1627 changelist.append(fname)
1624 changelist.append(fname)
1628 return node
1625 return node
1629
1626
1630 flog = self.file(fname)
1627 flog = self.file(fname)
1631 meta = {}
1628 meta = {}
1632 copy = fctx.renamed()
1629 copy = fctx.renamed()
1633 if copy and copy[0] != fname:
1630 if copy and copy[0] != fname:
1634 # Mark the new revision of this file as a copy of another
1631 # Mark the new revision of this file as a copy of another
1635 # file. This copy data will effectively act as a parent
1632 # file. This copy data will effectively act as a parent
1636 # of this new revision. If this is a merge, the first
1633 # of this new revision. If this is a merge, the first
1637 # parent will be the nullid (meaning "look up the copy data")
1634 # parent will be the nullid (meaning "look up the copy data")
1638 # and the second one will be the other parent. For example:
1635 # and the second one will be the other parent. For example:
1639 #
1636 #
1640 # 0 --- 1 --- 3 rev1 changes file foo
1637 # 0 --- 1 --- 3 rev1 changes file foo
1641 # \ / rev2 renames foo to bar and changes it
1638 # \ / rev2 renames foo to bar and changes it
1642 # \- 2 -/ rev3 should have bar with all changes and
1639 # \- 2 -/ rev3 should have bar with all changes and
1643 # should record that bar descends from
1640 # should record that bar descends from
1644 # bar in rev2 and foo in rev1
1641 # bar in rev2 and foo in rev1
1645 #
1642 #
1646 # this allows this merge to succeed:
1643 # this allows this merge to succeed:
1647 #
1644 #
1648 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1645 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1649 # \ / merging rev3 and rev4 should use bar@rev2
1646 # \ / merging rev3 and rev4 should use bar@rev2
1650 # \- 2 --- 4 as the merge base
1647 # \- 2 --- 4 as the merge base
1651 #
1648 #
1652
1649
1653 cfname = copy[0]
1650 cfname = copy[0]
1654 crev = manifest1.get(cfname)
1651 crev = manifest1.get(cfname)
1655 newfparent = fparent2
1652 newfparent = fparent2
1656
1653
1657 if manifest2: # branch merge
1654 if manifest2: # branch merge
1658 if fparent2 == nullid or crev is None: # copied on remote side
1655 if fparent2 == nullid or crev is None: # copied on remote side
1659 if cfname in manifest2:
1656 if cfname in manifest2:
1660 crev = manifest2[cfname]
1657 crev = manifest2[cfname]
1661 newfparent = fparent1
1658 newfparent = fparent1
1662
1659
1663 # Here, we used to search backwards through history to try to find
1660 # Here, we used to search backwards through history to try to find
1664 # where the file copy came from if the source of a copy was not in
1661 # where the file copy came from if the source of a copy was not in
1665 # the parent directory. However, this doesn't actually make sense to
1662 # the parent directory. However, this doesn't actually make sense to
1666 # do (what does a copy from something not in your working copy even
1663 # do (what does a copy from something not in your working copy even
1667 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1664 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1668 # the user that copy information was dropped, so if they didn't
1665 # the user that copy information was dropped, so if they didn't
1669 # expect this outcome it can be fixed, but this is the correct
1666 # expect this outcome it can be fixed, but this is the correct
1670 # behavior in this circumstance.
1667 # behavior in this circumstance.
1671
1668
1672 if crev:
1669 if crev:
1673 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1670 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1674 meta["copy"] = cfname
1671 meta["copy"] = cfname
1675 meta["copyrev"] = hex(crev)
1672 meta["copyrev"] = hex(crev)
1676 fparent1, fparent2 = nullid, newfparent
1673 fparent1, fparent2 = nullid, newfparent
1677 else:
1674 else:
1678 self.ui.warn(_("warning: can't find ancestor for '%s' "
1675 self.ui.warn(_("warning: can't find ancestor for '%s' "
1679 "copied from '%s'!\n") % (fname, cfname))
1676 "copied from '%s'!\n") % (fname, cfname))
1680
1677
1681 elif fparent1 == nullid:
1678 elif fparent1 == nullid:
1682 fparent1, fparent2 = fparent2, nullid
1679 fparent1, fparent2 = fparent2, nullid
1683 elif fparent2 != nullid:
1680 elif fparent2 != nullid:
1684 # is one parent an ancestor of the other?
1681 # is one parent an ancestor of the other?
1685 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1682 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1686 if fparent1 in fparentancestors:
1683 if fparent1 in fparentancestors:
1687 fparent1, fparent2 = fparent2, nullid
1684 fparent1, fparent2 = fparent2, nullid
1688 elif fparent2 in fparentancestors:
1685 elif fparent2 in fparentancestors:
1689 fparent2 = nullid
1686 fparent2 = nullid
1690
1687
1691 # is the file changed?
1688 # is the file changed?
1692 text = fctx.data()
1689 text = fctx.data()
1693 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1690 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1694 changelist.append(fname)
1691 changelist.append(fname)
1695 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1692 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1696 # are just the flags changed during merge?
1693 # are just the flags changed during merge?
1697 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1694 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1698 changelist.append(fname)
1695 changelist.append(fname)
1699
1696
1700 return fparent1
1697 return fparent1
1701
1698
1702 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1699 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1703 """check for commit arguments that aren't committable"""
1700 """check for commit arguments that aren't committable"""
1704 if match.isexact() or match.prefix():
1701 if match.isexact() or match.prefix():
1705 matched = set(status.modified + status.added + status.removed)
1702 matched = set(status.modified + status.added + status.removed)
1706
1703
1707 for f in match.files():
1704 for f in match.files():
1708 f = self.dirstate.normalize(f)
1705 f = self.dirstate.normalize(f)
1709 if f == '.' or f in matched or f in wctx.substate:
1706 if f == '.' or f in matched or f in wctx.substate:
1710 continue
1707 continue
1711 if f in status.deleted:
1708 if f in status.deleted:
1712 fail(f, _('file not found!'))
1709 fail(f, _('file not found!'))
1713 if f in vdirs: # visited directory
1710 if f in vdirs: # visited directory
1714 d = f + '/'
1711 d = f + '/'
1715 for mf in matched:
1712 for mf in matched:
1716 if mf.startswith(d):
1713 if mf.startswith(d):
1717 break
1714 break
1718 else:
1715 else:
1719 fail(f, _("no match under directory!"))
1716 fail(f, _("no match under directory!"))
1720 elif f not in self.dirstate:
1717 elif f not in self.dirstate:
1721 fail(f, _("file not tracked!"))
1718 fail(f, _("file not tracked!"))
1722
1719
1723 @unfilteredmethod
1720 @unfilteredmethod
1724 def commit(self, text="", user=None, date=None, match=None, force=False,
1721 def commit(self, text="", user=None, date=None, match=None, force=False,
1725 editor=False, extra=None):
1722 editor=False, extra=None):
1726 """Add a new revision to current repository.
1723 """Add a new revision to current repository.
1727
1724
1728 Revision information is gathered from the working directory,
1725 Revision information is gathered from the working directory,
1729 match can be used to filter the committed files. If editor is
1726 match can be used to filter the committed files. If editor is
1730 supplied, it is called to get a commit message.
1727 supplied, it is called to get a commit message.
1731 """
1728 """
1732 if extra is None:
1729 if extra is None:
1733 extra = {}
1730 extra = {}
1734
1731
1735 def fail(f, msg):
1732 def fail(f, msg):
1736 raise error.Abort('%s: %s' % (f, msg))
1733 raise error.Abort('%s: %s' % (f, msg))
1737
1734
1738 if not match:
1735 if not match:
1739 match = matchmod.always(self.root, '')
1736 match = matchmod.always(self.root, '')
1740
1737
1741 if not force:
1738 if not force:
1742 vdirs = []
1739 vdirs = []
1743 match.explicitdir = vdirs.append
1740 match.explicitdir = vdirs.append
1744 match.bad = fail
1741 match.bad = fail
1745
1742
1746 wlock = lock = tr = None
1743 wlock = lock = tr = None
1747 try:
1744 try:
1748 wlock = self.wlock()
1745 wlock = self.wlock()
1749 lock = self.lock() # for recent changelog (see issue4368)
1746 lock = self.lock() # for recent changelog (see issue4368)
1750
1747
1751 wctx = self[None]
1748 wctx = self[None]
1752 merge = len(wctx.parents()) > 1
1749 merge = len(wctx.parents()) > 1
1753
1750
1754 if not force and merge and not match.always():
1751 if not force and merge and not match.always():
1755 raise error.Abort(_('cannot partially commit a merge '
1752 raise error.Abort(_('cannot partially commit a merge '
1756 '(do not specify files or patterns)'))
1753 '(do not specify files or patterns)'))
1757
1754
1758 status = self.status(match=match, clean=force)
1755 status = self.status(match=match, clean=force)
1759 if force:
1756 if force:
1760 status.modified.extend(status.clean) # mq may commit clean files
1757 status.modified.extend(status.clean) # mq may commit clean files
1761
1758
1762 # check subrepos
1759 # check subrepos
1763 subs = []
1760 subs = []
1764 commitsubs = set()
1761 commitsubs = set()
1765 newstate = wctx.substate.copy()
1762 newstate = wctx.substate.copy()
1766 # only manage subrepos and .hgsubstate if .hgsub is present
1763 # only manage subrepos and .hgsubstate if .hgsub is present
1767 if '.hgsub' in wctx:
1764 if '.hgsub' in wctx:
1768 # we'll decide whether to track this ourselves, thanks
1765 # we'll decide whether to track this ourselves, thanks
1769 for c in status.modified, status.added, status.removed:
1766 for c in status.modified, status.added, status.removed:
1770 if '.hgsubstate' in c:
1767 if '.hgsubstate' in c:
1771 c.remove('.hgsubstate')
1768 c.remove('.hgsubstate')
1772
1769
1773 # compare current state to last committed state
1770 # compare current state to last committed state
1774 # build new substate based on last committed state
1771 # build new substate based on last committed state
1775 oldstate = wctx.p1().substate
1772 oldstate = wctx.p1().substate
1776 for s in sorted(newstate.keys()):
1773 for s in sorted(newstate.keys()):
1777 if not match(s):
1774 if not match(s):
1778 # ignore working copy, use old state if present
1775 # ignore working copy, use old state if present
1779 if s in oldstate:
1776 if s in oldstate:
1780 newstate[s] = oldstate[s]
1777 newstate[s] = oldstate[s]
1781 continue
1778 continue
1782 if not force:
1779 if not force:
1783 raise error.Abort(
1780 raise error.Abort(
1784 _("commit with new subrepo %s excluded") % s)
1781 _("commit with new subrepo %s excluded") % s)
1785 dirtyreason = wctx.sub(s).dirtyreason(True)
1782 dirtyreason = wctx.sub(s).dirtyreason(True)
1786 if dirtyreason:
1783 if dirtyreason:
1787 if not self.ui.configbool('ui', 'commitsubrepos'):
1784 if not self.ui.configbool('ui', 'commitsubrepos'):
1788 raise error.Abort(dirtyreason,
1785 raise error.Abort(dirtyreason,
1789 hint=_("use --subrepos for recursive commit"))
1786 hint=_("use --subrepos for recursive commit"))
1790 subs.append(s)
1787 subs.append(s)
1791 commitsubs.add(s)
1788 commitsubs.add(s)
1792 else:
1789 else:
1793 bs = wctx.sub(s).basestate()
1790 bs = wctx.sub(s).basestate()
1794 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1791 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1795 if oldstate.get(s, (None, None, None))[1] != bs:
1792 if oldstate.get(s, (None, None, None))[1] != bs:
1796 subs.append(s)
1793 subs.append(s)
1797
1794
1798 # check for removed subrepos
1795 # check for removed subrepos
1799 for p in wctx.parents():
1796 for p in wctx.parents():
1800 r = [s for s in p.substate if s not in newstate]
1797 r = [s for s in p.substate if s not in newstate]
1801 subs += [s for s in r if match(s)]
1798 subs += [s for s in r if match(s)]
1802 if subs:
1799 if subs:
1803 if (not match('.hgsub') and
1800 if (not match('.hgsub') and
1804 '.hgsub' in (wctx.modified() + wctx.added())):
1801 '.hgsub' in (wctx.modified() + wctx.added())):
1805 raise error.Abort(
1802 raise error.Abort(
1806 _("can't commit subrepos without .hgsub"))
1803 _("can't commit subrepos without .hgsub"))
1807 status.modified.insert(0, '.hgsubstate')
1804 status.modified.insert(0, '.hgsubstate')
1808
1805
1809 elif '.hgsub' in status.removed:
1806 elif '.hgsub' in status.removed:
1810 # clean up .hgsubstate when .hgsub is removed
1807 # clean up .hgsubstate when .hgsub is removed
1811 if ('.hgsubstate' in wctx and
1808 if ('.hgsubstate' in wctx and
1812 '.hgsubstate' not in (status.modified + status.added +
1809 '.hgsubstate' not in (status.modified + status.added +
1813 status.removed)):
1810 status.removed)):
1814 status.removed.insert(0, '.hgsubstate')
1811 status.removed.insert(0, '.hgsubstate')
1815
1812
1816 # make sure all explicit patterns are matched
1813 # make sure all explicit patterns are matched
1817 if not force:
1814 if not force:
1818 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1815 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1819
1816
1820 cctx = context.workingcommitctx(self, status,
1817 cctx = context.workingcommitctx(self, status,
1821 text, user, date, extra)
1818 text, user, date, extra)
1822
1819
1823 # internal config: ui.allowemptycommit
1820 # internal config: ui.allowemptycommit
1824 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1821 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1825 or extra.get('close') or merge or cctx.files()
1822 or extra.get('close') or merge or cctx.files()
1826 or self.ui.configbool('ui', 'allowemptycommit'))
1823 or self.ui.configbool('ui', 'allowemptycommit'))
1827 if not allowemptycommit:
1824 if not allowemptycommit:
1828 return None
1825 return None
1829
1826
1830 if merge and cctx.deleted():
1827 if merge and cctx.deleted():
1831 raise error.Abort(_("cannot commit merge with missing files"))
1828 raise error.Abort(_("cannot commit merge with missing files"))
1832
1829
1833 ms = mergemod.mergestate.read(self)
1830 ms = mergemod.mergestate.read(self)
1834 mergeutil.checkunresolved(ms)
1831 mergeutil.checkunresolved(ms)
1835
1832
1836 if editor:
1833 if editor:
1837 cctx._text = editor(self, cctx, subs)
1834 cctx._text = editor(self, cctx, subs)
1838 edited = (text != cctx._text)
1835 edited = (text != cctx._text)
1839
1836
1840 # Save commit message in case this transaction gets rolled back
1837 # Save commit message in case this transaction gets rolled back
1841 # (e.g. by a pretxncommit hook). Leave the content alone on
1838 # (e.g. by a pretxncommit hook). Leave the content alone on
1842 # the assumption that the user will use the same editor again.
1839 # the assumption that the user will use the same editor again.
1843 msgfn = self.savecommitmessage(cctx._text)
1840 msgfn = self.savecommitmessage(cctx._text)
1844
1841
1845 # commit subs and write new state
1842 # commit subs and write new state
1846 if subs:
1843 if subs:
1847 for s in sorted(commitsubs):
1844 for s in sorted(commitsubs):
1848 sub = wctx.sub(s)
1845 sub = wctx.sub(s)
1849 self.ui.status(_('committing subrepository %s\n') %
1846 self.ui.status(_('committing subrepository %s\n') %
1850 subrepo.subrelpath(sub))
1847 subrepo.subrelpath(sub))
1851 sr = sub.commit(cctx._text, user, date)
1848 sr = sub.commit(cctx._text, user, date)
1852 newstate[s] = (newstate[s][0], sr)
1849 newstate[s] = (newstate[s][0], sr)
1853 subrepo.writestate(self, newstate)
1850 subrepo.writestate(self, newstate)
1854
1851
1855 p1, p2 = self.dirstate.parents()
1852 p1, p2 = self.dirstate.parents()
1856 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1853 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1857 try:
1854 try:
1858 self.hook("precommit", throw=True, parent1=hookp1,
1855 self.hook("precommit", throw=True, parent1=hookp1,
1859 parent2=hookp2)
1856 parent2=hookp2)
1860 tr = self.transaction('commit')
1857 tr = self.transaction('commit')
1861 ret = self.commitctx(cctx, True)
1858 ret = self.commitctx(cctx, True)
1862 except: # re-raises
1859 except: # re-raises
1863 if edited:
1860 if edited:
1864 self.ui.write(
1861 self.ui.write(
1865 _('note: commit message saved in %s\n') % msgfn)
1862 _('note: commit message saved in %s\n') % msgfn)
1866 raise
1863 raise
1867 # update bookmarks, dirstate and mergestate
1864 # update bookmarks, dirstate and mergestate
1868 bookmarks.update(self, [p1, p2], ret)
1865 bookmarks.update(self, [p1, p2], ret)
1869 cctx.markcommitted(ret)
1866 cctx.markcommitted(ret)
1870 ms.reset()
1867 ms.reset()
1871 tr.close()
1868 tr.close()
1872
1869
1873 finally:
1870 finally:
1874 lockmod.release(tr, lock, wlock)
1871 lockmod.release(tr, lock, wlock)
1875
1872
1876 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1873 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1877 # hack for command that use a temporary commit (eg: histedit)
1874 # hack for command that use a temporary commit (eg: histedit)
1878 # temporary commit got stripped before hook release
1875 # temporary commit got stripped before hook release
1879 if self.changelog.hasnode(ret):
1876 if self.changelog.hasnode(ret):
1880 self.hook("commit", node=node, parent1=parent1,
1877 self.hook("commit", node=node, parent1=parent1,
1881 parent2=parent2)
1878 parent2=parent2)
1882 self._afterlock(commithook)
1879 self._afterlock(commithook)
1883 return ret
1880 return ret
1884
1881
1885 @unfilteredmethod
1882 @unfilteredmethod
1886 def commitctx(self, ctx, error=False):
1883 def commitctx(self, ctx, error=False):
1887 """Add a new revision to current repository.
1884 """Add a new revision to current repository.
1888 Revision information is passed via the context argument.
1885 Revision information is passed via the context argument.
1889 """
1886 """
1890
1887
1891 tr = None
1888 tr = None
1892 p1, p2 = ctx.p1(), ctx.p2()
1889 p1, p2 = ctx.p1(), ctx.p2()
1893 user = ctx.user()
1890 user = ctx.user()
1894
1891
1895 lock = self.lock()
1892 lock = self.lock()
1896 try:
1893 try:
1897 tr = self.transaction("commit")
1894 tr = self.transaction("commit")
1898 trp = weakref.proxy(tr)
1895 trp = weakref.proxy(tr)
1899
1896
1900 if ctx.manifestnode():
1897 if ctx.manifestnode():
1901 # reuse an existing manifest revision
1898 # reuse an existing manifest revision
1902 mn = ctx.manifestnode()
1899 mn = ctx.manifestnode()
1903 files = ctx.files()
1900 files = ctx.files()
1904 elif ctx.files():
1901 elif ctx.files():
1905 m1ctx = p1.manifestctx()
1902 m1ctx = p1.manifestctx()
1906 m2ctx = p2.manifestctx()
1903 m2ctx = p2.manifestctx()
1907 mctx = m1ctx.copy()
1904 mctx = m1ctx.copy()
1908
1905
1909 m = mctx.read()
1906 m = mctx.read()
1910 m1 = m1ctx.read()
1907 m1 = m1ctx.read()
1911 m2 = m2ctx.read()
1908 m2 = m2ctx.read()
1912
1909
1913 # check in files
1910 # check in files
1914 added = []
1911 added = []
1915 changed = []
1912 changed = []
1916 removed = list(ctx.removed())
1913 removed = list(ctx.removed())
1917 linkrev = len(self)
1914 linkrev = len(self)
1918 self.ui.note(_("committing files:\n"))
1915 self.ui.note(_("committing files:\n"))
1919 for f in sorted(ctx.modified() + ctx.added()):
1916 for f in sorted(ctx.modified() + ctx.added()):
1920 self.ui.note(f + "\n")
1917 self.ui.note(f + "\n")
1921 try:
1918 try:
1922 fctx = ctx[f]
1919 fctx = ctx[f]
1923 if fctx is None:
1920 if fctx is None:
1924 removed.append(f)
1921 removed.append(f)
1925 else:
1922 else:
1926 added.append(f)
1923 added.append(f)
1927 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1924 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1928 trp, changed)
1925 trp, changed)
1929 m.setflag(f, fctx.flags())
1926 m.setflag(f, fctx.flags())
1930 except OSError as inst:
1927 except OSError as inst:
1931 self.ui.warn(_("trouble committing %s!\n") % f)
1928 self.ui.warn(_("trouble committing %s!\n") % f)
1932 raise
1929 raise
1933 except IOError as inst:
1930 except IOError as inst:
1934 errcode = getattr(inst, 'errno', errno.ENOENT)
1931 errcode = getattr(inst, 'errno', errno.ENOENT)
1935 if error or errcode and errcode != errno.ENOENT:
1932 if error or errcode and errcode != errno.ENOENT:
1936 self.ui.warn(_("trouble committing %s!\n") % f)
1933 self.ui.warn(_("trouble committing %s!\n") % f)
1937 raise
1934 raise
1938
1935
1939 # update manifest
1936 # update manifest
1940 self.ui.note(_("committing manifest\n"))
1937 self.ui.note(_("committing manifest\n"))
1941 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1938 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1942 drop = [f for f in removed if f in m]
1939 drop = [f for f in removed if f in m]
1943 for f in drop:
1940 for f in drop:
1944 del m[f]
1941 del m[f]
1945 mn = mctx.write(trp, linkrev,
1942 mn = mctx.write(trp, linkrev,
1946 p1.manifestnode(), p2.manifestnode(),
1943 p1.manifestnode(), p2.manifestnode(),
1947 added, drop)
1944 added, drop)
1948 files = changed + removed
1945 files = changed + removed
1949 else:
1946 else:
1950 mn = p1.manifestnode()
1947 mn = p1.manifestnode()
1951 files = []
1948 files = []
1952
1949
1953 # update changelog
1950 # update changelog
1954 self.ui.note(_("committing changelog\n"))
1951 self.ui.note(_("committing changelog\n"))
1955 self.changelog.delayupdate(tr)
1952 self.changelog.delayupdate(tr)
1956 n = self.changelog.add(mn, files, ctx.description(),
1953 n = self.changelog.add(mn, files, ctx.description(),
1957 trp, p1.node(), p2.node(),
1954 trp, p1.node(), p2.node(),
1958 user, ctx.date(), ctx.extra().copy())
1955 user, ctx.date(), ctx.extra().copy())
1959 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1956 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1960 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1957 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1961 parent2=xp2)
1958 parent2=xp2)
1962 # set the new commit is proper phase
1959 # set the new commit is proper phase
1963 targetphase = subrepo.newcommitphase(self.ui, ctx)
1960 targetphase = subrepo.newcommitphase(self.ui, ctx)
1964 if targetphase:
1961 if targetphase:
1965 # retract boundary do not alter parent changeset.
1962 # retract boundary do not alter parent changeset.
1966 # if a parent have higher the resulting phase will
1963 # if a parent have higher the resulting phase will
1967 # be compliant anyway
1964 # be compliant anyway
1968 #
1965 #
1969 # if minimal phase was 0 we don't need to retract anything
1966 # if minimal phase was 0 we don't need to retract anything
1970 phases.registernew(self, tr, targetphase, [n])
1967 phases.registernew(self, tr, targetphase, [n])
1971 tr.close()
1968 tr.close()
1972 return n
1969 return n
1973 finally:
1970 finally:
1974 if tr:
1971 if tr:
1975 tr.release()
1972 tr.release()
1976 lock.release()
1973 lock.release()
1977
1974
1978 @unfilteredmethod
1975 @unfilteredmethod
1979 def destroying(self):
1976 def destroying(self):
1980 '''Inform the repository that nodes are about to be destroyed.
1977 '''Inform the repository that nodes are about to be destroyed.
1981 Intended for use by strip and rollback, so there's a common
1978 Intended for use by strip and rollback, so there's a common
1982 place for anything that has to be done before destroying history.
1979 place for anything that has to be done before destroying history.
1983
1980
1984 This is mostly useful for saving state that is in memory and waiting
1981 This is mostly useful for saving state that is in memory and waiting
1985 to be flushed when the current lock is released. Because a call to
1982 to be flushed when the current lock is released. Because a call to
1986 destroyed is imminent, the repo will be invalidated causing those
1983 destroyed is imminent, the repo will be invalidated causing those
1987 changes to stay in memory (waiting for the next unlock), or vanish
1984 changes to stay in memory (waiting for the next unlock), or vanish
1988 completely.
1985 completely.
1989 '''
1986 '''
1990 # When using the same lock to commit and strip, the phasecache is left
1987 # When using the same lock to commit and strip, the phasecache is left
1991 # dirty after committing. Then when we strip, the repo is invalidated,
1988 # dirty after committing. Then when we strip, the repo is invalidated,
1992 # causing those changes to disappear.
1989 # causing those changes to disappear.
1993 if '_phasecache' in vars(self):
1990 if '_phasecache' in vars(self):
1994 self._phasecache.write()
1991 self._phasecache.write()
1995
1992
1996 @unfilteredmethod
1993 @unfilteredmethod
1997 def destroyed(self):
1994 def destroyed(self):
1998 '''Inform the repository that nodes have been destroyed.
1995 '''Inform the repository that nodes have been destroyed.
1999 Intended for use by strip and rollback, so there's a common
1996 Intended for use by strip and rollback, so there's a common
2000 place for anything that has to be done after destroying history.
1997 place for anything that has to be done after destroying history.
2001 '''
1998 '''
2002 # When one tries to:
1999 # When one tries to:
2003 # 1) destroy nodes thus calling this method (e.g. strip)
2000 # 1) destroy nodes thus calling this method (e.g. strip)
2004 # 2) use phasecache somewhere (e.g. commit)
2001 # 2) use phasecache somewhere (e.g. commit)
2005 #
2002 #
2006 # then 2) will fail because the phasecache contains nodes that were
2003 # then 2) will fail because the phasecache contains nodes that were
2007 # removed. We can either remove phasecache from the filecache,
2004 # removed. We can either remove phasecache from the filecache,
2008 # causing it to reload next time it is accessed, or simply filter
2005 # causing it to reload next time it is accessed, or simply filter
2009 # the removed nodes now and write the updated cache.
2006 # the removed nodes now and write the updated cache.
2010 self._phasecache.filterunknown(self)
2007 self._phasecache.filterunknown(self)
2011 self._phasecache.write()
2008 self._phasecache.write()
2012
2009
2013 # refresh all repository caches
2010 # refresh all repository caches
2014 self.updatecaches()
2011 self.updatecaches()
2015
2012
2016 # Ensure the persistent tag cache is updated. Doing it now
2013 # Ensure the persistent tag cache is updated. Doing it now
2017 # means that the tag cache only has to worry about destroyed
2014 # means that the tag cache only has to worry about destroyed
2018 # heads immediately after a strip/rollback. That in turn
2015 # heads immediately after a strip/rollback. That in turn
2019 # guarantees that "cachetip == currenttip" (comparing both rev
2016 # guarantees that "cachetip == currenttip" (comparing both rev
2020 # and node) always means no nodes have been added or destroyed.
2017 # and node) always means no nodes have been added or destroyed.
2021
2018
2022 # XXX this is suboptimal when qrefresh'ing: we strip the current
2019 # XXX this is suboptimal when qrefresh'ing: we strip the current
2023 # head, refresh the tag cache, then immediately add a new head.
2020 # head, refresh the tag cache, then immediately add a new head.
2024 # But I think doing it this way is necessary for the "instant
2021 # But I think doing it this way is necessary for the "instant
2025 # tag cache retrieval" case to work.
2022 # tag cache retrieval" case to work.
2026 self.invalidate()
2023 self.invalidate()
2027
2024
2028 def walk(self, match, node=None):
2025 def walk(self, match, node=None):
2029 '''
2026 '''
2030 walk recursively through the directory tree or a given
2027 walk recursively through the directory tree or a given
2031 changeset, finding all files matched by the match
2028 changeset, finding all files matched by the match
2032 function
2029 function
2033 '''
2030 '''
2034 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2031 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2035 return self[node].walk(match)
2032 return self[node].walk(match)
2036
2033
2037 def status(self, node1='.', node2=None, match=None,
2034 def status(self, node1='.', node2=None, match=None,
2038 ignored=False, clean=False, unknown=False,
2035 ignored=False, clean=False, unknown=False,
2039 listsubrepos=False):
2036 listsubrepos=False):
2040 '''a convenience method that calls node1.status(node2)'''
2037 '''a convenience method that calls node1.status(node2)'''
2041 return self[node1].status(node2, match, ignored, clean, unknown,
2038 return self[node1].status(node2, match, ignored, clean, unknown,
2042 listsubrepos)
2039 listsubrepos)
2043
2040
2044 def addpostdsstatus(self, ps):
2041 def addpostdsstatus(self, ps):
2045 """Add a callback to run within the wlock, at the point at which status
2042 """Add a callback to run within the wlock, at the point at which status
2046 fixups happen.
2043 fixups happen.
2047
2044
2048 On status completion, callback(wctx, status) will be called with the
2045 On status completion, callback(wctx, status) will be called with the
2049 wlock held, unless the dirstate has changed from underneath or the wlock
2046 wlock held, unless the dirstate has changed from underneath or the wlock
2050 couldn't be grabbed.
2047 couldn't be grabbed.
2051
2048
2052 Callbacks should not capture and use a cached copy of the dirstate --
2049 Callbacks should not capture and use a cached copy of the dirstate --
2053 it might change in the meanwhile. Instead, they should access the
2050 it might change in the meanwhile. Instead, they should access the
2054 dirstate via wctx.repo().dirstate.
2051 dirstate via wctx.repo().dirstate.
2055
2052
2056 This list is emptied out after each status run -- extensions should
2053 This list is emptied out after each status run -- extensions should
2057 make sure it adds to this list each time dirstate.status is called.
2054 make sure it adds to this list each time dirstate.status is called.
2058 Extensions should also make sure they don't call this for statuses
2055 Extensions should also make sure they don't call this for statuses
2059 that don't involve the dirstate.
2056 that don't involve the dirstate.
2060 """
2057 """
2061
2058
2062 # The list is located here for uniqueness reasons -- it is actually
2059 # The list is located here for uniqueness reasons -- it is actually
2063 # managed by the workingctx, but that isn't unique per-repo.
2060 # managed by the workingctx, but that isn't unique per-repo.
2064 self._postdsstatus.append(ps)
2061 self._postdsstatus.append(ps)
2065
2062
2066 def postdsstatus(self):
2063 def postdsstatus(self):
2067 """Used by workingctx to get the list of post-dirstate-status hooks."""
2064 """Used by workingctx to get the list of post-dirstate-status hooks."""
2068 return self._postdsstatus
2065 return self._postdsstatus
2069
2066
2070 def clearpostdsstatus(self):
2067 def clearpostdsstatus(self):
2071 """Used by workingctx to clear post-dirstate-status hooks."""
2068 """Used by workingctx to clear post-dirstate-status hooks."""
2072 del self._postdsstatus[:]
2069 del self._postdsstatus[:]
2073
2070
2074 def heads(self, start=None):
2071 def heads(self, start=None):
2075 if start is None:
2072 if start is None:
2076 cl = self.changelog
2073 cl = self.changelog
2077 headrevs = reversed(cl.headrevs())
2074 headrevs = reversed(cl.headrevs())
2078 return [cl.node(rev) for rev in headrevs]
2075 return [cl.node(rev) for rev in headrevs]
2079
2076
2080 heads = self.changelog.heads(start)
2077 heads = self.changelog.heads(start)
2081 # sort the output in rev descending order
2078 # sort the output in rev descending order
2082 return sorted(heads, key=self.changelog.rev, reverse=True)
2079 return sorted(heads, key=self.changelog.rev, reverse=True)
2083
2080
2084 def branchheads(self, branch=None, start=None, closed=False):
2081 def branchheads(self, branch=None, start=None, closed=False):
2085 '''return a (possibly filtered) list of heads for the given branch
2082 '''return a (possibly filtered) list of heads for the given branch
2086
2083
2087 Heads are returned in topological order, from newest to oldest.
2084 Heads are returned in topological order, from newest to oldest.
2088 If branch is None, use the dirstate branch.
2085 If branch is None, use the dirstate branch.
2089 If start is not None, return only heads reachable from start.
2086 If start is not None, return only heads reachable from start.
2090 If closed is True, return heads that are marked as closed as well.
2087 If closed is True, return heads that are marked as closed as well.
2091 '''
2088 '''
2092 if branch is None:
2089 if branch is None:
2093 branch = self[None].branch()
2090 branch = self[None].branch()
2094 branches = self.branchmap()
2091 branches = self.branchmap()
2095 if branch not in branches:
2092 if branch not in branches:
2096 return []
2093 return []
2097 # the cache returns heads ordered lowest to highest
2094 # the cache returns heads ordered lowest to highest
2098 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2095 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2099 if start is not None:
2096 if start is not None:
2100 # filter out the heads that cannot be reached from startrev
2097 # filter out the heads that cannot be reached from startrev
2101 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2098 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2102 bheads = [h for h in bheads if h in fbheads]
2099 bheads = [h for h in bheads if h in fbheads]
2103 return bheads
2100 return bheads
2104
2101
2105 def branches(self, nodes):
2102 def branches(self, nodes):
2106 if not nodes:
2103 if not nodes:
2107 nodes = [self.changelog.tip()]
2104 nodes = [self.changelog.tip()]
2108 b = []
2105 b = []
2109 for n in nodes:
2106 for n in nodes:
2110 t = n
2107 t = n
2111 while True:
2108 while True:
2112 p = self.changelog.parents(n)
2109 p = self.changelog.parents(n)
2113 if p[1] != nullid or p[0] == nullid:
2110 if p[1] != nullid or p[0] == nullid:
2114 b.append((t, n, p[0], p[1]))
2111 b.append((t, n, p[0], p[1]))
2115 break
2112 break
2116 n = p[0]
2113 n = p[0]
2117 return b
2114 return b
2118
2115
2119 def between(self, pairs):
2116 def between(self, pairs):
2120 r = []
2117 r = []
2121
2118
2122 for top, bottom in pairs:
2119 for top, bottom in pairs:
2123 n, l, i = top, [], 0
2120 n, l, i = top, [], 0
2124 f = 1
2121 f = 1
2125
2122
2126 while n != bottom and n != nullid:
2123 while n != bottom and n != nullid:
2127 p = self.changelog.parents(n)[0]
2124 p = self.changelog.parents(n)[0]
2128 if i == f:
2125 if i == f:
2129 l.append(n)
2126 l.append(n)
2130 f = f * 2
2127 f = f * 2
2131 n = p
2128 n = p
2132 i += 1
2129 i += 1
2133
2130
2134 r.append(l)
2131 r.append(l)
2135
2132
2136 return r
2133 return r
2137
2134
2138 def checkpush(self, pushop):
2135 def checkpush(self, pushop):
2139 """Extensions can override this function if additional checks have
2136 """Extensions can override this function if additional checks have
2140 to be performed before pushing, or call it if they override push
2137 to be performed before pushing, or call it if they override push
2141 command.
2138 command.
2142 """
2139 """
2143 pass
2140 pass
2144
2141
2145 @unfilteredpropertycache
2142 @unfilteredpropertycache
2146 def prepushoutgoinghooks(self):
2143 def prepushoutgoinghooks(self):
2147 """Return util.hooks consists of a pushop with repo, remote, outgoing
2144 """Return util.hooks consists of a pushop with repo, remote, outgoing
2148 methods, which are called before pushing changesets.
2145 methods, which are called before pushing changesets.
2149 """
2146 """
2150 return util.hooks()
2147 return util.hooks()
2151
2148
2152 def pushkey(self, namespace, key, old, new):
2149 def pushkey(self, namespace, key, old, new):
2153 try:
2150 try:
2154 tr = self.currenttransaction()
2151 tr = self.currenttransaction()
2155 hookargs = {}
2152 hookargs = {}
2156 if tr is not None:
2153 if tr is not None:
2157 hookargs.update(tr.hookargs)
2154 hookargs.update(tr.hookargs)
2158 hookargs['namespace'] = namespace
2155 hookargs['namespace'] = namespace
2159 hookargs['key'] = key
2156 hookargs['key'] = key
2160 hookargs['old'] = old
2157 hookargs['old'] = old
2161 hookargs['new'] = new
2158 hookargs['new'] = new
2162 self.hook('prepushkey', throw=True, **hookargs)
2159 self.hook('prepushkey', throw=True, **hookargs)
2163 except error.HookAbort as exc:
2160 except error.HookAbort as exc:
2164 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2161 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2165 if exc.hint:
2162 if exc.hint:
2166 self.ui.write_err(_("(%s)\n") % exc.hint)
2163 self.ui.write_err(_("(%s)\n") % exc.hint)
2167 return False
2164 return False
2168 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2165 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2169 ret = pushkey.push(self, namespace, key, old, new)
2166 ret = pushkey.push(self, namespace, key, old, new)
2170 def runhook():
2167 def runhook():
2171 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2168 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2172 ret=ret)
2169 ret=ret)
2173 self._afterlock(runhook)
2170 self._afterlock(runhook)
2174 return ret
2171 return ret
2175
2172
2176 def listkeys(self, namespace):
2173 def listkeys(self, namespace):
2177 self.hook('prelistkeys', throw=True, namespace=namespace)
2174 self.hook('prelistkeys', throw=True, namespace=namespace)
2178 self.ui.debug('listing keys for "%s"\n' % namespace)
2175 self.ui.debug('listing keys for "%s"\n' % namespace)
2179 values = pushkey.list(self, namespace)
2176 values = pushkey.list(self, namespace)
2180 self.hook('listkeys', namespace=namespace, values=values)
2177 self.hook('listkeys', namespace=namespace, values=values)
2181 return values
2178 return values
2182
2179
2183 def debugwireargs(self, one, two, three=None, four=None, five=None):
2180 def debugwireargs(self, one, two, three=None, four=None, five=None):
2184 '''used to test argument passing over the wire'''
2181 '''used to test argument passing over the wire'''
2185 return "%s %s %s %s %s" % (one, two, three, four, five)
2182 return "%s %s %s %s %s" % (one, two, three, four, five)
2186
2183
2187 def savecommitmessage(self, text):
2184 def savecommitmessage(self, text):
2188 fp = self.vfs('last-message.txt', 'wb')
2185 fp = self.vfs('last-message.txt', 'wb')
2189 try:
2186 try:
2190 fp.write(text)
2187 fp.write(text)
2191 finally:
2188 finally:
2192 fp.close()
2189 fp.close()
2193 return self.pathto(fp.name[len(self.root) + 1:])
2190 return self.pathto(fp.name[len(self.root) + 1:])
2194
2191
2195 # used to avoid circular references so destructors work
2192 # used to avoid circular references so destructors work
2196 def aftertrans(files):
2193 def aftertrans(files):
2197 renamefiles = [tuple(t) for t in files]
2194 renamefiles = [tuple(t) for t in files]
2198 def a():
2195 def a():
2199 for vfs, src, dest in renamefiles:
2196 for vfs, src, dest in renamefiles:
2200 # if src and dest refer to a same file, vfs.rename is a no-op,
2197 # if src and dest refer to a same file, vfs.rename is a no-op,
2201 # leaving both src and dest on disk. delete dest to make sure
2198 # leaving both src and dest on disk. delete dest to make sure
2202 # the rename couldn't be such a no-op.
2199 # the rename couldn't be such a no-op.
2203 vfs.tryunlink(dest)
2200 vfs.tryunlink(dest)
2204 try:
2201 try:
2205 vfs.rename(src, dest)
2202 vfs.rename(src, dest)
2206 except OSError: # journal file does not yet exist
2203 except OSError: # journal file does not yet exist
2207 pass
2204 pass
2208 return a
2205 return a
2209
2206
2210 def undoname(fn):
2207 def undoname(fn):
2211 base, name = os.path.split(fn)
2208 base, name = os.path.split(fn)
2212 assert name.startswith('journal')
2209 assert name.startswith('journal')
2213 return os.path.join(base, name.replace('journal', 'undo', 1))
2210 return os.path.join(base, name.replace('journal', 'undo', 1))
2214
2211
2215 def instance(ui, path, create):
2212 def instance(ui, path, create):
2216 return localrepository(ui, util.urllocalpath(path), create)
2213 return localrepository(ui, util.urllocalpath(path), create)
2217
2214
2218 def islocal(path):
2215 def islocal(path):
2219 return True
2216 return True
2220
2217
2221 def newreporequirements(repo):
2218 def newreporequirements(repo):
2222 """Determine the set of requirements for a new local repository.
2219 """Determine the set of requirements for a new local repository.
2223
2220
2224 Extensions can wrap this function to specify custom requirements for
2221 Extensions can wrap this function to specify custom requirements for
2225 new repositories.
2222 new repositories.
2226 """
2223 """
2227 ui = repo.ui
2224 ui = repo.ui
2228 requirements = {'revlogv1'}
2225 requirements = {'revlogv1'}
2229 if ui.configbool('format', 'usestore'):
2226 if ui.configbool('format', 'usestore'):
2230 requirements.add('store')
2227 requirements.add('store')
2231 if ui.configbool('format', 'usefncache'):
2228 if ui.configbool('format', 'usefncache'):
2232 requirements.add('fncache')
2229 requirements.add('fncache')
2233 if ui.configbool('format', 'dotencode'):
2230 if ui.configbool('format', 'dotencode'):
2234 requirements.add('dotencode')
2231 requirements.add('dotencode')
2235
2232
2236 compengine = ui.config('experimental', 'format.compression')
2233 compengine = ui.config('experimental', 'format.compression')
2237 if compengine not in util.compengines:
2234 if compengine not in util.compengines:
2238 raise error.Abort(_('compression engine %s defined by '
2235 raise error.Abort(_('compression engine %s defined by '
2239 'experimental.format.compression not available') %
2236 'experimental.format.compression not available') %
2240 compengine,
2237 compengine,
2241 hint=_('run "hg debuginstall" to list available '
2238 hint=_('run "hg debuginstall" to list available '
2242 'compression engines'))
2239 'compression engines'))
2243
2240
2244 # zlib is the historical default and doesn't need an explicit requirement.
2241 # zlib is the historical default and doesn't need an explicit requirement.
2245 if compengine != 'zlib':
2242 if compengine != 'zlib':
2246 requirements.add('exp-compression-%s' % compengine)
2243 requirements.add('exp-compression-%s' % compengine)
2247
2244
2248 if scmutil.gdinitconfig(ui):
2245 if scmutil.gdinitconfig(ui):
2249 requirements.add('generaldelta')
2246 requirements.add('generaldelta')
2250 if ui.configbool('experimental', 'treemanifest'):
2247 if ui.configbool('experimental', 'treemanifest'):
2251 requirements.add('treemanifest')
2248 requirements.add('treemanifest')
2252 if ui.configbool('experimental', 'manifestv2'):
2249 if ui.configbool('experimental', 'manifestv2'):
2253 requirements.add('manifestv2')
2250 requirements.add('manifestv2')
2254
2251
2255 revlogv2 = ui.config('experimental', 'revlogv2')
2252 revlogv2 = ui.config('experimental', 'revlogv2')
2256 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2253 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2257 requirements.remove('revlogv1')
2254 requirements.remove('revlogv1')
2258 # generaldelta is implied by revlogv2.
2255 # generaldelta is implied by revlogv2.
2259 requirements.discard('generaldelta')
2256 requirements.discard('generaldelta')
2260 requirements.add(REVLOGV2_REQUIREMENT)
2257 requirements.add(REVLOGV2_REQUIREMENT)
2261
2258
2262 return requirements
2259 return requirements
@@ -1,369 +1,325 b''
1 # sshpeer.py - ssh repository proxy class for mercurial
1 # sshpeer.py - ssh repository proxy class for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 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 error,
14 error,
15 pycompat,
15 pycompat,
16 util,
16 util,
17 wireproto,
17 wireproto,
18 )
18 )
19
19
20 class remotelock(object):
21 def __init__(self, repo):
22 self.repo = repo
23 def release(self):
24 self.repo.unlock()
25 self.repo = None
26 def __enter__(self):
27 return self
28 def __exit__(self, exc_type, exc_val, exc_tb):
29 if self.repo:
30 self.release()
31 def __del__(self):
32 if self.repo:
33 self.release()
34
35 def _serverquote(s):
20 def _serverquote(s):
36 if not s:
21 if not s:
37 return s
22 return s
38 '''quote a string for the remote shell ... which we assume is sh'''
23 '''quote a string for the remote shell ... which we assume is sh'''
39 if re.match('[a-zA-Z0-9@%_+=:,./-]*$', s):
24 if re.match('[a-zA-Z0-9@%_+=:,./-]*$', s):
40 return s
25 return s
41 return "'%s'" % s.replace("'", "'\\''")
26 return "'%s'" % s.replace("'", "'\\''")
42
27
43 def _forwardoutput(ui, pipe):
28 def _forwardoutput(ui, pipe):
44 """display all data currently available on pipe as remote output.
29 """display all data currently available on pipe as remote output.
45
30
46 This is non blocking."""
31 This is non blocking."""
47 s = util.readpipe(pipe)
32 s = util.readpipe(pipe)
48 if s:
33 if s:
49 for l in s.splitlines():
34 for l in s.splitlines():
50 ui.status(_("remote: "), l, '\n')
35 ui.status(_("remote: "), l, '\n')
51
36
52 class doublepipe(object):
37 class doublepipe(object):
53 """Operate a side-channel pipe in addition of a main one
38 """Operate a side-channel pipe in addition of a main one
54
39
55 The side-channel pipe contains server output to be forwarded to the user
40 The side-channel pipe contains server output to be forwarded to the user
56 input. The double pipe will behave as the "main" pipe, but will ensure the
41 input. The double pipe will behave as the "main" pipe, but will ensure the
57 content of the "side" pipe is properly processed while we wait for blocking
42 content of the "side" pipe is properly processed while we wait for blocking
58 call on the "main" pipe.
43 call on the "main" pipe.
59
44
60 If large amounts of data are read from "main", the forward will cease after
45 If large amounts of data are read from "main", the forward will cease after
61 the first bytes start to appear. This simplifies the implementation
46 the first bytes start to appear. This simplifies the implementation
62 without affecting actual output of sshpeer too much as we rarely issue
47 without affecting actual output of sshpeer too much as we rarely issue
63 large read for data not yet emitted by the server.
48 large read for data not yet emitted by the server.
64
49
65 The main pipe is expected to be a 'bufferedinputpipe' from the util module
50 The main pipe is expected to be a 'bufferedinputpipe' from the util module
66 that handle all the os specific bits. This class lives in this module
51 that handle all the os specific bits. This class lives in this module
67 because it focus on behavior specific to the ssh protocol."""
52 because it focus on behavior specific to the ssh protocol."""
68
53
69 def __init__(self, ui, main, side):
54 def __init__(self, ui, main, side):
70 self._ui = ui
55 self._ui = ui
71 self._main = main
56 self._main = main
72 self._side = side
57 self._side = side
73
58
74 def _wait(self):
59 def _wait(self):
75 """wait until some data are available on main or side
60 """wait until some data are available on main or side
76
61
77 return a pair of boolean (ismainready, issideready)
62 return a pair of boolean (ismainready, issideready)
78
63
79 (This will only wait for data if the setup is supported by `util.poll`)
64 (This will only wait for data if the setup is supported by `util.poll`)
80 """
65 """
81 if getattr(self._main, 'hasbuffer', False): # getattr for classic pipe
66 if getattr(self._main, 'hasbuffer', False): # getattr for classic pipe
82 return (True, True) # main has data, assume side is worth poking at.
67 return (True, True) # main has data, assume side is worth poking at.
83 fds = [self._main.fileno(), self._side.fileno()]
68 fds = [self._main.fileno(), self._side.fileno()]
84 try:
69 try:
85 act = util.poll(fds)
70 act = util.poll(fds)
86 except NotImplementedError:
71 except NotImplementedError:
87 # non supported yet case, assume all have data.
72 # non supported yet case, assume all have data.
88 act = fds
73 act = fds
89 return (self._main.fileno() in act, self._side.fileno() in act)
74 return (self._main.fileno() in act, self._side.fileno() in act)
90
75
91 def write(self, data):
76 def write(self, data):
92 return self._call('write', data)
77 return self._call('write', data)
93
78
94 def read(self, size):
79 def read(self, size):
95 r = self._call('read', size)
80 r = self._call('read', size)
96 if size != 0 and not r:
81 if size != 0 and not r:
97 # We've observed a condition that indicates the
82 # We've observed a condition that indicates the
98 # stdout closed unexpectedly. Check stderr one
83 # stdout closed unexpectedly. Check stderr one
99 # more time and snag anything that's there before
84 # more time and snag anything that's there before
100 # letting anyone know the main part of the pipe
85 # letting anyone know the main part of the pipe
101 # closed prematurely.
86 # closed prematurely.
102 _forwardoutput(self._ui, self._side)
87 _forwardoutput(self._ui, self._side)
103 return r
88 return r
104
89
105 def readline(self):
90 def readline(self):
106 return self._call('readline')
91 return self._call('readline')
107
92
108 def _call(self, methname, data=None):
93 def _call(self, methname, data=None):
109 """call <methname> on "main", forward output of "side" while blocking
94 """call <methname> on "main", forward output of "side" while blocking
110 """
95 """
111 # data can be '' or 0
96 # data can be '' or 0
112 if (data is not None and not data) or self._main.closed:
97 if (data is not None and not data) or self._main.closed:
113 _forwardoutput(self._ui, self._side)
98 _forwardoutput(self._ui, self._side)
114 return ''
99 return ''
115 while True:
100 while True:
116 mainready, sideready = self._wait()
101 mainready, sideready = self._wait()
117 if sideready:
102 if sideready:
118 _forwardoutput(self._ui, self._side)
103 _forwardoutput(self._ui, self._side)
119 if mainready:
104 if mainready:
120 meth = getattr(self._main, methname)
105 meth = getattr(self._main, methname)
121 if data is None:
106 if data is None:
122 return meth()
107 return meth()
123 else:
108 else:
124 return meth(data)
109 return meth(data)
125
110
126 def close(self):
111 def close(self):
127 return self._main.close()
112 return self._main.close()
128
113
129 def flush(self):
114 def flush(self):
130 return self._main.flush()
115 return self._main.flush()
131
116
132 class sshpeer(wireproto.wirepeer):
117 class sshpeer(wireproto.wirepeer):
133 def __init__(self, ui, path, create=False):
118 def __init__(self, ui, path, create=False):
134 self._url = path
119 self._url = path
135 self.ui = ui
120 self.ui = ui
136 self.pipeo = self.pipei = self.pipee = None
121 self.pipeo = self.pipei = self.pipee = None
137
122
138 u = util.url(path, parsequery=False, parsefragment=False)
123 u = util.url(path, parsequery=False, parsefragment=False)
139 if u.scheme != 'ssh' or not u.host or u.path is None:
124 if u.scheme != 'ssh' or not u.host or u.path is None:
140 self._abort(error.RepoError(_("couldn't parse location %s") % path))
125 self._abort(error.RepoError(_("couldn't parse location %s") % path))
141
126
142 self.user = u.user
127 self.user = u.user
143 if u.passwd is not None:
128 if u.passwd is not None:
144 self._abort(error.RepoError(_("password in URL not supported")))
129 self._abort(error.RepoError(_("password in URL not supported")))
145 self.host = u.host
130 self.host = u.host
146 self.port = u.port
131 self.port = u.port
147 self.path = u.path or "."
132 self.path = u.path or "."
148
133
149 sshcmd = self.ui.config("ui", "ssh")
134 sshcmd = self.ui.config("ui", "ssh")
150 remotecmd = self.ui.config("ui", "remotecmd")
135 remotecmd = self.ui.config("ui", "remotecmd")
151
136
152 args = util.sshargs(sshcmd,
137 args = util.sshargs(sshcmd,
153 _serverquote(self.host),
138 _serverquote(self.host),
154 _serverquote(self.user),
139 _serverquote(self.user),
155 _serverquote(self.port))
140 _serverquote(self.port))
156
141
157 if create:
142 if create:
158 cmd = '%s %s %s' % (sshcmd, args,
143 cmd = '%s %s %s' % (sshcmd, args,
159 util.shellquote("%s init %s" %
144 util.shellquote("%s init %s" %
160 (_serverquote(remotecmd), _serverquote(self.path))))
145 (_serverquote(remotecmd), _serverquote(self.path))))
161 ui.debug('running %s\n' % cmd)
146 ui.debug('running %s\n' % cmd)
162 res = ui.system(cmd, blockedtag='sshpeer')
147 res = ui.system(cmd, blockedtag='sshpeer')
163 if res != 0:
148 if res != 0:
164 self._abort(error.RepoError(_("could not create remote repo")))
149 self._abort(error.RepoError(_("could not create remote repo")))
165
150
166 self._validaterepo(sshcmd, args, remotecmd)
151 self._validaterepo(sshcmd, args, remotecmd)
167
152
168 def url(self):
153 def url(self):
169 return self._url
154 return self._url
170
155
171 def _validaterepo(self, sshcmd, args, remotecmd):
156 def _validaterepo(self, sshcmd, args, remotecmd):
172 # cleanup up previous run
157 # cleanup up previous run
173 self.cleanup()
158 self.cleanup()
174
159
175 cmd = '%s %s %s' % (sshcmd, args,
160 cmd = '%s %s %s' % (sshcmd, args,
176 util.shellquote("%s -R %s serve --stdio" %
161 util.shellquote("%s -R %s serve --stdio" %
177 (_serverquote(remotecmd), _serverquote(self.path))))
162 (_serverquote(remotecmd), _serverquote(self.path))))
178 self.ui.debug('running %s\n' % cmd)
163 self.ui.debug('running %s\n' % cmd)
179 cmd = util.quotecommand(cmd)
164 cmd = util.quotecommand(cmd)
180
165
181 # while self.subprocess isn't used, having it allows the subprocess to
166 # while self.subprocess isn't used, having it allows the subprocess to
182 # to clean up correctly later
167 # to clean up correctly later
183 #
168 #
184 # no buffer allow the use of 'select'
169 # no buffer allow the use of 'select'
185 # feel free to remove buffering and select usage when we ultimately
170 # feel free to remove buffering and select usage when we ultimately
186 # move to threading.
171 # move to threading.
187 sub = util.popen4(cmd, bufsize=0)
172 sub = util.popen4(cmd, bufsize=0)
188 self.pipeo, self.pipei, self.pipee, self.subprocess = sub
173 self.pipeo, self.pipei, self.pipee, self.subprocess = sub
189
174
190 self.pipei = util.bufferedinputpipe(self.pipei)
175 self.pipei = util.bufferedinputpipe(self.pipei)
191 self.pipei = doublepipe(self.ui, self.pipei, self.pipee)
176 self.pipei = doublepipe(self.ui, self.pipei, self.pipee)
192 self.pipeo = doublepipe(self.ui, self.pipeo, self.pipee)
177 self.pipeo = doublepipe(self.ui, self.pipeo, self.pipee)
193
178
194 # skip any noise generated by remote shell
179 # skip any noise generated by remote shell
195 self._callstream("hello")
180 self._callstream("hello")
196 r = self._callstream("between", pairs=("%s-%s" % ("0"*40, "0"*40)))
181 r = self._callstream("between", pairs=("%s-%s" % ("0"*40, "0"*40)))
197 lines = ["", "dummy"]
182 lines = ["", "dummy"]
198 max_noise = 500
183 max_noise = 500
199 while lines[-1] and max_noise:
184 while lines[-1] and max_noise:
200 l = r.readline()
185 l = r.readline()
201 self.readerr()
186 self.readerr()
202 if lines[-1] == "1\n" and l == "\n":
187 if lines[-1] == "1\n" and l == "\n":
203 break
188 break
204 if l:
189 if l:
205 self.ui.debug("remote: ", l)
190 self.ui.debug("remote: ", l)
206 lines.append(l)
191 lines.append(l)
207 max_noise -= 1
192 max_noise -= 1
208 else:
193 else:
209 self._abort(error.RepoError(_('no suitable response from '
194 self._abort(error.RepoError(_('no suitable response from '
210 'remote hg')))
195 'remote hg')))
211
196
212 self._caps = set()
197 self._caps = set()
213 for l in reversed(lines):
198 for l in reversed(lines):
214 if l.startswith("capabilities:"):
199 if l.startswith("capabilities:"):
215 self._caps.update(l[:-1].split(":")[1].split())
200 self._caps.update(l[:-1].split(":")[1].split())
216 break
201 break
217
202
218 def _capabilities(self):
203 def _capabilities(self):
219 return self._caps
204 return self._caps
220
205
221 def readerr(self):
206 def readerr(self):
222 _forwardoutput(self.ui, self.pipee)
207 _forwardoutput(self.ui, self.pipee)
223
208
224 def _abort(self, exception):
209 def _abort(self, exception):
225 self.cleanup()
210 self.cleanup()
226 raise exception
211 raise exception
227
212
228 def cleanup(self):
213 def cleanup(self):
229 if self.pipeo is None:
214 if self.pipeo is None:
230 return
215 return
231 self.pipeo.close()
216 self.pipeo.close()
232 self.pipei.close()
217 self.pipei.close()
233 try:
218 try:
234 # read the error descriptor until EOF
219 # read the error descriptor until EOF
235 for l in self.pipee:
220 for l in self.pipee:
236 self.ui.status(_("remote: "), l)
221 self.ui.status(_("remote: "), l)
237 except (IOError, ValueError):
222 except (IOError, ValueError):
238 pass
223 pass
239 self.pipee.close()
224 self.pipee.close()
240
225
241 __del__ = cleanup
226 __del__ = cleanup
242
227
243 def _submitbatch(self, req):
228 def _submitbatch(self, req):
244 rsp = self._callstream("batch", cmds=wireproto.encodebatchcmds(req))
229 rsp = self._callstream("batch", cmds=wireproto.encodebatchcmds(req))
245 available = self._getamount()
230 available = self._getamount()
246 # TODO this response parsing is probably suboptimal for large
231 # TODO this response parsing is probably suboptimal for large
247 # batches with large responses.
232 # batches with large responses.
248 toread = min(available, 1024)
233 toread = min(available, 1024)
249 work = rsp.read(toread)
234 work = rsp.read(toread)
250 available -= toread
235 available -= toread
251 chunk = work
236 chunk = work
252 while chunk:
237 while chunk:
253 while ';' in work:
238 while ';' in work:
254 one, work = work.split(';', 1)
239 one, work = work.split(';', 1)
255 yield wireproto.unescapearg(one)
240 yield wireproto.unescapearg(one)
256 toread = min(available, 1024)
241 toread = min(available, 1024)
257 chunk = rsp.read(toread)
242 chunk = rsp.read(toread)
258 available -= toread
243 available -= toread
259 work += chunk
244 work += chunk
260 yield wireproto.unescapearg(work)
245 yield wireproto.unescapearg(work)
261
246
262 def _callstream(self, cmd, **args):
247 def _callstream(self, cmd, **args):
263 args = pycompat.byteskwargs(args)
248 args = pycompat.byteskwargs(args)
264 self.ui.debug("sending %s command\n" % cmd)
249 self.ui.debug("sending %s command\n" % cmd)
265 self.pipeo.write("%s\n" % cmd)
250 self.pipeo.write("%s\n" % cmd)
266 _func, names = wireproto.commands[cmd]
251 _func, names = wireproto.commands[cmd]
267 keys = names.split()
252 keys = names.split()
268 wireargs = {}
253 wireargs = {}
269 for k in keys:
254 for k in keys:
270 if k == '*':
255 if k == '*':
271 wireargs['*'] = args
256 wireargs['*'] = args
272 break
257 break
273 else:
258 else:
274 wireargs[k] = args[k]
259 wireargs[k] = args[k]
275 del args[k]
260 del args[k]
276 for k, v in sorted(wireargs.iteritems()):
261 for k, v in sorted(wireargs.iteritems()):
277 self.pipeo.write("%s %d\n" % (k, len(v)))
262 self.pipeo.write("%s %d\n" % (k, len(v)))
278 if isinstance(v, dict):
263 if isinstance(v, dict):
279 for dk, dv in v.iteritems():
264 for dk, dv in v.iteritems():
280 self.pipeo.write("%s %d\n" % (dk, len(dv)))
265 self.pipeo.write("%s %d\n" % (dk, len(dv)))
281 self.pipeo.write(dv)
266 self.pipeo.write(dv)
282 else:
267 else:
283 self.pipeo.write(v)
268 self.pipeo.write(v)
284 self.pipeo.flush()
269 self.pipeo.flush()
285
270
286 return self.pipei
271 return self.pipei
287
272
288 def _callcompressable(self, cmd, **args):
273 def _callcompressable(self, cmd, **args):
289 return self._callstream(cmd, **args)
274 return self._callstream(cmd, **args)
290
275
291 def _call(self, cmd, **args):
276 def _call(self, cmd, **args):
292 self._callstream(cmd, **args)
277 self._callstream(cmd, **args)
293 return self._recv()
278 return self._recv()
294
279
295 def _callpush(self, cmd, fp, **args):
280 def _callpush(self, cmd, fp, **args):
296 r = self._call(cmd, **args)
281 r = self._call(cmd, **args)
297 if r:
282 if r:
298 return '', r
283 return '', r
299 for d in iter(lambda: fp.read(4096), ''):
284 for d in iter(lambda: fp.read(4096), ''):
300 self._send(d)
285 self._send(d)
301 self._send("", flush=True)
286 self._send("", flush=True)
302 r = self._recv()
287 r = self._recv()
303 if r:
288 if r:
304 return '', r
289 return '', r
305 return self._recv(), ''
290 return self._recv(), ''
306
291
307 def _calltwowaystream(self, cmd, fp, **args):
292 def _calltwowaystream(self, cmd, fp, **args):
308 r = self._call(cmd, **args)
293 r = self._call(cmd, **args)
309 if r:
294 if r:
310 # XXX needs to be made better
295 # XXX needs to be made better
311 raise error.Abort(_('unexpected remote reply: %s') % r)
296 raise error.Abort(_('unexpected remote reply: %s') % r)
312 for d in iter(lambda: fp.read(4096), ''):
297 for d in iter(lambda: fp.read(4096), ''):
313 self._send(d)
298 self._send(d)
314 self._send("", flush=True)
299 self._send("", flush=True)
315 return self.pipei
300 return self.pipei
316
301
317 def _getamount(self):
302 def _getamount(self):
318 l = self.pipei.readline()
303 l = self.pipei.readline()
319 if l == '\n':
304 if l == '\n':
320 self.readerr()
305 self.readerr()
321 msg = _('check previous remote output')
306 msg = _('check previous remote output')
322 self._abort(error.OutOfBandError(hint=msg))
307 self._abort(error.OutOfBandError(hint=msg))
323 self.readerr()
308 self.readerr()
324 try:
309 try:
325 return int(l)
310 return int(l)
326 except ValueError:
311 except ValueError:
327 self._abort(error.ResponseError(_("unexpected response:"), l))
312 self._abort(error.ResponseError(_("unexpected response:"), l))
328
313
329 def _recv(self):
314 def _recv(self):
330 return self.pipei.read(self._getamount())
315 return self.pipei.read(self._getamount())
331
316
332 def _send(self, data, flush=False):
317 def _send(self, data, flush=False):
333 self.pipeo.write("%d\n" % len(data))
318 self.pipeo.write("%d\n" % len(data))
334 if data:
319 if data:
335 self.pipeo.write(data)
320 self.pipeo.write(data)
336 if flush:
321 if flush:
337 self.pipeo.flush()
322 self.pipeo.flush()
338 self.readerr()
323 self.readerr()
339
324
340 def lock(self):
341 self._call("lock")
342 return remotelock(self)
343
344 def unlock(self):
345 self._call("unlock")
346
347 def addchangegroup(self, cg, source, url, lock=None):
348 '''Send a changegroup to the remote server. Return an integer
349 similar to unbundle(). DEPRECATED, since it requires locking the
350 remote.'''
351 d = self._call("addchangegroup")
352 if d:
353 self._abort(error.RepoError(_("push refused: %s") % d))
354 for d in iter(lambda: cg.read(4096), ''):
355 self.pipeo.write(d)
356 self.readerr()
357
358 self.pipeo.flush()
359
360 self.readerr()
361 r = self._recv()
362 if not r:
363 return 1
364 try:
365 return int(r)
366 except ValueError:
367 self._abort(error.ResponseError(_("unexpected response:"), r))
368
369 instance = sshpeer
325 instance = sshpeer
General Comments 0
You need to be logged in to leave comments. Login now