##// END OF EJS Templates
exchange: fix indentation in _pullchangeset
Mike Edgar -
r23217:2f12ac53 default
parent child Browse files
Show More
@@ -1,1297 +1,1297 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 i18n import _
8 from i18n import _
9 from node import hex, nullid
9 from node import hex, nullid
10 import errno, urllib
10 import errno, urllib
11 import util, scmutil, changegroup, base85, error
11 import util, scmutil, changegroup, base85, error
12 import discovery, phases, obsolete, bookmarks as bookmod, bundle2, pushkey
12 import discovery, phases, obsolete, bookmarks as bookmod, bundle2, pushkey
13
13
14 def readbundle(ui, fh, fname, vfs=None):
14 def readbundle(ui, fh, fname, vfs=None):
15 header = changegroup.readexactly(fh, 4)
15 header = changegroup.readexactly(fh, 4)
16
16
17 alg = None
17 alg = None
18 if not fname:
18 if not fname:
19 fname = "stream"
19 fname = "stream"
20 if not header.startswith('HG') and header.startswith('\0'):
20 if not header.startswith('HG') and header.startswith('\0'):
21 fh = changegroup.headerlessfixup(fh, header)
21 fh = changegroup.headerlessfixup(fh, header)
22 header = "HG10"
22 header = "HG10"
23 alg = 'UN'
23 alg = 'UN'
24 elif vfs:
24 elif vfs:
25 fname = vfs.join(fname)
25 fname = vfs.join(fname)
26
26
27 magic, version = header[0:2], header[2:4]
27 magic, version = header[0:2], header[2:4]
28
28
29 if magic != 'HG':
29 if magic != 'HG':
30 raise util.Abort(_('%s: not a Mercurial bundle') % fname)
30 raise util.Abort(_('%s: not a Mercurial bundle') % fname)
31 if version == '10':
31 if version == '10':
32 if alg is None:
32 if alg is None:
33 alg = changegroup.readexactly(fh, 2)
33 alg = changegroup.readexactly(fh, 2)
34 return changegroup.cg1unpacker(fh, alg)
34 return changegroup.cg1unpacker(fh, alg)
35 elif version == '2Y':
35 elif version == '2Y':
36 return bundle2.unbundle20(ui, fh, header=magic + version)
36 return bundle2.unbundle20(ui, fh, header=magic + version)
37 else:
37 else:
38 raise util.Abort(_('%s: unknown bundle version %s') % (fname, version))
38 raise util.Abort(_('%s: unknown bundle version %s') % (fname, version))
39
39
40 def buildobsmarkerspart(bundler, markers):
40 def buildobsmarkerspart(bundler, markers):
41 """add an obsmarker part to the bundler with <markers>
41 """add an obsmarker part to the bundler with <markers>
42
42
43 No part is created if markers is empty.
43 No part is created if markers is empty.
44 Raises ValueError if the bundler doesn't support any known obsmarker format.
44 Raises ValueError if the bundler doesn't support any known obsmarker format.
45 """
45 """
46 if markers:
46 if markers:
47 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
47 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
48 version = obsolete.commonversion(remoteversions)
48 version = obsolete.commonversion(remoteversions)
49 if version is None:
49 if version is None:
50 raise ValueError('bundler do not support common obsmarker format')
50 raise ValueError('bundler do not support common obsmarker format')
51 stream = obsolete.encodemarkers(markers, True, version=version)
51 stream = obsolete.encodemarkers(markers, True, version=version)
52 return bundler.newpart('B2X:OBSMARKERS', data=stream)
52 return bundler.newpart('B2X:OBSMARKERS', data=stream)
53 return None
53 return None
54
54
55 class pushoperation(object):
55 class pushoperation(object):
56 """A object that represent a single push operation
56 """A object that represent a single push operation
57
57
58 It purpose is to carry push related state and very common operation.
58 It purpose is to carry push related state and very common operation.
59
59
60 A new should be created at the beginning of each push and discarded
60 A new should be created at the beginning of each push and discarded
61 afterward.
61 afterward.
62 """
62 """
63
63
64 def __init__(self, repo, remote, force=False, revs=None, newbranch=False,
64 def __init__(self, repo, remote, force=False, revs=None, newbranch=False,
65 bookmarks=()):
65 bookmarks=()):
66 # repo we push from
66 # repo we push from
67 self.repo = repo
67 self.repo = repo
68 self.ui = repo.ui
68 self.ui = repo.ui
69 # repo we push to
69 # repo we push to
70 self.remote = remote
70 self.remote = remote
71 # force option provided
71 # force option provided
72 self.force = force
72 self.force = force
73 # revs to be pushed (None is "all")
73 # revs to be pushed (None is "all")
74 self.revs = revs
74 self.revs = revs
75 # bookmark explicitly pushed
75 # bookmark explicitly pushed
76 self.bookmarks = bookmarks
76 self.bookmarks = bookmarks
77 # allow push of new branch
77 # allow push of new branch
78 self.newbranch = newbranch
78 self.newbranch = newbranch
79 # did a local lock get acquired?
79 # did a local lock get acquired?
80 self.locallocked = None
80 self.locallocked = None
81 # step already performed
81 # step already performed
82 # (used to check what steps have been already performed through bundle2)
82 # (used to check what steps have been already performed through bundle2)
83 self.stepsdone = set()
83 self.stepsdone = set()
84 # Integer version of the changegroup push result
84 # Integer version of the changegroup push result
85 # - None means nothing to push
85 # - None means nothing to push
86 # - 0 means HTTP error
86 # - 0 means HTTP error
87 # - 1 means we pushed and remote head count is unchanged *or*
87 # - 1 means we pushed and remote head count is unchanged *or*
88 # we have outgoing changesets but refused to push
88 # we have outgoing changesets but refused to push
89 # - other values as described by addchangegroup()
89 # - other values as described by addchangegroup()
90 self.cgresult = None
90 self.cgresult = None
91 # Boolean value for the bookmark push
91 # Boolean value for the bookmark push
92 self.bkresult = None
92 self.bkresult = None
93 # discover.outgoing object (contains common and outgoing data)
93 # discover.outgoing object (contains common and outgoing data)
94 self.outgoing = None
94 self.outgoing = None
95 # all remote heads before the push
95 # all remote heads before the push
96 self.remoteheads = None
96 self.remoteheads = None
97 # testable as a boolean indicating if any nodes are missing locally.
97 # testable as a boolean indicating if any nodes are missing locally.
98 self.incoming = None
98 self.incoming = None
99 # phases changes that must be pushed along side the changesets
99 # phases changes that must be pushed along side the changesets
100 self.outdatedphases = None
100 self.outdatedphases = None
101 # phases changes that must be pushed if changeset push fails
101 # phases changes that must be pushed if changeset push fails
102 self.fallbackoutdatedphases = None
102 self.fallbackoutdatedphases = None
103 # outgoing obsmarkers
103 # outgoing obsmarkers
104 self.outobsmarkers = set()
104 self.outobsmarkers = set()
105 # outgoing bookmarks
105 # outgoing bookmarks
106 self.outbookmarks = []
106 self.outbookmarks = []
107
107
108 @util.propertycache
108 @util.propertycache
109 def futureheads(self):
109 def futureheads(self):
110 """future remote heads if the changeset push succeeds"""
110 """future remote heads if the changeset push succeeds"""
111 return self.outgoing.missingheads
111 return self.outgoing.missingheads
112
112
113 @util.propertycache
113 @util.propertycache
114 def fallbackheads(self):
114 def fallbackheads(self):
115 """future remote heads if the changeset push fails"""
115 """future remote heads if the changeset push fails"""
116 if self.revs is None:
116 if self.revs is None:
117 # not target to push, all common are relevant
117 # not target to push, all common are relevant
118 return self.outgoing.commonheads
118 return self.outgoing.commonheads
119 unfi = self.repo.unfiltered()
119 unfi = self.repo.unfiltered()
120 # I want cheads = heads(::missingheads and ::commonheads)
120 # I want cheads = heads(::missingheads and ::commonheads)
121 # (missingheads is revs with secret changeset filtered out)
121 # (missingheads is revs with secret changeset filtered out)
122 #
122 #
123 # This can be expressed as:
123 # This can be expressed as:
124 # cheads = ( (missingheads and ::commonheads)
124 # cheads = ( (missingheads and ::commonheads)
125 # + (commonheads and ::missingheads))"
125 # + (commonheads and ::missingheads))"
126 # )
126 # )
127 #
127 #
128 # while trying to push we already computed the following:
128 # while trying to push we already computed the following:
129 # common = (::commonheads)
129 # common = (::commonheads)
130 # missing = ((commonheads::missingheads) - commonheads)
130 # missing = ((commonheads::missingheads) - commonheads)
131 #
131 #
132 # We can pick:
132 # We can pick:
133 # * missingheads part of common (::commonheads)
133 # * missingheads part of common (::commonheads)
134 common = set(self.outgoing.common)
134 common = set(self.outgoing.common)
135 nm = self.repo.changelog.nodemap
135 nm = self.repo.changelog.nodemap
136 cheads = [node for node in self.revs if nm[node] in common]
136 cheads = [node for node in self.revs if nm[node] in common]
137 # and
137 # and
138 # * commonheads parents on missing
138 # * commonheads parents on missing
139 revset = unfi.set('%ln and parents(roots(%ln))',
139 revset = unfi.set('%ln and parents(roots(%ln))',
140 self.outgoing.commonheads,
140 self.outgoing.commonheads,
141 self.outgoing.missing)
141 self.outgoing.missing)
142 cheads.extend(c.node() for c in revset)
142 cheads.extend(c.node() for c in revset)
143 return cheads
143 return cheads
144
144
145 @property
145 @property
146 def commonheads(self):
146 def commonheads(self):
147 """set of all common heads after changeset bundle push"""
147 """set of all common heads after changeset bundle push"""
148 if self.cgresult:
148 if self.cgresult:
149 return self.futureheads
149 return self.futureheads
150 else:
150 else:
151 return self.fallbackheads
151 return self.fallbackheads
152
152
153 # mapping of message used when pushing bookmark
153 # mapping of message used when pushing bookmark
154 bookmsgmap = {'update': (_("updating bookmark %s\n"),
154 bookmsgmap = {'update': (_("updating bookmark %s\n"),
155 _('updating bookmark %s failed!\n')),
155 _('updating bookmark %s failed!\n')),
156 'export': (_("exporting bookmark %s\n"),
156 'export': (_("exporting bookmark %s\n"),
157 _('exporting bookmark %s failed!\n')),
157 _('exporting bookmark %s failed!\n')),
158 'delete': (_("deleting remote bookmark %s\n"),
158 'delete': (_("deleting remote bookmark %s\n"),
159 _('deleting remote bookmark %s failed!\n')),
159 _('deleting remote bookmark %s failed!\n')),
160 }
160 }
161
161
162
162
163 def push(repo, remote, force=False, revs=None, newbranch=False, bookmarks=()):
163 def push(repo, remote, force=False, revs=None, newbranch=False, bookmarks=()):
164 '''Push outgoing changesets (limited by revs) from a local
164 '''Push outgoing changesets (limited by revs) from a local
165 repository to remote. Return an integer:
165 repository to remote. Return an integer:
166 - None means nothing to push
166 - None means nothing to push
167 - 0 means HTTP error
167 - 0 means HTTP error
168 - 1 means we pushed and remote head count is unchanged *or*
168 - 1 means we pushed and remote head count is unchanged *or*
169 we have outgoing changesets but refused to push
169 we have outgoing changesets but refused to push
170 - other values as described by addchangegroup()
170 - other values as described by addchangegroup()
171 '''
171 '''
172 pushop = pushoperation(repo, remote, force, revs, newbranch, bookmarks)
172 pushop = pushoperation(repo, remote, force, revs, newbranch, bookmarks)
173 if pushop.remote.local():
173 if pushop.remote.local():
174 missing = (set(pushop.repo.requirements)
174 missing = (set(pushop.repo.requirements)
175 - pushop.remote.local().supported)
175 - pushop.remote.local().supported)
176 if missing:
176 if missing:
177 msg = _("required features are not"
177 msg = _("required features are not"
178 " supported in the destination:"
178 " supported in the destination:"
179 " %s") % (', '.join(sorted(missing)))
179 " %s") % (', '.join(sorted(missing)))
180 raise util.Abort(msg)
180 raise util.Abort(msg)
181
181
182 # there are two ways to push to remote repo:
182 # there are two ways to push to remote repo:
183 #
183 #
184 # addchangegroup assumes local user can lock remote
184 # addchangegroup assumes local user can lock remote
185 # repo (local filesystem, old ssh servers).
185 # repo (local filesystem, old ssh servers).
186 #
186 #
187 # unbundle assumes local user cannot lock remote repo (new ssh
187 # unbundle assumes local user cannot lock remote repo (new ssh
188 # servers, http servers).
188 # servers, http servers).
189
189
190 if not pushop.remote.canpush():
190 if not pushop.remote.canpush():
191 raise util.Abort(_("destination does not support push"))
191 raise util.Abort(_("destination does not support push"))
192 # get local lock as we might write phase data
192 # get local lock as we might write phase data
193 locallock = None
193 locallock = None
194 try:
194 try:
195 locallock = pushop.repo.lock()
195 locallock = pushop.repo.lock()
196 pushop.locallocked = True
196 pushop.locallocked = True
197 except IOError, err:
197 except IOError, err:
198 pushop.locallocked = False
198 pushop.locallocked = False
199 if err.errno != errno.EACCES:
199 if err.errno != errno.EACCES:
200 raise
200 raise
201 # source repo cannot be locked.
201 # source repo cannot be locked.
202 # We do not abort the push, but just disable the local phase
202 # We do not abort the push, but just disable the local phase
203 # synchronisation.
203 # synchronisation.
204 msg = 'cannot lock source repository: %s\n' % err
204 msg = 'cannot lock source repository: %s\n' % err
205 pushop.ui.debug(msg)
205 pushop.ui.debug(msg)
206 try:
206 try:
207 pushop.repo.checkpush(pushop)
207 pushop.repo.checkpush(pushop)
208 lock = None
208 lock = None
209 unbundle = pushop.remote.capable('unbundle')
209 unbundle = pushop.remote.capable('unbundle')
210 if not unbundle:
210 if not unbundle:
211 lock = pushop.remote.lock()
211 lock = pushop.remote.lock()
212 try:
212 try:
213 _pushdiscovery(pushop)
213 _pushdiscovery(pushop)
214 if (pushop.repo.ui.configbool('experimental', 'bundle2-exp',
214 if (pushop.repo.ui.configbool('experimental', 'bundle2-exp',
215 False)
215 False)
216 and pushop.remote.capable('bundle2-exp')):
216 and pushop.remote.capable('bundle2-exp')):
217 _pushbundle2(pushop)
217 _pushbundle2(pushop)
218 _pushchangeset(pushop)
218 _pushchangeset(pushop)
219 _pushsyncphase(pushop)
219 _pushsyncphase(pushop)
220 _pushobsolete(pushop)
220 _pushobsolete(pushop)
221 _pushbookmark(pushop)
221 _pushbookmark(pushop)
222 finally:
222 finally:
223 if lock is not None:
223 if lock is not None:
224 lock.release()
224 lock.release()
225 finally:
225 finally:
226 if locallock is not None:
226 if locallock is not None:
227 locallock.release()
227 locallock.release()
228
228
229 return pushop
229 return pushop
230
230
231 # list of steps to perform discovery before push
231 # list of steps to perform discovery before push
232 pushdiscoveryorder = []
232 pushdiscoveryorder = []
233
233
234 # Mapping between step name and function
234 # Mapping between step name and function
235 #
235 #
236 # This exists to help extensions wrap steps if necessary
236 # This exists to help extensions wrap steps if necessary
237 pushdiscoverymapping = {}
237 pushdiscoverymapping = {}
238
238
239 def pushdiscovery(stepname):
239 def pushdiscovery(stepname):
240 """decorator for function performing discovery before push
240 """decorator for function performing discovery before push
241
241
242 The function is added to the step -> function mapping and appended to the
242 The function is added to the step -> function mapping and appended to the
243 list of steps. Beware that decorated function will be added in order (this
243 list of steps. Beware that decorated function will be added in order (this
244 may matter).
244 may matter).
245
245
246 You can only use this decorator for a new step, if you want to wrap a step
246 You can only use this decorator for a new step, if you want to wrap a step
247 from an extension, change the pushdiscovery dictionary directly."""
247 from an extension, change the pushdiscovery dictionary directly."""
248 def dec(func):
248 def dec(func):
249 assert stepname not in pushdiscoverymapping
249 assert stepname not in pushdiscoverymapping
250 pushdiscoverymapping[stepname] = func
250 pushdiscoverymapping[stepname] = func
251 pushdiscoveryorder.append(stepname)
251 pushdiscoveryorder.append(stepname)
252 return func
252 return func
253 return dec
253 return dec
254
254
255 def _pushdiscovery(pushop):
255 def _pushdiscovery(pushop):
256 """Run all discovery steps"""
256 """Run all discovery steps"""
257 for stepname in pushdiscoveryorder:
257 for stepname in pushdiscoveryorder:
258 step = pushdiscoverymapping[stepname]
258 step = pushdiscoverymapping[stepname]
259 step(pushop)
259 step(pushop)
260
260
261 @pushdiscovery('changeset')
261 @pushdiscovery('changeset')
262 def _pushdiscoverychangeset(pushop):
262 def _pushdiscoverychangeset(pushop):
263 """discover the changeset that need to be pushed"""
263 """discover the changeset that need to be pushed"""
264 unfi = pushop.repo.unfiltered()
264 unfi = pushop.repo.unfiltered()
265 fci = discovery.findcommonincoming
265 fci = discovery.findcommonincoming
266 commoninc = fci(unfi, pushop.remote, force=pushop.force)
266 commoninc = fci(unfi, pushop.remote, force=pushop.force)
267 common, inc, remoteheads = commoninc
267 common, inc, remoteheads = commoninc
268 fco = discovery.findcommonoutgoing
268 fco = discovery.findcommonoutgoing
269 outgoing = fco(unfi, pushop.remote, onlyheads=pushop.revs,
269 outgoing = fco(unfi, pushop.remote, onlyheads=pushop.revs,
270 commoninc=commoninc, force=pushop.force)
270 commoninc=commoninc, force=pushop.force)
271 pushop.outgoing = outgoing
271 pushop.outgoing = outgoing
272 pushop.remoteheads = remoteheads
272 pushop.remoteheads = remoteheads
273 pushop.incoming = inc
273 pushop.incoming = inc
274
274
275 @pushdiscovery('phase')
275 @pushdiscovery('phase')
276 def _pushdiscoveryphase(pushop):
276 def _pushdiscoveryphase(pushop):
277 """discover the phase that needs to be pushed
277 """discover the phase that needs to be pushed
278
278
279 (computed for both success and failure case for changesets push)"""
279 (computed for both success and failure case for changesets push)"""
280 outgoing = pushop.outgoing
280 outgoing = pushop.outgoing
281 unfi = pushop.repo.unfiltered()
281 unfi = pushop.repo.unfiltered()
282 remotephases = pushop.remote.listkeys('phases')
282 remotephases = pushop.remote.listkeys('phases')
283 publishing = remotephases.get('publishing', False)
283 publishing = remotephases.get('publishing', False)
284 ana = phases.analyzeremotephases(pushop.repo,
284 ana = phases.analyzeremotephases(pushop.repo,
285 pushop.fallbackheads,
285 pushop.fallbackheads,
286 remotephases)
286 remotephases)
287 pheads, droots = ana
287 pheads, droots = ana
288 extracond = ''
288 extracond = ''
289 if not publishing:
289 if not publishing:
290 extracond = ' and public()'
290 extracond = ' and public()'
291 revset = 'heads((%%ln::%%ln) %s)' % extracond
291 revset = 'heads((%%ln::%%ln) %s)' % extracond
292 # Get the list of all revs draft on remote by public here.
292 # Get the list of all revs draft on remote by public here.
293 # XXX Beware that revset break if droots is not strictly
293 # XXX Beware that revset break if droots is not strictly
294 # XXX root we may want to ensure it is but it is costly
294 # XXX root we may want to ensure it is but it is costly
295 fallback = list(unfi.set(revset, droots, pushop.fallbackheads))
295 fallback = list(unfi.set(revset, droots, pushop.fallbackheads))
296 if not outgoing.missing:
296 if not outgoing.missing:
297 future = fallback
297 future = fallback
298 else:
298 else:
299 # adds changeset we are going to push as draft
299 # adds changeset we are going to push as draft
300 #
300 #
301 # should not be necessary for publishing server, but because of an
301 # should not be necessary for publishing server, but because of an
302 # issue fixed in xxxxx we have to do it anyway.
302 # issue fixed in xxxxx we have to do it anyway.
303 fdroots = list(unfi.set('roots(%ln + %ln::)',
303 fdroots = list(unfi.set('roots(%ln + %ln::)',
304 outgoing.missing, droots))
304 outgoing.missing, droots))
305 fdroots = [f.node() for f in fdroots]
305 fdroots = [f.node() for f in fdroots]
306 future = list(unfi.set(revset, fdroots, pushop.futureheads))
306 future = list(unfi.set(revset, fdroots, pushop.futureheads))
307 pushop.outdatedphases = future
307 pushop.outdatedphases = future
308 pushop.fallbackoutdatedphases = fallback
308 pushop.fallbackoutdatedphases = fallback
309
309
310 @pushdiscovery('obsmarker')
310 @pushdiscovery('obsmarker')
311 def _pushdiscoveryobsmarkers(pushop):
311 def _pushdiscoveryobsmarkers(pushop):
312 if (obsolete.isenabled(pushop.repo, obsolete.exchangeopt)
312 if (obsolete.isenabled(pushop.repo, obsolete.exchangeopt)
313 and pushop.repo.obsstore
313 and pushop.repo.obsstore
314 and 'obsolete' in pushop.remote.listkeys('namespaces')):
314 and 'obsolete' in pushop.remote.listkeys('namespaces')):
315 repo = pushop.repo
315 repo = pushop.repo
316 # very naive computation, that can be quite expensive on big repo.
316 # very naive computation, that can be quite expensive on big repo.
317 # However: evolution is currently slow on them anyway.
317 # However: evolution is currently slow on them anyway.
318 nodes = (c.node() for c in repo.set('::%ln', pushop.futureheads))
318 nodes = (c.node() for c in repo.set('::%ln', pushop.futureheads))
319 pushop.outobsmarkers = pushop.repo.obsstore.relevantmarkers(nodes)
319 pushop.outobsmarkers = pushop.repo.obsstore.relevantmarkers(nodes)
320
320
321 @pushdiscovery('bookmarks')
321 @pushdiscovery('bookmarks')
322 def _pushdiscoverybookmarks(pushop):
322 def _pushdiscoverybookmarks(pushop):
323 ui = pushop.ui
323 ui = pushop.ui
324 repo = pushop.repo.unfiltered()
324 repo = pushop.repo.unfiltered()
325 remote = pushop.remote
325 remote = pushop.remote
326 ui.debug("checking for updated bookmarks\n")
326 ui.debug("checking for updated bookmarks\n")
327 ancestors = ()
327 ancestors = ()
328 if pushop.revs:
328 if pushop.revs:
329 revnums = map(repo.changelog.rev, pushop.revs)
329 revnums = map(repo.changelog.rev, pushop.revs)
330 ancestors = repo.changelog.ancestors(revnums, inclusive=True)
330 ancestors = repo.changelog.ancestors(revnums, inclusive=True)
331 remotebookmark = remote.listkeys('bookmarks')
331 remotebookmark = remote.listkeys('bookmarks')
332
332
333 explicit = set(pushop.bookmarks)
333 explicit = set(pushop.bookmarks)
334
334
335 comp = bookmod.compare(repo, repo._bookmarks, remotebookmark, srchex=hex)
335 comp = bookmod.compare(repo, repo._bookmarks, remotebookmark, srchex=hex)
336 addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = comp
336 addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = comp
337 for b, scid, dcid in advsrc:
337 for b, scid, dcid in advsrc:
338 if b in explicit:
338 if b in explicit:
339 explicit.remove(b)
339 explicit.remove(b)
340 if not ancestors or repo[scid].rev() in ancestors:
340 if not ancestors or repo[scid].rev() in ancestors:
341 pushop.outbookmarks.append((b, dcid, scid))
341 pushop.outbookmarks.append((b, dcid, scid))
342 # search added bookmark
342 # search added bookmark
343 for b, scid, dcid in addsrc:
343 for b, scid, dcid in addsrc:
344 if b in explicit:
344 if b in explicit:
345 explicit.remove(b)
345 explicit.remove(b)
346 pushop.outbookmarks.append((b, '', scid))
346 pushop.outbookmarks.append((b, '', scid))
347 # search for overwritten bookmark
347 # search for overwritten bookmark
348 for b, scid, dcid in advdst + diverge + differ:
348 for b, scid, dcid in advdst + diverge + differ:
349 if b in explicit:
349 if b in explicit:
350 explicit.remove(b)
350 explicit.remove(b)
351 pushop.outbookmarks.append((b, dcid, scid))
351 pushop.outbookmarks.append((b, dcid, scid))
352 # search for bookmark to delete
352 # search for bookmark to delete
353 for b, scid, dcid in adddst:
353 for b, scid, dcid in adddst:
354 if b in explicit:
354 if b in explicit:
355 explicit.remove(b)
355 explicit.remove(b)
356 # treat as "deleted locally"
356 # treat as "deleted locally"
357 pushop.outbookmarks.append((b, dcid, ''))
357 pushop.outbookmarks.append((b, dcid, ''))
358 # identical bookmarks shouldn't get reported
358 # identical bookmarks shouldn't get reported
359 for b, scid, dcid in same:
359 for b, scid, dcid in same:
360 if b in explicit:
360 if b in explicit:
361 explicit.remove(b)
361 explicit.remove(b)
362
362
363 if explicit:
363 if explicit:
364 explicit = sorted(explicit)
364 explicit = sorted(explicit)
365 # we should probably list all of them
365 # we should probably list all of them
366 ui.warn(_('bookmark %s does not exist on the local '
366 ui.warn(_('bookmark %s does not exist on the local '
367 'or remote repository!\n') % explicit[0])
367 'or remote repository!\n') % explicit[0])
368 pushop.bkresult = 2
368 pushop.bkresult = 2
369
369
370 pushop.outbookmarks.sort()
370 pushop.outbookmarks.sort()
371
371
372 def _pushcheckoutgoing(pushop):
372 def _pushcheckoutgoing(pushop):
373 outgoing = pushop.outgoing
373 outgoing = pushop.outgoing
374 unfi = pushop.repo.unfiltered()
374 unfi = pushop.repo.unfiltered()
375 if not outgoing.missing:
375 if not outgoing.missing:
376 # nothing to push
376 # nothing to push
377 scmutil.nochangesfound(unfi.ui, unfi, outgoing.excluded)
377 scmutil.nochangesfound(unfi.ui, unfi, outgoing.excluded)
378 return False
378 return False
379 # something to push
379 # something to push
380 if not pushop.force:
380 if not pushop.force:
381 # if repo.obsstore == False --> no obsolete
381 # if repo.obsstore == False --> no obsolete
382 # then, save the iteration
382 # then, save the iteration
383 if unfi.obsstore:
383 if unfi.obsstore:
384 # this message are here for 80 char limit reason
384 # this message are here for 80 char limit reason
385 mso = _("push includes obsolete changeset: %s!")
385 mso = _("push includes obsolete changeset: %s!")
386 mst = {"unstable": _("push includes unstable changeset: %s!"),
386 mst = {"unstable": _("push includes unstable changeset: %s!"),
387 "bumped": _("push includes bumped changeset: %s!"),
387 "bumped": _("push includes bumped changeset: %s!"),
388 "divergent": _("push includes divergent changeset: %s!")}
388 "divergent": _("push includes divergent changeset: %s!")}
389 # If we are to push if there is at least one
389 # If we are to push if there is at least one
390 # obsolete or unstable changeset in missing, at
390 # obsolete or unstable changeset in missing, at
391 # least one of the missinghead will be obsolete or
391 # least one of the missinghead will be obsolete or
392 # unstable. So checking heads only is ok
392 # unstable. So checking heads only is ok
393 for node in outgoing.missingheads:
393 for node in outgoing.missingheads:
394 ctx = unfi[node]
394 ctx = unfi[node]
395 if ctx.obsolete():
395 if ctx.obsolete():
396 raise util.Abort(mso % ctx)
396 raise util.Abort(mso % ctx)
397 elif ctx.troubled():
397 elif ctx.troubled():
398 raise util.Abort(mst[ctx.troubles()[0]] % ctx)
398 raise util.Abort(mst[ctx.troubles()[0]] % ctx)
399 newbm = pushop.ui.configlist('bookmarks', 'pushing')
399 newbm = pushop.ui.configlist('bookmarks', 'pushing')
400 discovery.checkheads(unfi, pushop.remote, outgoing,
400 discovery.checkheads(unfi, pushop.remote, outgoing,
401 pushop.remoteheads,
401 pushop.remoteheads,
402 pushop.newbranch,
402 pushop.newbranch,
403 bool(pushop.incoming),
403 bool(pushop.incoming),
404 newbm)
404 newbm)
405 return True
405 return True
406
406
407 # List of names of steps to perform for an outgoing bundle2, order matters.
407 # List of names of steps to perform for an outgoing bundle2, order matters.
408 b2partsgenorder = []
408 b2partsgenorder = []
409
409
410 # Mapping between step name and function
410 # Mapping between step name and function
411 #
411 #
412 # This exists to help extensions wrap steps if necessary
412 # This exists to help extensions wrap steps if necessary
413 b2partsgenmapping = {}
413 b2partsgenmapping = {}
414
414
415 def b2partsgenerator(stepname):
415 def b2partsgenerator(stepname):
416 """decorator for function generating bundle2 part
416 """decorator for function generating bundle2 part
417
417
418 The function is added to the step -> function mapping and appended to the
418 The function is added to the step -> function mapping and appended to the
419 list of steps. Beware that decorated functions will be added in order
419 list of steps. Beware that decorated functions will be added in order
420 (this may matter).
420 (this may matter).
421
421
422 You can only use this decorator for new steps, if you want to wrap a step
422 You can only use this decorator for new steps, if you want to wrap a step
423 from an extension, attack the b2partsgenmapping dictionary directly."""
423 from an extension, attack the b2partsgenmapping dictionary directly."""
424 def dec(func):
424 def dec(func):
425 assert stepname not in b2partsgenmapping
425 assert stepname not in b2partsgenmapping
426 b2partsgenmapping[stepname] = func
426 b2partsgenmapping[stepname] = func
427 b2partsgenorder.append(stepname)
427 b2partsgenorder.append(stepname)
428 return func
428 return func
429 return dec
429 return dec
430
430
431 @b2partsgenerator('changeset')
431 @b2partsgenerator('changeset')
432 def _pushb2ctx(pushop, bundler):
432 def _pushb2ctx(pushop, bundler):
433 """handle changegroup push through bundle2
433 """handle changegroup push through bundle2
434
434
435 addchangegroup result is stored in the ``pushop.cgresult`` attribute.
435 addchangegroup result is stored in the ``pushop.cgresult`` attribute.
436 """
436 """
437 if 'changesets' in pushop.stepsdone:
437 if 'changesets' in pushop.stepsdone:
438 return
438 return
439 pushop.stepsdone.add('changesets')
439 pushop.stepsdone.add('changesets')
440 # Send known heads to the server for race detection.
440 # Send known heads to the server for race detection.
441 if not _pushcheckoutgoing(pushop):
441 if not _pushcheckoutgoing(pushop):
442 return
442 return
443 pushop.repo.prepushoutgoinghooks(pushop.repo,
443 pushop.repo.prepushoutgoinghooks(pushop.repo,
444 pushop.remote,
444 pushop.remote,
445 pushop.outgoing)
445 pushop.outgoing)
446 if not pushop.force:
446 if not pushop.force:
447 bundler.newpart('B2X:CHECK:HEADS', data=iter(pushop.remoteheads))
447 bundler.newpart('B2X:CHECK:HEADS', data=iter(pushop.remoteheads))
448 b2caps = bundle2.bundle2caps(pushop.remote)
448 b2caps = bundle2.bundle2caps(pushop.remote)
449 version = None
449 version = None
450 cgversions = b2caps.get('b2x:changegroup')
450 cgversions = b2caps.get('b2x:changegroup')
451 if not cgversions: # 3.1 and 3.2 ship with an empty value
451 if not cgversions: # 3.1 and 3.2 ship with an empty value
452 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
452 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
453 pushop.outgoing)
453 pushop.outgoing)
454 else:
454 else:
455 cgversions = [v for v in cgversions if v in changegroup.packermap]
455 cgversions = [v for v in cgversions if v in changegroup.packermap]
456 if not cgversions:
456 if not cgversions:
457 raise ValueError(_('no common changegroup version'))
457 raise ValueError(_('no common changegroup version'))
458 version = max(cgversions)
458 version = max(cgversions)
459 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
459 cg = changegroup.getlocalchangegroupraw(pushop.repo, 'push',
460 pushop.outgoing,
460 pushop.outgoing,
461 version=version)
461 version=version)
462 cgpart = bundler.newpart('B2X:CHANGEGROUP', data=cg)
462 cgpart = bundler.newpart('B2X:CHANGEGROUP', data=cg)
463 if version is not None:
463 if version is not None:
464 cgpart.addparam('version', version)
464 cgpart.addparam('version', version)
465 def handlereply(op):
465 def handlereply(op):
466 """extract addchangegroup returns from server reply"""
466 """extract addchangegroup returns from server reply"""
467 cgreplies = op.records.getreplies(cgpart.id)
467 cgreplies = op.records.getreplies(cgpart.id)
468 assert len(cgreplies['changegroup']) == 1
468 assert len(cgreplies['changegroup']) == 1
469 pushop.cgresult = cgreplies['changegroup'][0]['return']
469 pushop.cgresult = cgreplies['changegroup'][0]['return']
470 return handlereply
470 return handlereply
471
471
472 @b2partsgenerator('phase')
472 @b2partsgenerator('phase')
473 def _pushb2phases(pushop, bundler):
473 def _pushb2phases(pushop, bundler):
474 """handle phase push through bundle2"""
474 """handle phase push through bundle2"""
475 if 'phases' in pushop.stepsdone:
475 if 'phases' in pushop.stepsdone:
476 return
476 return
477 b2caps = bundle2.bundle2caps(pushop.remote)
477 b2caps = bundle2.bundle2caps(pushop.remote)
478 if not 'b2x:pushkey' in b2caps:
478 if not 'b2x:pushkey' in b2caps:
479 return
479 return
480 pushop.stepsdone.add('phases')
480 pushop.stepsdone.add('phases')
481 part2node = []
481 part2node = []
482 enc = pushkey.encode
482 enc = pushkey.encode
483 for newremotehead in pushop.outdatedphases:
483 for newremotehead in pushop.outdatedphases:
484 part = bundler.newpart('b2x:pushkey')
484 part = bundler.newpart('b2x:pushkey')
485 part.addparam('namespace', enc('phases'))
485 part.addparam('namespace', enc('phases'))
486 part.addparam('key', enc(newremotehead.hex()))
486 part.addparam('key', enc(newremotehead.hex()))
487 part.addparam('old', enc(str(phases.draft)))
487 part.addparam('old', enc(str(phases.draft)))
488 part.addparam('new', enc(str(phases.public)))
488 part.addparam('new', enc(str(phases.public)))
489 part2node.append((part.id, newremotehead))
489 part2node.append((part.id, newremotehead))
490 def handlereply(op):
490 def handlereply(op):
491 for partid, node in part2node:
491 for partid, node in part2node:
492 partrep = op.records.getreplies(partid)
492 partrep = op.records.getreplies(partid)
493 results = partrep['pushkey']
493 results = partrep['pushkey']
494 assert len(results) <= 1
494 assert len(results) <= 1
495 msg = None
495 msg = None
496 if not results:
496 if not results:
497 msg = _('server ignored update of %s to public!\n') % node
497 msg = _('server ignored update of %s to public!\n') % node
498 elif not int(results[0]['return']):
498 elif not int(results[0]['return']):
499 msg = _('updating %s to public failed!\n') % node
499 msg = _('updating %s to public failed!\n') % node
500 if msg is not None:
500 if msg is not None:
501 pushop.ui.warn(msg)
501 pushop.ui.warn(msg)
502 return handlereply
502 return handlereply
503
503
504 @b2partsgenerator('obsmarkers')
504 @b2partsgenerator('obsmarkers')
505 def _pushb2obsmarkers(pushop, bundler):
505 def _pushb2obsmarkers(pushop, bundler):
506 if 'obsmarkers' in pushop.stepsdone:
506 if 'obsmarkers' in pushop.stepsdone:
507 return
507 return
508 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
508 remoteversions = bundle2.obsmarkersversion(bundler.capabilities)
509 if obsolete.commonversion(remoteversions) is None:
509 if obsolete.commonversion(remoteversions) is None:
510 return
510 return
511 pushop.stepsdone.add('obsmarkers')
511 pushop.stepsdone.add('obsmarkers')
512 if pushop.outobsmarkers:
512 if pushop.outobsmarkers:
513 buildobsmarkerspart(bundler, pushop.outobsmarkers)
513 buildobsmarkerspart(bundler, pushop.outobsmarkers)
514
514
515 @b2partsgenerator('bookmarks')
515 @b2partsgenerator('bookmarks')
516 def _pushb2bookmarks(pushop, bundler):
516 def _pushb2bookmarks(pushop, bundler):
517 """handle phase push through bundle2"""
517 """handle phase push through bundle2"""
518 if 'bookmarks' in pushop.stepsdone:
518 if 'bookmarks' in pushop.stepsdone:
519 return
519 return
520 b2caps = bundle2.bundle2caps(pushop.remote)
520 b2caps = bundle2.bundle2caps(pushop.remote)
521 if 'b2x:pushkey' not in b2caps:
521 if 'b2x:pushkey' not in b2caps:
522 return
522 return
523 pushop.stepsdone.add('bookmarks')
523 pushop.stepsdone.add('bookmarks')
524 part2book = []
524 part2book = []
525 enc = pushkey.encode
525 enc = pushkey.encode
526 for book, old, new in pushop.outbookmarks:
526 for book, old, new in pushop.outbookmarks:
527 part = bundler.newpart('b2x:pushkey')
527 part = bundler.newpart('b2x:pushkey')
528 part.addparam('namespace', enc('bookmarks'))
528 part.addparam('namespace', enc('bookmarks'))
529 part.addparam('key', enc(book))
529 part.addparam('key', enc(book))
530 part.addparam('old', enc(old))
530 part.addparam('old', enc(old))
531 part.addparam('new', enc(new))
531 part.addparam('new', enc(new))
532 action = 'update'
532 action = 'update'
533 if not old:
533 if not old:
534 action = 'export'
534 action = 'export'
535 elif not new:
535 elif not new:
536 action = 'delete'
536 action = 'delete'
537 part2book.append((part.id, book, action))
537 part2book.append((part.id, book, action))
538
538
539
539
540 def handlereply(op):
540 def handlereply(op):
541 ui = pushop.ui
541 ui = pushop.ui
542 for partid, book, action in part2book:
542 for partid, book, action in part2book:
543 partrep = op.records.getreplies(partid)
543 partrep = op.records.getreplies(partid)
544 results = partrep['pushkey']
544 results = partrep['pushkey']
545 assert len(results) <= 1
545 assert len(results) <= 1
546 if not results:
546 if not results:
547 pushop.ui.warn(_('server ignored bookmark %s update\n') % book)
547 pushop.ui.warn(_('server ignored bookmark %s update\n') % book)
548 else:
548 else:
549 ret = int(results[0]['return'])
549 ret = int(results[0]['return'])
550 if ret:
550 if ret:
551 ui.status(bookmsgmap[action][0] % book)
551 ui.status(bookmsgmap[action][0] % book)
552 else:
552 else:
553 ui.warn(bookmsgmap[action][1] % book)
553 ui.warn(bookmsgmap[action][1] % book)
554 if pushop.bkresult is not None:
554 if pushop.bkresult is not None:
555 pushop.bkresult = 1
555 pushop.bkresult = 1
556 return handlereply
556 return handlereply
557
557
558
558
559 def _pushbundle2(pushop):
559 def _pushbundle2(pushop):
560 """push data to the remote using bundle2
560 """push data to the remote using bundle2
561
561
562 The only currently supported type of data is changegroup but this will
562 The only currently supported type of data is changegroup but this will
563 evolve in the future."""
563 evolve in the future."""
564 bundler = bundle2.bundle20(pushop.ui, bundle2.bundle2caps(pushop.remote))
564 bundler = bundle2.bundle20(pushop.ui, bundle2.bundle2caps(pushop.remote))
565 # create reply capability
565 # create reply capability
566 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo))
566 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo))
567 bundler.newpart('b2x:replycaps', data=capsblob)
567 bundler.newpart('b2x:replycaps', data=capsblob)
568 replyhandlers = []
568 replyhandlers = []
569 for partgenname in b2partsgenorder:
569 for partgenname in b2partsgenorder:
570 partgen = b2partsgenmapping[partgenname]
570 partgen = b2partsgenmapping[partgenname]
571 ret = partgen(pushop, bundler)
571 ret = partgen(pushop, bundler)
572 if callable(ret):
572 if callable(ret):
573 replyhandlers.append(ret)
573 replyhandlers.append(ret)
574 # do not push if nothing to push
574 # do not push if nothing to push
575 if bundler.nbparts <= 1:
575 if bundler.nbparts <= 1:
576 return
576 return
577 stream = util.chunkbuffer(bundler.getchunks())
577 stream = util.chunkbuffer(bundler.getchunks())
578 try:
578 try:
579 reply = pushop.remote.unbundle(stream, ['force'], 'push')
579 reply = pushop.remote.unbundle(stream, ['force'], 'push')
580 except error.BundleValueError, exc:
580 except error.BundleValueError, exc:
581 raise util.Abort('missing support for %s' % exc)
581 raise util.Abort('missing support for %s' % exc)
582 try:
582 try:
583 op = bundle2.processbundle(pushop.repo, reply)
583 op = bundle2.processbundle(pushop.repo, reply)
584 except error.BundleValueError, exc:
584 except error.BundleValueError, exc:
585 raise util.Abort('missing support for %s' % exc)
585 raise util.Abort('missing support for %s' % exc)
586 for rephand in replyhandlers:
586 for rephand in replyhandlers:
587 rephand(op)
587 rephand(op)
588
588
589 def _pushchangeset(pushop):
589 def _pushchangeset(pushop):
590 """Make the actual push of changeset bundle to remote repo"""
590 """Make the actual push of changeset bundle to remote repo"""
591 if 'changesets' in pushop.stepsdone:
591 if 'changesets' in pushop.stepsdone:
592 return
592 return
593 pushop.stepsdone.add('changesets')
593 pushop.stepsdone.add('changesets')
594 if not _pushcheckoutgoing(pushop):
594 if not _pushcheckoutgoing(pushop):
595 return
595 return
596 pushop.repo.prepushoutgoinghooks(pushop.repo,
596 pushop.repo.prepushoutgoinghooks(pushop.repo,
597 pushop.remote,
597 pushop.remote,
598 pushop.outgoing)
598 pushop.outgoing)
599 outgoing = pushop.outgoing
599 outgoing = pushop.outgoing
600 unbundle = pushop.remote.capable('unbundle')
600 unbundle = pushop.remote.capable('unbundle')
601 # TODO: get bundlecaps from remote
601 # TODO: get bundlecaps from remote
602 bundlecaps = None
602 bundlecaps = None
603 # create a changegroup from local
603 # create a changegroup from local
604 if pushop.revs is None and not (outgoing.excluded
604 if pushop.revs is None and not (outgoing.excluded
605 or pushop.repo.changelog.filteredrevs):
605 or pushop.repo.changelog.filteredrevs):
606 # push everything,
606 # push everything,
607 # use the fast path, no race possible on push
607 # use the fast path, no race possible on push
608 bundler = changegroup.cg1packer(pushop.repo, bundlecaps)
608 bundler = changegroup.cg1packer(pushop.repo, bundlecaps)
609 cg = changegroup.getsubset(pushop.repo,
609 cg = changegroup.getsubset(pushop.repo,
610 outgoing,
610 outgoing,
611 bundler,
611 bundler,
612 'push',
612 'push',
613 fastpath=True)
613 fastpath=True)
614 else:
614 else:
615 cg = changegroup.getlocalchangegroup(pushop.repo, 'push', outgoing,
615 cg = changegroup.getlocalchangegroup(pushop.repo, 'push', outgoing,
616 bundlecaps)
616 bundlecaps)
617
617
618 # apply changegroup to remote
618 # apply changegroup to remote
619 if unbundle:
619 if unbundle:
620 # local repo finds heads on server, finds out what
620 # local repo finds heads on server, finds out what
621 # revs it must push. once revs transferred, if server
621 # revs it must push. once revs transferred, if server
622 # finds it has different heads (someone else won
622 # finds it has different heads (someone else won
623 # commit/push race), server aborts.
623 # commit/push race), server aborts.
624 if pushop.force:
624 if pushop.force:
625 remoteheads = ['force']
625 remoteheads = ['force']
626 else:
626 else:
627 remoteheads = pushop.remoteheads
627 remoteheads = pushop.remoteheads
628 # ssh: return remote's addchangegroup()
628 # ssh: return remote's addchangegroup()
629 # http: return remote's addchangegroup() or 0 for error
629 # http: return remote's addchangegroup() or 0 for error
630 pushop.cgresult = pushop.remote.unbundle(cg, remoteheads,
630 pushop.cgresult = pushop.remote.unbundle(cg, remoteheads,
631 pushop.repo.url())
631 pushop.repo.url())
632 else:
632 else:
633 # we return an integer indicating remote head count
633 # we return an integer indicating remote head count
634 # change
634 # change
635 pushop.cgresult = pushop.remote.addchangegroup(cg, 'push',
635 pushop.cgresult = pushop.remote.addchangegroup(cg, 'push',
636 pushop.repo.url())
636 pushop.repo.url())
637
637
638 def _pushsyncphase(pushop):
638 def _pushsyncphase(pushop):
639 """synchronise phase information locally and remotely"""
639 """synchronise phase information locally and remotely"""
640 cheads = pushop.commonheads
640 cheads = pushop.commonheads
641 # even when we don't push, exchanging phase data is useful
641 # even when we don't push, exchanging phase data is useful
642 remotephases = pushop.remote.listkeys('phases')
642 remotephases = pushop.remote.listkeys('phases')
643 if (pushop.ui.configbool('ui', '_usedassubrepo', False)
643 if (pushop.ui.configbool('ui', '_usedassubrepo', False)
644 and remotephases # server supports phases
644 and remotephases # server supports phases
645 and pushop.cgresult is None # nothing was pushed
645 and pushop.cgresult is None # nothing was pushed
646 and remotephases.get('publishing', False)):
646 and remotephases.get('publishing', False)):
647 # When:
647 # When:
648 # - this is a subrepo push
648 # - this is a subrepo push
649 # - and remote support phase
649 # - and remote support phase
650 # - and no changeset was pushed
650 # - and no changeset was pushed
651 # - and remote is publishing
651 # - and remote is publishing
652 # We may be in issue 3871 case!
652 # We may be in issue 3871 case!
653 # We drop the possible phase synchronisation done by
653 # We drop the possible phase synchronisation done by
654 # courtesy to publish changesets possibly locally draft
654 # courtesy to publish changesets possibly locally draft
655 # on the remote.
655 # on the remote.
656 remotephases = {'publishing': 'True'}
656 remotephases = {'publishing': 'True'}
657 if not remotephases: # old server or public only reply from non-publishing
657 if not remotephases: # old server or public only reply from non-publishing
658 _localphasemove(pushop, cheads)
658 _localphasemove(pushop, cheads)
659 # don't push any phase data as there is nothing to push
659 # don't push any phase data as there is nothing to push
660 else:
660 else:
661 ana = phases.analyzeremotephases(pushop.repo, cheads,
661 ana = phases.analyzeremotephases(pushop.repo, cheads,
662 remotephases)
662 remotephases)
663 pheads, droots = ana
663 pheads, droots = ana
664 ### Apply remote phase on local
664 ### Apply remote phase on local
665 if remotephases.get('publishing', False):
665 if remotephases.get('publishing', False):
666 _localphasemove(pushop, cheads)
666 _localphasemove(pushop, cheads)
667 else: # publish = False
667 else: # publish = False
668 _localphasemove(pushop, pheads)
668 _localphasemove(pushop, pheads)
669 _localphasemove(pushop, cheads, phases.draft)
669 _localphasemove(pushop, cheads, phases.draft)
670 ### Apply local phase on remote
670 ### Apply local phase on remote
671
671
672 if pushop.cgresult:
672 if pushop.cgresult:
673 if 'phases' in pushop.stepsdone:
673 if 'phases' in pushop.stepsdone:
674 # phases already pushed though bundle2
674 # phases already pushed though bundle2
675 return
675 return
676 outdated = pushop.outdatedphases
676 outdated = pushop.outdatedphases
677 else:
677 else:
678 outdated = pushop.fallbackoutdatedphases
678 outdated = pushop.fallbackoutdatedphases
679
679
680 pushop.stepsdone.add('phases')
680 pushop.stepsdone.add('phases')
681
681
682 # filter heads already turned public by the push
682 # filter heads already turned public by the push
683 outdated = [c for c in outdated if c.node() not in pheads]
683 outdated = [c for c in outdated if c.node() not in pheads]
684 b2caps = bundle2.bundle2caps(pushop.remote)
684 b2caps = bundle2.bundle2caps(pushop.remote)
685 if 'b2x:pushkey' in b2caps:
685 if 'b2x:pushkey' in b2caps:
686 # server supports bundle2, let's do a batched push through it
686 # server supports bundle2, let's do a batched push through it
687 #
687 #
688 # This will eventually be unified with the changesets bundle2 push
688 # This will eventually be unified with the changesets bundle2 push
689 bundler = bundle2.bundle20(pushop.ui, b2caps)
689 bundler = bundle2.bundle20(pushop.ui, b2caps)
690 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo))
690 capsblob = bundle2.encodecaps(bundle2.getrepocaps(pushop.repo))
691 bundler.newpart('b2x:replycaps', data=capsblob)
691 bundler.newpart('b2x:replycaps', data=capsblob)
692 part2node = []
692 part2node = []
693 enc = pushkey.encode
693 enc = pushkey.encode
694 for newremotehead in outdated:
694 for newremotehead in outdated:
695 part = bundler.newpart('b2x:pushkey')
695 part = bundler.newpart('b2x:pushkey')
696 part.addparam('namespace', enc('phases'))
696 part.addparam('namespace', enc('phases'))
697 part.addparam('key', enc(newremotehead.hex()))
697 part.addparam('key', enc(newremotehead.hex()))
698 part.addparam('old', enc(str(phases.draft)))
698 part.addparam('old', enc(str(phases.draft)))
699 part.addparam('new', enc(str(phases.public)))
699 part.addparam('new', enc(str(phases.public)))
700 part2node.append((part.id, newremotehead))
700 part2node.append((part.id, newremotehead))
701 stream = util.chunkbuffer(bundler.getchunks())
701 stream = util.chunkbuffer(bundler.getchunks())
702 try:
702 try:
703 reply = pushop.remote.unbundle(stream, ['force'], 'push')
703 reply = pushop.remote.unbundle(stream, ['force'], 'push')
704 op = bundle2.processbundle(pushop.repo, reply)
704 op = bundle2.processbundle(pushop.repo, reply)
705 except error.BundleValueError, exc:
705 except error.BundleValueError, exc:
706 raise util.Abort('missing support for %s' % exc)
706 raise util.Abort('missing support for %s' % exc)
707 for partid, node in part2node:
707 for partid, node in part2node:
708 partrep = op.records.getreplies(partid)
708 partrep = op.records.getreplies(partid)
709 results = partrep['pushkey']
709 results = partrep['pushkey']
710 assert len(results) <= 1
710 assert len(results) <= 1
711 msg = None
711 msg = None
712 if not results:
712 if not results:
713 msg = _('server ignored update of %s to public!\n') % node
713 msg = _('server ignored update of %s to public!\n') % node
714 elif not int(results[0]['return']):
714 elif not int(results[0]['return']):
715 msg = _('updating %s to public failed!\n') % node
715 msg = _('updating %s to public failed!\n') % node
716 if msg is not None:
716 if msg is not None:
717 pushop.ui.warn(msg)
717 pushop.ui.warn(msg)
718
718
719 else:
719 else:
720 # fallback to independent pushkey command
720 # fallback to independent pushkey command
721 for newremotehead in outdated:
721 for newremotehead in outdated:
722 r = pushop.remote.pushkey('phases',
722 r = pushop.remote.pushkey('phases',
723 newremotehead.hex(),
723 newremotehead.hex(),
724 str(phases.draft),
724 str(phases.draft),
725 str(phases.public))
725 str(phases.public))
726 if not r:
726 if not r:
727 pushop.ui.warn(_('updating %s to public failed!\n')
727 pushop.ui.warn(_('updating %s to public failed!\n')
728 % newremotehead)
728 % newremotehead)
729
729
730 def _localphasemove(pushop, nodes, phase=phases.public):
730 def _localphasemove(pushop, nodes, phase=phases.public):
731 """move <nodes> to <phase> in the local source repo"""
731 """move <nodes> to <phase> in the local source repo"""
732 if pushop.locallocked:
732 if pushop.locallocked:
733 tr = pushop.repo.transaction('push-phase-sync')
733 tr = pushop.repo.transaction('push-phase-sync')
734 try:
734 try:
735 phases.advanceboundary(pushop.repo, tr, phase, nodes)
735 phases.advanceboundary(pushop.repo, tr, phase, nodes)
736 tr.close()
736 tr.close()
737 finally:
737 finally:
738 tr.release()
738 tr.release()
739 else:
739 else:
740 # repo is not locked, do not change any phases!
740 # repo is not locked, do not change any phases!
741 # Informs the user that phases should have been moved when
741 # Informs the user that phases should have been moved when
742 # applicable.
742 # applicable.
743 actualmoves = [n for n in nodes if phase < pushop.repo[n].phase()]
743 actualmoves = [n for n in nodes if phase < pushop.repo[n].phase()]
744 phasestr = phases.phasenames[phase]
744 phasestr = phases.phasenames[phase]
745 if actualmoves:
745 if actualmoves:
746 pushop.ui.status(_('cannot lock source repo, skipping '
746 pushop.ui.status(_('cannot lock source repo, skipping '
747 'local %s phase update\n') % phasestr)
747 'local %s phase update\n') % phasestr)
748
748
749 def _pushobsolete(pushop):
749 def _pushobsolete(pushop):
750 """utility function to push obsolete markers to a remote"""
750 """utility function to push obsolete markers to a remote"""
751 if 'obsmarkers' in pushop.stepsdone:
751 if 'obsmarkers' in pushop.stepsdone:
752 return
752 return
753 pushop.ui.debug('try to push obsolete markers to remote\n')
753 pushop.ui.debug('try to push obsolete markers to remote\n')
754 repo = pushop.repo
754 repo = pushop.repo
755 remote = pushop.remote
755 remote = pushop.remote
756 pushop.stepsdone.add('obsmarkers')
756 pushop.stepsdone.add('obsmarkers')
757 if pushop.outobsmarkers:
757 if pushop.outobsmarkers:
758 rslts = []
758 rslts = []
759 remotedata = obsolete._pushkeyescape(pushop.outobsmarkers)
759 remotedata = obsolete._pushkeyescape(pushop.outobsmarkers)
760 for key in sorted(remotedata, reverse=True):
760 for key in sorted(remotedata, reverse=True):
761 # reverse sort to ensure we end with dump0
761 # reverse sort to ensure we end with dump0
762 data = remotedata[key]
762 data = remotedata[key]
763 rslts.append(remote.pushkey('obsolete', key, '', data))
763 rslts.append(remote.pushkey('obsolete', key, '', data))
764 if [r for r in rslts if not r]:
764 if [r for r in rslts if not r]:
765 msg = _('failed to push some obsolete markers!\n')
765 msg = _('failed to push some obsolete markers!\n')
766 repo.ui.warn(msg)
766 repo.ui.warn(msg)
767
767
768 def _pushbookmark(pushop):
768 def _pushbookmark(pushop):
769 """Update bookmark position on remote"""
769 """Update bookmark position on remote"""
770 if pushop.cgresult == 0 or 'bookmarks' in pushop.stepsdone:
770 if pushop.cgresult == 0 or 'bookmarks' in pushop.stepsdone:
771 return
771 return
772 pushop.stepsdone.add('bookmarks')
772 pushop.stepsdone.add('bookmarks')
773 ui = pushop.ui
773 ui = pushop.ui
774 remote = pushop.remote
774 remote = pushop.remote
775
775
776 for b, old, new in pushop.outbookmarks:
776 for b, old, new in pushop.outbookmarks:
777 action = 'update'
777 action = 'update'
778 if not old:
778 if not old:
779 action = 'export'
779 action = 'export'
780 elif not new:
780 elif not new:
781 action = 'delete'
781 action = 'delete'
782 if remote.pushkey('bookmarks', b, old, new):
782 if remote.pushkey('bookmarks', b, old, new):
783 ui.status(bookmsgmap[action][0] % b)
783 ui.status(bookmsgmap[action][0] % b)
784 else:
784 else:
785 ui.warn(bookmsgmap[action][1] % b)
785 ui.warn(bookmsgmap[action][1] % b)
786 # discovery can have set the value form invalid entry
786 # discovery can have set the value form invalid entry
787 if pushop.bkresult is not None:
787 if pushop.bkresult is not None:
788 pushop.bkresult = 1
788 pushop.bkresult = 1
789
789
790 class pulloperation(object):
790 class pulloperation(object):
791 """A object that represent a single pull operation
791 """A object that represent a single pull operation
792
792
793 It purpose is to carry push related state and very common operation.
793 It purpose is to carry push related state and very common operation.
794
794
795 A new should be created at the beginning of each pull and discarded
795 A new should be created at the beginning of each pull and discarded
796 afterward.
796 afterward.
797 """
797 """
798
798
799 def __init__(self, repo, remote, heads=None, force=False, bookmarks=()):
799 def __init__(self, repo, remote, heads=None, force=False, bookmarks=()):
800 # repo we pull into
800 # repo we pull into
801 self.repo = repo
801 self.repo = repo
802 # repo we pull from
802 # repo we pull from
803 self.remote = remote
803 self.remote = remote
804 # revision we try to pull (None is "all")
804 # revision we try to pull (None is "all")
805 self.heads = heads
805 self.heads = heads
806 # bookmark pulled explicitly
806 # bookmark pulled explicitly
807 self.explicitbookmarks = bookmarks
807 self.explicitbookmarks = bookmarks
808 # do we force pull?
808 # do we force pull?
809 self.force = force
809 self.force = force
810 # the name the pull transaction
810 # the name the pull transaction
811 self._trname = 'pull\n' + util.hidepassword(remote.url())
811 self._trname = 'pull\n' + util.hidepassword(remote.url())
812 # hold the transaction once created
812 # hold the transaction once created
813 self._tr = None
813 self._tr = None
814 # set of common changeset between local and remote before pull
814 # set of common changeset between local and remote before pull
815 self.common = None
815 self.common = None
816 # set of pulled head
816 # set of pulled head
817 self.rheads = None
817 self.rheads = None
818 # list of missing changeset to fetch remotely
818 # list of missing changeset to fetch remotely
819 self.fetch = None
819 self.fetch = None
820 # remote bookmarks data
820 # remote bookmarks data
821 self.remotebookmarks = None
821 self.remotebookmarks = None
822 # result of changegroup pulling (used as return code by pull)
822 # result of changegroup pulling (used as return code by pull)
823 self.cgresult = None
823 self.cgresult = None
824 # list of step already done
824 # list of step already done
825 self.stepsdone = set()
825 self.stepsdone = set()
826
826
827 @util.propertycache
827 @util.propertycache
828 def pulledsubset(self):
828 def pulledsubset(self):
829 """heads of the set of changeset target by the pull"""
829 """heads of the set of changeset target by the pull"""
830 # compute target subset
830 # compute target subset
831 if self.heads is None:
831 if self.heads is None:
832 # We pulled every thing possible
832 # We pulled every thing possible
833 # sync on everything common
833 # sync on everything common
834 c = set(self.common)
834 c = set(self.common)
835 ret = list(self.common)
835 ret = list(self.common)
836 for n in self.rheads:
836 for n in self.rheads:
837 if n not in c:
837 if n not in c:
838 ret.append(n)
838 ret.append(n)
839 return ret
839 return ret
840 else:
840 else:
841 # We pulled a specific subset
841 # We pulled a specific subset
842 # sync on this subset
842 # sync on this subset
843 return self.heads
843 return self.heads
844
844
845 def gettransaction(self):
845 def gettransaction(self):
846 """get appropriate pull transaction, creating it if needed"""
846 """get appropriate pull transaction, creating it if needed"""
847 if self._tr is None:
847 if self._tr is None:
848 self._tr = self.repo.transaction(self._trname)
848 self._tr = self.repo.transaction(self._trname)
849 self._tr.hookargs['source'] = 'pull'
849 self._tr.hookargs['source'] = 'pull'
850 self._tr.hookargs['url'] = self.remote.url()
850 self._tr.hookargs['url'] = self.remote.url()
851 return self._tr
851 return self._tr
852
852
853 def closetransaction(self):
853 def closetransaction(self):
854 """close transaction if created"""
854 """close transaction if created"""
855 if self._tr is not None:
855 if self._tr is not None:
856 repo = self.repo
856 repo = self.repo
857 p = lambda: self._tr.writepending() and repo.root or ""
857 p = lambda: self._tr.writepending() and repo.root or ""
858 repo.hook('b2x-pretransactionclose', throw=True, pending=p,
858 repo.hook('b2x-pretransactionclose', throw=True, pending=p,
859 **self._tr.hookargs)
859 **self._tr.hookargs)
860 self._tr.close()
860 self._tr.close()
861 hookargs = dict(self._tr.hookargs)
861 hookargs = dict(self._tr.hookargs)
862 def runhooks():
862 def runhooks():
863 repo.hook('b2x-transactionclose', **hookargs)
863 repo.hook('b2x-transactionclose', **hookargs)
864 repo._afterlock(runhooks)
864 repo._afterlock(runhooks)
865
865
866 def releasetransaction(self):
866 def releasetransaction(self):
867 """release transaction if created"""
867 """release transaction if created"""
868 if self._tr is not None:
868 if self._tr is not None:
869 self._tr.release()
869 self._tr.release()
870
870
871 def pull(repo, remote, heads=None, force=False, bookmarks=()):
871 def pull(repo, remote, heads=None, force=False, bookmarks=()):
872 pullop = pulloperation(repo, remote, heads, force, bookmarks=bookmarks)
872 pullop = pulloperation(repo, remote, heads, force, bookmarks=bookmarks)
873 if pullop.remote.local():
873 if pullop.remote.local():
874 missing = set(pullop.remote.requirements) - pullop.repo.supported
874 missing = set(pullop.remote.requirements) - pullop.repo.supported
875 if missing:
875 if missing:
876 msg = _("required features are not"
876 msg = _("required features are not"
877 " supported in the destination:"
877 " supported in the destination:"
878 " %s") % (', '.join(sorted(missing)))
878 " %s") % (', '.join(sorted(missing)))
879 raise util.Abort(msg)
879 raise util.Abort(msg)
880
880
881 pullop.remotebookmarks = remote.listkeys('bookmarks')
881 pullop.remotebookmarks = remote.listkeys('bookmarks')
882 lock = pullop.repo.lock()
882 lock = pullop.repo.lock()
883 try:
883 try:
884 _pulldiscovery(pullop)
884 _pulldiscovery(pullop)
885 if (pullop.repo.ui.configbool('experimental', 'bundle2-exp', False)
885 if (pullop.repo.ui.configbool('experimental', 'bundle2-exp', False)
886 and pullop.remote.capable('bundle2-exp')):
886 and pullop.remote.capable('bundle2-exp')):
887 _pullbundle2(pullop)
887 _pullbundle2(pullop)
888 _pullchangeset(pullop)
888 _pullchangeset(pullop)
889 _pullphase(pullop)
889 _pullphase(pullop)
890 _pullbookmarks(pullop)
890 _pullbookmarks(pullop)
891 _pullobsolete(pullop)
891 _pullobsolete(pullop)
892 pullop.closetransaction()
892 pullop.closetransaction()
893 finally:
893 finally:
894 pullop.releasetransaction()
894 pullop.releasetransaction()
895 lock.release()
895 lock.release()
896
896
897 return pullop
897 return pullop
898
898
899 # list of steps to perform discovery before pull
899 # list of steps to perform discovery before pull
900 pulldiscoveryorder = []
900 pulldiscoveryorder = []
901
901
902 # Mapping between step name and function
902 # Mapping between step name and function
903 #
903 #
904 # This exists to help extensions wrap steps if necessary
904 # This exists to help extensions wrap steps if necessary
905 pulldiscoverymapping = {}
905 pulldiscoverymapping = {}
906
906
907 def pulldiscovery(stepname):
907 def pulldiscovery(stepname):
908 """decorator for function performing discovery before pull
908 """decorator for function performing discovery before pull
909
909
910 The function is added to the step -> function mapping and appended to the
910 The function is added to the step -> function mapping and appended to the
911 list of steps. Beware that decorated function will be added in order (this
911 list of steps. Beware that decorated function will be added in order (this
912 may matter).
912 may matter).
913
913
914 You can only use this decorator for a new step, if you want to wrap a step
914 You can only use this decorator for a new step, if you want to wrap a step
915 from an extension, change the pulldiscovery dictionary directly."""
915 from an extension, change the pulldiscovery dictionary directly."""
916 def dec(func):
916 def dec(func):
917 assert stepname not in pulldiscoverymapping
917 assert stepname not in pulldiscoverymapping
918 pulldiscoverymapping[stepname] = func
918 pulldiscoverymapping[stepname] = func
919 pulldiscoveryorder.append(stepname)
919 pulldiscoveryorder.append(stepname)
920 return func
920 return func
921 return dec
921 return dec
922
922
923 def _pulldiscovery(pullop):
923 def _pulldiscovery(pullop):
924 """Run all discovery steps"""
924 """Run all discovery steps"""
925 for stepname in pulldiscoveryorder:
925 for stepname in pulldiscoveryorder:
926 step = pulldiscoverymapping[stepname]
926 step = pulldiscoverymapping[stepname]
927 step(pullop)
927 step(pullop)
928
928
929 @pulldiscovery('changegroup')
929 @pulldiscovery('changegroup')
930 def _pulldiscoverychangegroup(pullop):
930 def _pulldiscoverychangegroup(pullop):
931 """discovery phase for the pull
931 """discovery phase for the pull
932
932
933 Current handle changeset discovery only, will change handle all discovery
933 Current handle changeset discovery only, will change handle all discovery
934 at some point."""
934 at some point."""
935 tmp = discovery.findcommonincoming(pullop.repo.unfiltered(),
935 tmp = discovery.findcommonincoming(pullop.repo.unfiltered(),
936 pullop.remote,
936 pullop.remote,
937 heads=pullop.heads,
937 heads=pullop.heads,
938 force=pullop.force)
938 force=pullop.force)
939 pullop.common, pullop.fetch, pullop.rheads = tmp
939 pullop.common, pullop.fetch, pullop.rheads = tmp
940
940
941 def _pullbundle2(pullop):
941 def _pullbundle2(pullop):
942 """pull data using bundle2
942 """pull data using bundle2
943
943
944 For now, the only supported data are changegroup."""
944 For now, the only supported data are changegroup."""
945 remotecaps = bundle2.bundle2caps(pullop.remote)
945 remotecaps = bundle2.bundle2caps(pullop.remote)
946 kwargs = {'bundlecaps': caps20to10(pullop.repo)}
946 kwargs = {'bundlecaps': caps20to10(pullop.repo)}
947 # pulling changegroup
947 # pulling changegroup
948 pullop.stepsdone.add('changegroup')
948 pullop.stepsdone.add('changegroup')
949
949
950 kwargs['common'] = pullop.common
950 kwargs['common'] = pullop.common
951 kwargs['heads'] = pullop.heads or pullop.rheads
951 kwargs['heads'] = pullop.heads or pullop.rheads
952 kwargs['cg'] = pullop.fetch
952 kwargs['cg'] = pullop.fetch
953 if 'b2x:listkeys' in remotecaps:
953 if 'b2x:listkeys' in remotecaps:
954 kwargs['listkeys'] = ['phase', 'bookmarks']
954 kwargs['listkeys'] = ['phase', 'bookmarks']
955 if not pullop.fetch:
955 if not pullop.fetch:
956 pullop.repo.ui.status(_("no changes found\n"))
956 pullop.repo.ui.status(_("no changes found\n"))
957 pullop.cgresult = 0
957 pullop.cgresult = 0
958 else:
958 else:
959 if pullop.heads is None and list(pullop.common) == [nullid]:
959 if pullop.heads is None and list(pullop.common) == [nullid]:
960 pullop.repo.ui.status(_("requesting all changes\n"))
960 pullop.repo.ui.status(_("requesting all changes\n"))
961 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
961 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
962 remoteversions = bundle2.obsmarkersversion(remotecaps)
962 remoteversions = bundle2.obsmarkersversion(remotecaps)
963 if obsolete.commonversion(remoteversions) is not None:
963 if obsolete.commonversion(remoteversions) is not None:
964 kwargs['obsmarkers'] = True
964 kwargs['obsmarkers'] = True
965 pullop.stepsdone.add('obsmarkers')
965 pullop.stepsdone.add('obsmarkers')
966 _pullbundle2extraprepare(pullop, kwargs)
966 _pullbundle2extraprepare(pullop, kwargs)
967 if kwargs.keys() == ['format']:
967 if kwargs.keys() == ['format']:
968 return # nothing to pull
968 return # nothing to pull
969 bundle = pullop.remote.getbundle('pull', **kwargs)
969 bundle = pullop.remote.getbundle('pull', **kwargs)
970 try:
970 try:
971 op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
971 op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
972 except error.BundleValueError, exc:
972 except error.BundleValueError, exc:
973 raise util.Abort('missing support for %s' % exc)
973 raise util.Abort('missing support for %s' % exc)
974
974
975 if pullop.fetch:
975 if pullop.fetch:
976 changedheads = 0
976 changedheads = 0
977 pullop.cgresult = 1
977 pullop.cgresult = 1
978 for cg in op.records['changegroup']:
978 for cg in op.records['changegroup']:
979 ret = cg['return']
979 ret = cg['return']
980 # If any changegroup result is 0, return 0
980 # If any changegroup result is 0, return 0
981 if ret == 0:
981 if ret == 0:
982 pullop.cgresult = 0
982 pullop.cgresult = 0
983 break
983 break
984 if ret < -1:
984 if ret < -1:
985 changedheads += ret + 1
985 changedheads += ret + 1
986 elif ret > 1:
986 elif ret > 1:
987 changedheads += ret - 1
987 changedheads += ret - 1
988 if changedheads > 0:
988 if changedheads > 0:
989 pullop.cgresult = 1 + changedheads
989 pullop.cgresult = 1 + changedheads
990 elif changedheads < 0:
990 elif changedheads < 0:
991 pullop.cgresult = -1 + changedheads
991 pullop.cgresult = -1 + changedheads
992
992
993 # processing phases change
993 # processing phases change
994 for namespace, value in op.records['listkeys']:
994 for namespace, value in op.records['listkeys']:
995 if namespace == 'phases':
995 if namespace == 'phases':
996 _pullapplyphases(pullop, value)
996 _pullapplyphases(pullop, value)
997
997
998 # processing bookmark update
998 # processing bookmark update
999 for namespace, value in op.records['listkeys']:
999 for namespace, value in op.records['listkeys']:
1000 if namespace == 'bookmarks':
1000 if namespace == 'bookmarks':
1001 pullop.remotebookmarks = value
1001 pullop.remotebookmarks = value
1002 _pullbookmarks(pullop)
1002 _pullbookmarks(pullop)
1003
1003
1004 def _pullbundle2extraprepare(pullop, kwargs):
1004 def _pullbundle2extraprepare(pullop, kwargs):
1005 """hook function so that extensions can extend the getbundle call"""
1005 """hook function so that extensions can extend the getbundle call"""
1006 pass
1006 pass
1007
1007
1008 def _pullchangeset(pullop):
1008 def _pullchangeset(pullop):
1009 """pull changeset from unbundle into the local repo"""
1009 """pull changeset from unbundle into the local repo"""
1010 # We delay the open of the transaction as late as possible so we
1010 # We delay the open of the transaction as late as possible so we
1011 # don't open transaction for nothing or you break future useful
1011 # don't open transaction for nothing or you break future useful
1012 # rollback call
1012 # rollback call
1013 if 'changegroup' in pullop.stepsdone:
1013 if 'changegroup' in pullop.stepsdone:
1014 return
1014 return
1015 pullop.stepsdone.add('changegroup')
1015 pullop.stepsdone.add('changegroup')
1016 if not pullop.fetch:
1016 if not pullop.fetch:
1017 pullop.repo.ui.status(_("no changes found\n"))
1017 pullop.repo.ui.status(_("no changes found\n"))
1018 pullop.cgresult = 0
1018 pullop.cgresult = 0
1019 return
1019 return
1020 pullop.gettransaction()
1020 pullop.gettransaction()
1021 if pullop.heads is None and list(pullop.common) == [nullid]:
1021 if pullop.heads is None and list(pullop.common) == [nullid]:
1022 pullop.repo.ui.status(_("requesting all changes\n"))
1022 pullop.repo.ui.status(_("requesting all changes\n"))
1023 elif pullop.heads is None and pullop.remote.capable('changegroupsubset'):
1023 elif pullop.heads is None and pullop.remote.capable('changegroupsubset'):
1024 # issue1320, avoid a race if remote changed after discovery
1024 # issue1320, avoid a race if remote changed after discovery
1025 pullop.heads = pullop.rheads
1025 pullop.heads = pullop.rheads
1026
1026
1027 if pullop.remote.capable('getbundle'):
1027 if pullop.remote.capable('getbundle'):
1028 # TODO: get bundlecaps from remote
1028 # TODO: get bundlecaps from remote
1029 cg = pullop.remote.getbundle('pull', common=pullop.common,
1029 cg = pullop.remote.getbundle('pull', common=pullop.common,
1030 heads=pullop.heads or pullop.rheads)
1030 heads=pullop.heads or pullop.rheads)
1031 elif pullop.heads is None:
1031 elif pullop.heads is None:
1032 cg = pullop.remote.changegroup(pullop.fetch, 'pull')
1032 cg = pullop.remote.changegroup(pullop.fetch, 'pull')
1033 elif not pullop.remote.capable('changegroupsubset'):
1033 elif not pullop.remote.capable('changegroupsubset'):
1034 raise util.Abort(_("partial pull cannot be done because "
1034 raise util.Abort(_("partial pull cannot be done because "
1035 "other repository doesn't support "
1035 "other repository doesn't support "
1036 "changegroupsubset."))
1036 "changegroupsubset."))
1037 else:
1037 else:
1038 cg = pullop.remote.changegroupsubset(pullop.fetch, pullop.heads, 'pull')
1038 cg = pullop.remote.changegroupsubset(pullop.fetch, pullop.heads, 'pull')
1039 pullop.cgresult = changegroup.addchangegroup(pullop.repo, cg, 'pull',
1039 pullop.cgresult = changegroup.addchangegroup(pullop.repo, cg, 'pull',
1040 pullop.remote.url())
1040 pullop.remote.url())
1041
1041
1042 def _pullphase(pullop):
1042 def _pullphase(pullop):
1043 # Get remote phases data from remote
1043 # Get remote phases data from remote
1044 if 'phases' in pullop.stepsdone:
1044 if 'phases' in pullop.stepsdone:
1045 return
1045 return
1046 remotephases = pullop.remote.listkeys('phases')
1046 remotephases = pullop.remote.listkeys('phases')
1047 _pullapplyphases(pullop, remotephases)
1047 _pullapplyphases(pullop, remotephases)
1048
1048
1049 def _pullapplyphases(pullop, remotephases):
1049 def _pullapplyphases(pullop, remotephases):
1050 """apply phase movement from observed remote state"""
1050 """apply phase movement from observed remote state"""
1051 if 'phases' in pullop.stepsdone:
1051 if 'phases' in pullop.stepsdone:
1052 return
1052 return
1053 pullop.stepsdone.add('phases')
1053 pullop.stepsdone.add('phases')
1054 publishing = bool(remotephases.get('publishing', False))
1054 publishing = bool(remotephases.get('publishing', False))
1055 if remotephases and not publishing:
1055 if remotephases and not publishing:
1056 # remote is new and unpublishing
1056 # remote is new and unpublishing
1057 pheads, _dr = phases.analyzeremotephases(pullop.repo,
1057 pheads, _dr = phases.analyzeremotephases(pullop.repo,
1058 pullop.pulledsubset,
1058 pullop.pulledsubset,
1059 remotephases)
1059 remotephases)
1060 dheads = pullop.pulledsubset
1060 dheads = pullop.pulledsubset
1061 else:
1061 else:
1062 # Remote is old or publishing all common changesets
1062 # Remote is old or publishing all common changesets
1063 # should be seen as public
1063 # should be seen as public
1064 pheads = pullop.pulledsubset
1064 pheads = pullop.pulledsubset
1065 dheads = []
1065 dheads = []
1066 unfi = pullop.repo.unfiltered()
1066 unfi = pullop.repo.unfiltered()
1067 phase = unfi._phasecache.phase
1067 phase = unfi._phasecache.phase
1068 rev = unfi.changelog.nodemap.get
1068 rev = unfi.changelog.nodemap.get
1069 public = phases.public
1069 public = phases.public
1070 draft = phases.draft
1070 draft = phases.draft
1071
1071
1072 # exclude changesets already public locally and update the others
1072 # exclude changesets already public locally and update the others
1073 pheads = [pn for pn in pheads if phase(unfi, rev(pn)) > public]
1073 pheads = [pn for pn in pheads if phase(unfi, rev(pn)) > public]
1074 if pheads:
1074 if pheads:
1075 tr = pullop.gettransaction()
1075 tr = pullop.gettransaction()
1076 phases.advanceboundary(pullop.repo, tr, public, pheads)
1076 phases.advanceboundary(pullop.repo, tr, public, pheads)
1077
1077
1078 # exclude changesets already draft locally and update the others
1078 # exclude changesets already draft locally and update the others
1079 dheads = [pn for pn in dheads if phase(unfi, rev(pn)) > draft]
1079 dheads = [pn for pn in dheads if phase(unfi, rev(pn)) > draft]
1080 if dheads:
1080 if dheads:
1081 tr = pullop.gettransaction()
1081 tr = pullop.gettransaction()
1082 phases.advanceboundary(pullop.repo, tr, draft, dheads)
1082 phases.advanceboundary(pullop.repo, tr, draft, dheads)
1083
1083
1084 def _pullbookmarks(pullop):
1084 def _pullbookmarks(pullop):
1085 """process the remote bookmark information to update the local one"""
1085 """process the remote bookmark information to update the local one"""
1086 if 'bookmarks' in pullop.stepsdone:
1086 if 'bookmarks' in pullop.stepsdone:
1087 return
1087 return
1088 pullop.stepsdone.add('bookmarks')
1088 pullop.stepsdone.add('bookmarks')
1089 repo = pullop.repo
1089 repo = pullop.repo
1090 remotebookmarks = pullop.remotebookmarks
1090 remotebookmarks = pullop.remotebookmarks
1091 bookmod.updatefromremote(repo.ui, repo, remotebookmarks,
1091 bookmod.updatefromremote(repo.ui, repo, remotebookmarks,
1092 pullop.remote.url(),
1092 pullop.remote.url(),
1093 pullop.gettransaction,
1093 pullop.gettransaction,
1094 explicit=pullop.explicitbookmarks)
1094 explicit=pullop.explicitbookmarks)
1095
1095
1096 def _pullobsolete(pullop):
1096 def _pullobsolete(pullop):
1097 """utility function to pull obsolete markers from a remote
1097 """utility function to pull obsolete markers from a remote
1098
1098
1099 The `gettransaction` is function that return the pull transaction, creating
1099 The `gettransaction` is function that return the pull transaction, creating
1100 one if necessary. We return the transaction to inform the calling code that
1100 one if necessary. We return the transaction to inform the calling code that
1101 a new transaction have been created (when applicable).
1101 a new transaction have been created (when applicable).
1102
1102
1103 Exists mostly to allow overriding for experimentation purpose"""
1103 Exists mostly to allow overriding for experimentation purpose"""
1104 if 'obsmarkers' in pullop.stepsdone:
1104 if 'obsmarkers' in pullop.stepsdone:
1105 return
1105 return
1106 pullop.stepsdone.add('obsmarkers')
1106 pullop.stepsdone.add('obsmarkers')
1107 tr = None
1107 tr = None
1108 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1108 if obsolete.isenabled(pullop.repo, obsolete.exchangeopt):
1109 pullop.repo.ui.debug('fetching remote obsolete markers\n')
1109 pullop.repo.ui.debug('fetching remote obsolete markers\n')
1110 remoteobs = pullop.remote.listkeys('obsolete')
1110 remoteobs = pullop.remote.listkeys('obsolete')
1111 if 'dump0' in remoteobs:
1111 if 'dump0' in remoteobs:
1112 tr = pullop.gettransaction()
1112 tr = pullop.gettransaction()
1113 for key in sorted(remoteobs, reverse=True):
1113 for key in sorted(remoteobs, reverse=True):
1114 if key.startswith('dump'):
1114 if key.startswith('dump'):
1115 data = base85.b85decode(remoteobs[key])
1115 data = base85.b85decode(remoteobs[key])
1116 pullop.repo.obsstore.mergemarkers(tr, data)
1116 pullop.repo.obsstore.mergemarkers(tr, data)
1117 pullop.repo.invalidatevolatilesets()
1117 pullop.repo.invalidatevolatilesets()
1118 return tr
1118 return tr
1119
1119
1120 def caps20to10(repo):
1120 def caps20to10(repo):
1121 """return a set with appropriate options to use bundle20 during getbundle"""
1121 """return a set with appropriate options to use bundle20 during getbundle"""
1122 caps = set(['HG2Y'])
1122 caps = set(['HG2Y'])
1123 capsblob = bundle2.encodecaps(bundle2.getrepocaps(repo))
1123 capsblob = bundle2.encodecaps(bundle2.getrepocaps(repo))
1124 caps.add('bundle2=' + urllib.quote(capsblob))
1124 caps.add('bundle2=' + urllib.quote(capsblob))
1125 return caps
1125 return caps
1126
1126
1127 # List of names of steps to perform for a bundle2 for getbundle, order matters.
1127 # List of names of steps to perform for a bundle2 for getbundle, order matters.
1128 getbundle2partsorder = []
1128 getbundle2partsorder = []
1129
1129
1130 # Mapping between step name and function
1130 # Mapping between step name and function
1131 #
1131 #
1132 # This exists to help extensions wrap steps if necessary
1132 # This exists to help extensions wrap steps if necessary
1133 getbundle2partsmapping = {}
1133 getbundle2partsmapping = {}
1134
1134
1135 def getbundle2partsgenerator(stepname):
1135 def getbundle2partsgenerator(stepname):
1136 """decorator for function generating bundle2 part for getbundle
1136 """decorator for function generating bundle2 part for getbundle
1137
1137
1138 The function is added to the step -> function mapping and appended to the
1138 The function is added to the step -> function mapping and appended to the
1139 list of steps. Beware that decorated functions will be added in order
1139 list of steps. Beware that decorated functions will be added in order
1140 (this may matter).
1140 (this may matter).
1141
1141
1142 You can only use this decorator for new steps, if you want to wrap a step
1142 You can only use this decorator for new steps, if you want to wrap a step
1143 from an extension, attack the getbundle2partsmapping dictionary directly."""
1143 from an extension, attack the getbundle2partsmapping dictionary directly."""
1144 def dec(func):
1144 def dec(func):
1145 assert stepname not in getbundle2partsmapping
1145 assert stepname not in getbundle2partsmapping
1146 getbundle2partsmapping[stepname] = func
1146 getbundle2partsmapping[stepname] = func
1147 getbundle2partsorder.append(stepname)
1147 getbundle2partsorder.append(stepname)
1148 return func
1148 return func
1149 return dec
1149 return dec
1150
1150
1151 def getbundle(repo, source, heads=None, common=None, bundlecaps=None,
1151 def getbundle(repo, source, heads=None, common=None, bundlecaps=None,
1152 **kwargs):
1152 **kwargs):
1153 """return a full bundle (with potentially multiple kind of parts)
1153 """return a full bundle (with potentially multiple kind of parts)
1154
1154
1155 Could be a bundle HG10 or a bundle HG2Y depending on bundlecaps
1155 Could be a bundle HG10 or a bundle HG2Y depending on bundlecaps
1156 passed. For now, the bundle can contain only changegroup, but this will
1156 passed. For now, the bundle can contain only changegroup, but this will
1157 changes when more part type will be available for bundle2.
1157 changes when more part type will be available for bundle2.
1158
1158
1159 This is different from changegroup.getchangegroup that only returns an HG10
1159 This is different from changegroup.getchangegroup that only returns an HG10
1160 changegroup bundle. They may eventually get reunited in the future when we
1160 changegroup bundle. They may eventually get reunited in the future when we
1161 have a clearer idea of the API we what to query different data.
1161 have a clearer idea of the API we what to query different data.
1162
1162
1163 The implementation is at a very early stage and will get massive rework
1163 The implementation is at a very early stage and will get massive rework
1164 when the API of bundle is refined.
1164 when the API of bundle is refined.
1165 """
1165 """
1166 # bundle10 case
1166 # bundle10 case
1167 if bundlecaps is None or 'HG2Y' not in bundlecaps:
1167 if bundlecaps is None or 'HG2Y' not in bundlecaps:
1168 if bundlecaps and not kwargs.get('cg', True):
1168 if bundlecaps and not kwargs.get('cg', True):
1169 raise ValueError(_('request for bundle10 must include changegroup'))
1169 raise ValueError(_('request for bundle10 must include changegroup'))
1170
1170
1171 if kwargs:
1171 if kwargs:
1172 raise ValueError(_('unsupported getbundle arguments: %s')
1172 raise ValueError(_('unsupported getbundle arguments: %s')
1173 % ', '.join(sorted(kwargs.keys())))
1173 % ', '.join(sorted(kwargs.keys())))
1174 return changegroup.getchangegroup(repo, source, heads=heads,
1174 return changegroup.getchangegroup(repo, source, heads=heads,
1175 common=common, bundlecaps=bundlecaps)
1175 common=common, bundlecaps=bundlecaps)
1176
1176
1177 # bundle20 case
1177 # bundle20 case
1178 b2caps = {}
1178 b2caps = {}
1179 for bcaps in bundlecaps:
1179 for bcaps in bundlecaps:
1180 if bcaps.startswith('bundle2='):
1180 if bcaps.startswith('bundle2='):
1181 blob = urllib.unquote(bcaps[len('bundle2='):])
1181 blob = urllib.unquote(bcaps[len('bundle2='):])
1182 b2caps.update(bundle2.decodecaps(blob))
1182 b2caps.update(bundle2.decodecaps(blob))
1183 bundler = bundle2.bundle20(repo.ui, b2caps)
1183 bundler = bundle2.bundle20(repo.ui, b2caps)
1184
1184
1185 for name in getbundle2partsorder:
1185 for name in getbundle2partsorder:
1186 func = getbundle2partsmapping[name]
1186 func = getbundle2partsmapping[name]
1187 kwargs['heads'] = heads
1187 kwargs['heads'] = heads
1188 kwargs['common'] = common
1188 kwargs['common'] = common
1189 func(bundler, repo, source, bundlecaps=bundlecaps, b2caps=b2caps,
1189 func(bundler, repo, source, bundlecaps=bundlecaps, b2caps=b2caps,
1190 **kwargs)
1190 **kwargs)
1191
1191
1192 return util.chunkbuffer(bundler.getchunks())
1192 return util.chunkbuffer(bundler.getchunks())
1193
1193
1194 @getbundle2partsgenerator('changegroup')
1194 @getbundle2partsgenerator('changegroup')
1195 def _getbundlechangegrouppart(bundler, repo, source, bundlecaps=None,
1195 def _getbundlechangegrouppart(bundler, repo, source, bundlecaps=None,
1196 b2caps=None, heads=None, common=None, **kwargs):
1196 b2caps=None, heads=None, common=None, **kwargs):
1197 """add a changegroup part to the requested bundle"""
1197 """add a changegroup part to the requested bundle"""
1198 cg = None
1198 cg = None
1199 if kwargs.get('cg', True):
1199 if kwargs.get('cg', True):
1200 # build changegroup bundle here.
1200 # build changegroup bundle here.
1201 version = None
1201 version = None
1202 cgversions = b2caps.get('b2x:changegroup')
1202 cgversions = b2caps.get('b2x:changegroup')
1203 if not cgversions: # 3.1 and 3.2 ship with an empty value
1203 if not cgversions: # 3.1 and 3.2 ship with an empty value
1204 cg = changegroup.getchangegroupraw(repo, source, heads=heads,
1204 cg = changegroup.getchangegroupraw(repo, source, heads=heads,
1205 common=common,
1205 common=common,
1206 bundlecaps=bundlecaps)
1206 bundlecaps=bundlecaps)
1207 else:
1207 else:
1208 cgversions = [v for v in cgversions if v in changegroup.packermap]
1208 cgversions = [v for v in cgversions if v in changegroup.packermap]
1209 if not cgversions:
1209 if not cgversions:
1210 raise ValueError(_('no common changegroup version'))
1210 raise ValueError(_('no common changegroup version'))
1211 version = max(cgversions)
1211 version = max(cgversions)
1212 cg = changegroup.getchangegroupraw(repo, source, heads=heads,
1212 cg = changegroup.getchangegroupraw(repo, source, heads=heads,
1213 common=common,
1213 common=common,
1214 bundlecaps=bundlecaps,
1214 bundlecaps=bundlecaps,
1215 version=version)
1215 version=version)
1216
1216
1217 if cg:
1217 if cg:
1218 part = bundler.newpart('b2x:changegroup', data=cg)
1218 part = bundler.newpart('b2x:changegroup', data=cg)
1219 if version is not None:
1219 if version is not None:
1220 part.addparam('version', version)
1220 part.addparam('version', version)
1221
1221
1222 @getbundle2partsgenerator('listkeys')
1222 @getbundle2partsgenerator('listkeys')
1223 def _getbundlelistkeysparts(bundler, repo, source, bundlecaps=None,
1223 def _getbundlelistkeysparts(bundler, repo, source, bundlecaps=None,
1224 b2caps=None, **kwargs):
1224 b2caps=None, **kwargs):
1225 """add parts containing listkeys namespaces to the requested bundle"""
1225 """add parts containing listkeys namespaces to the requested bundle"""
1226 listkeys = kwargs.get('listkeys', ())
1226 listkeys = kwargs.get('listkeys', ())
1227 for namespace in listkeys:
1227 for namespace in listkeys:
1228 part = bundler.newpart('b2x:listkeys')
1228 part = bundler.newpart('b2x:listkeys')
1229 part.addparam('namespace', namespace)
1229 part.addparam('namespace', namespace)
1230 keys = repo.listkeys(namespace).items()
1230 keys = repo.listkeys(namespace).items()
1231 part.data = pushkey.encodekeys(keys)
1231 part.data = pushkey.encodekeys(keys)
1232
1232
1233 @getbundle2partsgenerator('obsmarkers')
1233 @getbundle2partsgenerator('obsmarkers')
1234 def _getbundleobsmarkerpart(bundler, repo, source, bundlecaps=None,
1234 def _getbundleobsmarkerpart(bundler, repo, source, bundlecaps=None,
1235 b2caps=None, heads=None, **kwargs):
1235 b2caps=None, heads=None, **kwargs):
1236 """add an obsolescence markers part to the requested bundle"""
1236 """add an obsolescence markers part to the requested bundle"""
1237 if kwargs.get('obsmarkers', False):
1237 if kwargs.get('obsmarkers', False):
1238 if heads is None:
1238 if heads is None:
1239 heads = repo.heads()
1239 heads = repo.heads()
1240 subset = [c.node() for c in repo.set('::%ln', heads)]
1240 subset = [c.node() for c in repo.set('::%ln', heads)]
1241 markers = repo.obsstore.relevantmarkers(subset)
1241 markers = repo.obsstore.relevantmarkers(subset)
1242 buildobsmarkerspart(bundler, markers)
1242 buildobsmarkerspart(bundler, markers)
1243
1243
1244 def check_heads(repo, their_heads, context):
1244 def check_heads(repo, their_heads, context):
1245 """check if the heads of a repo have been modified
1245 """check if the heads of a repo have been modified
1246
1246
1247 Used by peer for unbundling.
1247 Used by peer for unbundling.
1248 """
1248 """
1249 heads = repo.heads()
1249 heads = repo.heads()
1250 heads_hash = util.sha1(''.join(sorted(heads))).digest()
1250 heads_hash = util.sha1(''.join(sorted(heads))).digest()
1251 if not (their_heads == ['force'] or their_heads == heads or
1251 if not (their_heads == ['force'] or their_heads == heads or
1252 their_heads == ['hashed', heads_hash]):
1252 their_heads == ['hashed', heads_hash]):
1253 # someone else committed/pushed/unbundled while we
1253 # someone else committed/pushed/unbundled while we
1254 # were transferring data
1254 # were transferring data
1255 raise error.PushRaced('repository changed while %s - '
1255 raise error.PushRaced('repository changed while %s - '
1256 'please try again' % context)
1256 'please try again' % context)
1257
1257
1258 def unbundle(repo, cg, heads, source, url):
1258 def unbundle(repo, cg, heads, source, url):
1259 """Apply a bundle to a repo.
1259 """Apply a bundle to a repo.
1260
1260
1261 this function makes sure the repo is locked during the application and have
1261 this function makes sure the repo is locked during the application and have
1262 mechanism to check that no push race occurred between the creation of the
1262 mechanism to check that no push race occurred between the creation of the
1263 bundle and its application.
1263 bundle and its application.
1264
1264
1265 If the push was raced as PushRaced exception is raised."""
1265 If the push was raced as PushRaced exception is raised."""
1266 r = 0
1266 r = 0
1267 # need a transaction when processing a bundle2 stream
1267 # need a transaction when processing a bundle2 stream
1268 tr = None
1268 tr = None
1269 lock = repo.lock()
1269 lock = repo.lock()
1270 try:
1270 try:
1271 check_heads(repo, heads, 'uploading changes')
1271 check_heads(repo, heads, 'uploading changes')
1272 # push can proceed
1272 # push can proceed
1273 if util.safehasattr(cg, 'params'):
1273 if util.safehasattr(cg, 'params'):
1274 try:
1274 try:
1275 tr = repo.transaction('unbundle')
1275 tr = repo.transaction('unbundle')
1276 tr.hookargs['source'] = source
1276 tr.hookargs['source'] = source
1277 tr.hookargs['url'] = url
1277 tr.hookargs['url'] = url
1278 tr.hookargs['bundle2-exp'] = '1'
1278 tr.hookargs['bundle2-exp'] = '1'
1279 r = bundle2.processbundle(repo, cg, lambda: tr).reply
1279 r = bundle2.processbundle(repo, cg, lambda: tr).reply
1280 p = lambda: tr.writepending() and repo.root or ""
1280 p = lambda: tr.writepending() and repo.root or ""
1281 repo.hook('b2x-pretransactionclose', throw=True, pending=p,
1281 repo.hook('b2x-pretransactionclose', throw=True, pending=p,
1282 **tr.hookargs)
1282 **tr.hookargs)
1283 tr.close()
1283 tr.close()
1284 hookargs = dict(tr.hookargs)
1284 hookargs = dict(tr.hookargs)
1285 def runhooks():
1285 def runhooks():
1286 repo.hook('b2x-transactionclose', **hookargs)
1286 repo.hook('b2x-transactionclose', **hookargs)
1287 repo._afterlock(runhooks)
1287 repo._afterlock(runhooks)
1288 except Exception, exc:
1288 except Exception, exc:
1289 exc.duringunbundle2 = True
1289 exc.duringunbundle2 = True
1290 raise
1290 raise
1291 else:
1291 else:
1292 r = changegroup.addchangegroup(repo, cg, source, url)
1292 r = changegroup.addchangegroup(repo, cg, source, url)
1293 finally:
1293 finally:
1294 if tr is not None:
1294 if tr is not None:
1295 tr.release()
1295 tr.release()
1296 lock.release()
1296 lock.release()
1297 return r
1297 return r
General Comments 0
You need to be logged in to leave comments. Login now