##// END OF EJS Templates
changegroup: move generate() modifications from narrow...
Gregory Szorc -
r38926:d706c774 default
parent child Browse files
Show More
@@ -1,90 +1,88 b''
1 # __init__.py - narrowhg extension
1 # __init__.py - narrowhg extension
2 #
2 #
3 # Copyright 2017 Google, Inc.
3 # Copyright 2017 Google, Inc.
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 '''create clones which fetch history data for subset of files (EXPERIMENTAL)'''
7 '''create clones which fetch history data for subset of files (EXPERIMENTAL)'''
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
11 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
12 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
12 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
13 # be specifying the version(s) of Mercurial they are tested with, or
13 # be specifying the version(s) of Mercurial they are tested with, or
14 # leave the attribute unspecified.
14 # leave the attribute unspecified.
15 testedwith = 'ships-with-hg-core'
15 testedwith = 'ships-with-hg-core'
16
16
17 from mercurial import (
17 from mercurial import (
18 extensions,
18 extensions,
19 localrepo,
19 localrepo,
20 registrar,
20 registrar,
21 repository,
21 repository,
22 verify as verifymod,
22 verify as verifymod,
23 )
23 )
24
24
25 from . import (
25 from . import (
26 narrowbundle2,
26 narrowbundle2,
27 narrowchangegroup,
28 narrowcommands,
27 narrowcommands,
29 narrowcopies,
28 narrowcopies,
30 narrowpatch,
29 narrowpatch,
31 narrowrepo,
30 narrowrepo,
32 narrowrevlog,
31 narrowrevlog,
33 narrowtemplates,
32 narrowtemplates,
34 narrowwirepeer,
33 narrowwirepeer,
35 )
34 )
36
35
37 configtable = {}
36 configtable = {}
38 configitem = registrar.configitem(configtable)
37 configitem = registrar.configitem(configtable)
39 # Narrowhg *has* support for serving ellipsis nodes (which are used at
38 # Narrowhg *has* support for serving ellipsis nodes (which are used at
40 # least by Google's internal server), but that support is pretty
39 # least by Google's internal server), but that support is pretty
41 # fragile and has a lot of problems on real-world repositories that
40 # fragile and has a lot of problems on real-world repositories that
42 # have complex graph topologies. This could probably be corrected, but
41 # have complex graph topologies. This could probably be corrected, but
43 # absent someone needing the full support for ellipsis nodes in
42 # absent someone needing the full support for ellipsis nodes in
44 # repositories with merges, it's unlikely this work will get done. As
43 # repositories with merges, it's unlikely this work will get done. As
45 # of this writining in late 2017, all repositories large enough for
44 # of this writining in late 2017, all repositories large enough for
46 # ellipsis nodes to be a hard requirement also enforce strictly linear
45 # ellipsis nodes to be a hard requirement also enforce strictly linear
47 # history for other scaling reasons.
46 # history for other scaling reasons.
48 configitem('experimental', 'narrowservebrokenellipses',
47 configitem('experimental', 'narrowservebrokenellipses',
49 default=False,
48 default=False,
50 alias=[('narrow', 'serveellipses')],
49 alias=[('narrow', 'serveellipses')],
51 )
50 )
52
51
53 # Export the commands table for Mercurial to see.
52 # Export the commands table for Mercurial to see.
54 cmdtable = narrowcommands.table
53 cmdtable = narrowcommands.table
55
54
56 def featuresetup(ui, features):
55 def featuresetup(ui, features):
57 features.add(repository.NARROW_REQUIREMENT)
56 features.add(repository.NARROW_REQUIREMENT)
58
57
59 def uisetup(ui):
58 def uisetup(ui):
60 """Wraps user-facing mercurial commands with narrow-aware versions."""
59 """Wraps user-facing mercurial commands with narrow-aware versions."""
61 localrepo.featuresetupfuncs.add(featuresetup)
60 localrepo.featuresetupfuncs.add(featuresetup)
62 narrowrevlog.setup()
61 narrowrevlog.setup()
63 narrowbundle2.setup()
62 narrowbundle2.setup()
64 narrowcommands.setup()
63 narrowcommands.setup()
65 narrowchangegroup.setup()
66 narrowwirepeer.uisetup()
64 narrowwirepeer.uisetup()
67
65
68 def reposetup(ui, repo):
66 def reposetup(ui, repo):
69 """Wraps local repositories with narrow repo support."""
67 """Wraps local repositories with narrow repo support."""
70 if not repo.local():
68 if not repo.local():
71 return
69 return
72
70
73 if repository.NARROW_REQUIREMENT in repo.requirements:
71 if repository.NARROW_REQUIREMENT in repo.requirements:
74 narrowrepo.wraprepo(repo)
72 narrowrepo.wraprepo(repo)
75 narrowcopies.setup(repo)
73 narrowcopies.setup(repo)
76 narrowpatch.setup(repo)
74 narrowpatch.setup(repo)
77 narrowwirepeer.reposetup(repo)
75 narrowwirepeer.reposetup(repo)
78
76
79 def _verifierinit(orig, self, repo, matcher=None):
77 def _verifierinit(orig, self, repo, matcher=None):
80 # The verifier's matcher argument was desgined for narrowhg, so it should
78 # The verifier's matcher argument was desgined for narrowhg, so it should
81 # be None from core. If another extension passes a matcher (unlikely),
79 # be None from core. If another extension passes a matcher (unlikely),
82 # we'll have to fail until matchers can be composed more easily.
80 # we'll have to fail until matchers can be composed more easily.
83 assert matcher is None
81 assert matcher is None
84 orig(self, repo, repo.narrowmatch())
82 orig(self, repo, repo.narrowmatch())
85
83
86 def extsetup(ui):
84 def extsetup(ui):
87 extensions.wrapfunction(verifymod.verifier, '__init__', _verifierinit)
85 extensions.wrapfunction(verifymod.verifier, '__init__', _verifierinit)
88
86
89 templatekeyword = narrowtemplates.templatekeyword
87 templatekeyword = narrowtemplates.templatekeyword
90 revsetpredicate = narrowtemplates.revsetpredicate
88 revsetpredicate = narrowtemplates.revsetpredicate
@@ -1,1284 +1,1331 b''
1 # changegroup.py - Mercurial changegroup manipulation functions
1 # changegroup.py - Mercurial changegroup manipulation functions
2 #
2 #
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 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 os
10 import os
11 import struct
11 import struct
12 import weakref
12 import weakref
13
13
14 from .i18n import _
14 from .i18n import _
15 from .node import (
15 from .node import (
16 hex,
16 hex,
17 nullid,
17 nullid,
18 nullrev,
18 nullrev,
19 short,
19 short,
20 )
20 )
21
21
22 from . import (
22 from . import (
23 dagutil,
23 dagutil,
24 error,
24 error,
25 manifest,
25 manifest,
26 match as matchmod,
26 match as matchmod,
27 mdiff,
27 mdiff,
28 phases,
28 phases,
29 pycompat,
29 pycompat,
30 repository,
30 repository,
31 revlog,
31 revlog,
32 util,
32 util,
33 )
33 )
34
34
35 from .utils import (
35 from .utils import (
36 stringutil,
36 stringutil,
37 )
37 )
38
38
39 _CHANGEGROUPV1_DELTA_HEADER = "20s20s20s20s"
39 _CHANGEGROUPV1_DELTA_HEADER = "20s20s20s20s"
40 _CHANGEGROUPV2_DELTA_HEADER = "20s20s20s20s20s"
40 _CHANGEGROUPV2_DELTA_HEADER = "20s20s20s20s20s"
41 _CHANGEGROUPV3_DELTA_HEADER = ">20s20s20s20s20sH"
41 _CHANGEGROUPV3_DELTA_HEADER = ">20s20s20s20s20sH"
42
42
43 LFS_REQUIREMENT = 'lfs'
43 LFS_REQUIREMENT = 'lfs'
44
44
45 readexactly = util.readexactly
45 readexactly = util.readexactly
46
46
47 def getchunk(stream):
47 def getchunk(stream):
48 """return the next chunk from stream as a string"""
48 """return the next chunk from stream as a string"""
49 d = readexactly(stream, 4)
49 d = readexactly(stream, 4)
50 l = struct.unpack(">l", d)[0]
50 l = struct.unpack(">l", d)[0]
51 if l <= 4:
51 if l <= 4:
52 if l:
52 if l:
53 raise error.Abort(_("invalid chunk length %d") % l)
53 raise error.Abort(_("invalid chunk length %d") % l)
54 return ""
54 return ""
55 return readexactly(stream, l - 4)
55 return readexactly(stream, l - 4)
56
56
57 def chunkheader(length):
57 def chunkheader(length):
58 """return a changegroup chunk header (string)"""
58 """return a changegroup chunk header (string)"""
59 return struct.pack(">l", length + 4)
59 return struct.pack(">l", length + 4)
60
60
61 def closechunk():
61 def closechunk():
62 """return a changegroup chunk header (string) for a zero-length chunk"""
62 """return a changegroup chunk header (string) for a zero-length chunk"""
63 return struct.pack(">l", 0)
63 return struct.pack(">l", 0)
64
64
65 def writechunks(ui, chunks, filename, vfs=None):
65 def writechunks(ui, chunks, filename, vfs=None):
66 """Write chunks to a file and return its filename.
66 """Write chunks to a file and return its filename.
67
67
68 The stream is assumed to be a bundle file.
68 The stream is assumed to be a bundle file.
69 Existing files will not be overwritten.
69 Existing files will not be overwritten.
70 If no filename is specified, a temporary file is created.
70 If no filename is specified, a temporary file is created.
71 """
71 """
72 fh = None
72 fh = None
73 cleanup = None
73 cleanup = None
74 try:
74 try:
75 if filename:
75 if filename:
76 if vfs:
76 if vfs:
77 fh = vfs.open(filename, "wb")
77 fh = vfs.open(filename, "wb")
78 else:
78 else:
79 # Increase default buffer size because default is usually
79 # Increase default buffer size because default is usually
80 # small (4k is common on Linux).
80 # small (4k is common on Linux).
81 fh = open(filename, "wb", 131072)
81 fh = open(filename, "wb", 131072)
82 else:
82 else:
83 fd, filename = pycompat.mkstemp(prefix="hg-bundle-", suffix=".hg")
83 fd, filename = pycompat.mkstemp(prefix="hg-bundle-", suffix=".hg")
84 fh = os.fdopen(fd, r"wb")
84 fh = os.fdopen(fd, r"wb")
85 cleanup = filename
85 cleanup = filename
86 for c in chunks:
86 for c in chunks:
87 fh.write(c)
87 fh.write(c)
88 cleanup = None
88 cleanup = None
89 return filename
89 return filename
90 finally:
90 finally:
91 if fh is not None:
91 if fh is not None:
92 fh.close()
92 fh.close()
93 if cleanup is not None:
93 if cleanup is not None:
94 if filename and vfs:
94 if filename and vfs:
95 vfs.unlink(cleanup)
95 vfs.unlink(cleanup)
96 else:
96 else:
97 os.unlink(cleanup)
97 os.unlink(cleanup)
98
98
99 class cg1unpacker(object):
99 class cg1unpacker(object):
100 """Unpacker for cg1 changegroup streams.
100 """Unpacker for cg1 changegroup streams.
101
101
102 A changegroup unpacker handles the framing of the revision data in
102 A changegroup unpacker handles the framing of the revision data in
103 the wire format. Most consumers will want to use the apply()
103 the wire format. Most consumers will want to use the apply()
104 method to add the changes from the changegroup to a repository.
104 method to add the changes from the changegroup to a repository.
105
105
106 If you're forwarding a changegroup unmodified to another consumer,
106 If you're forwarding a changegroup unmodified to another consumer,
107 use getchunks(), which returns an iterator of changegroup
107 use getchunks(), which returns an iterator of changegroup
108 chunks. This is mostly useful for cases where you need to know the
108 chunks. This is mostly useful for cases where you need to know the
109 data stream has ended by observing the end of the changegroup.
109 data stream has ended by observing the end of the changegroup.
110
110
111 deltachunk() is useful only if you're applying delta data. Most
111 deltachunk() is useful only if you're applying delta data. Most
112 consumers should prefer apply() instead.
112 consumers should prefer apply() instead.
113
113
114 A few other public methods exist. Those are used only for
114 A few other public methods exist. Those are used only for
115 bundlerepo and some debug commands - their use is discouraged.
115 bundlerepo and some debug commands - their use is discouraged.
116 """
116 """
117 deltaheader = _CHANGEGROUPV1_DELTA_HEADER
117 deltaheader = _CHANGEGROUPV1_DELTA_HEADER
118 deltaheadersize = struct.calcsize(deltaheader)
118 deltaheadersize = struct.calcsize(deltaheader)
119 version = '01'
119 version = '01'
120 _grouplistcount = 1 # One list of files after the manifests
120 _grouplistcount = 1 # One list of files after the manifests
121
121
122 def __init__(self, fh, alg, extras=None):
122 def __init__(self, fh, alg, extras=None):
123 if alg is None:
123 if alg is None:
124 alg = 'UN'
124 alg = 'UN'
125 if alg not in util.compengines.supportedbundletypes:
125 if alg not in util.compengines.supportedbundletypes:
126 raise error.Abort(_('unknown stream compression type: %s')
126 raise error.Abort(_('unknown stream compression type: %s')
127 % alg)
127 % alg)
128 if alg == 'BZ':
128 if alg == 'BZ':
129 alg = '_truncatedBZ'
129 alg = '_truncatedBZ'
130
130
131 compengine = util.compengines.forbundletype(alg)
131 compengine = util.compengines.forbundletype(alg)
132 self._stream = compengine.decompressorreader(fh)
132 self._stream = compengine.decompressorreader(fh)
133 self._type = alg
133 self._type = alg
134 self.extras = extras or {}
134 self.extras = extras or {}
135 self.callback = None
135 self.callback = None
136
136
137 # These methods (compressed, read, seek, tell) all appear to only
137 # These methods (compressed, read, seek, tell) all appear to only
138 # be used by bundlerepo, but it's a little hard to tell.
138 # be used by bundlerepo, but it's a little hard to tell.
139 def compressed(self):
139 def compressed(self):
140 return self._type is not None and self._type != 'UN'
140 return self._type is not None and self._type != 'UN'
141 def read(self, l):
141 def read(self, l):
142 return self._stream.read(l)
142 return self._stream.read(l)
143 def seek(self, pos):
143 def seek(self, pos):
144 return self._stream.seek(pos)
144 return self._stream.seek(pos)
145 def tell(self):
145 def tell(self):
146 return self._stream.tell()
146 return self._stream.tell()
147 def close(self):
147 def close(self):
148 return self._stream.close()
148 return self._stream.close()
149
149
150 def _chunklength(self):
150 def _chunklength(self):
151 d = readexactly(self._stream, 4)
151 d = readexactly(self._stream, 4)
152 l = struct.unpack(">l", d)[0]
152 l = struct.unpack(">l", d)[0]
153 if l <= 4:
153 if l <= 4:
154 if l:
154 if l:
155 raise error.Abort(_("invalid chunk length %d") % l)
155 raise error.Abort(_("invalid chunk length %d") % l)
156 return 0
156 return 0
157 if self.callback:
157 if self.callback:
158 self.callback()
158 self.callback()
159 return l - 4
159 return l - 4
160
160
161 def changelogheader(self):
161 def changelogheader(self):
162 """v10 does not have a changelog header chunk"""
162 """v10 does not have a changelog header chunk"""
163 return {}
163 return {}
164
164
165 def manifestheader(self):
165 def manifestheader(self):
166 """v10 does not have a manifest header chunk"""
166 """v10 does not have a manifest header chunk"""
167 return {}
167 return {}
168
168
169 def filelogheader(self):
169 def filelogheader(self):
170 """return the header of the filelogs chunk, v10 only has the filename"""
170 """return the header of the filelogs chunk, v10 only has the filename"""
171 l = self._chunklength()
171 l = self._chunklength()
172 if not l:
172 if not l:
173 return {}
173 return {}
174 fname = readexactly(self._stream, l)
174 fname = readexactly(self._stream, l)
175 return {'filename': fname}
175 return {'filename': fname}
176
176
177 def _deltaheader(self, headertuple, prevnode):
177 def _deltaheader(self, headertuple, prevnode):
178 node, p1, p2, cs = headertuple
178 node, p1, p2, cs = headertuple
179 if prevnode is None:
179 if prevnode is None:
180 deltabase = p1
180 deltabase = p1
181 else:
181 else:
182 deltabase = prevnode
182 deltabase = prevnode
183 flags = 0
183 flags = 0
184 return node, p1, p2, deltabase, cs, flags
184 return node, p1, p2, deltabase, cs, flags
185
185
186 def deltachunk(self, prevnode):
186 def deltachunk(self, prevnode):
187 l = self._chunklength()
187 l = self._chunklength()
188 if not l:
188 if not l:
189 return {}
189 return {}
190 headerdata = readexactly(self._stream, self.deltaheadersize)
190 headerdata = readexactly(self._stream, self.deltaheadersize)
191 header = struct.unpack(self.deltaheader, headerdata)
191 header = struct.unpack(self.deltaheader, headerdata)
192 delta = readexactly(self._stream, l - self.deltaheadersize)
192 delta = readexactly(self._stream, l - self.deltaheadersize)
193 node, p1, p2, deltabase, cs, flags = self._deltaheader(header, prevnode)
193 node, p1, p2, deltabase, cs, flags = self._deltaheader(header, prevnode)
194 return (node, p1, p2, cs, deltabase, delta, flags)
194 return (node, p1, p2, cs, deltabase, delta, flags)
195
195
196 def getchunks(self):
196 def getchunks(self):
197 """returns all the chunks contains in the bundle
197 """returns all the chunks contains in the bundle
198
198
199 Used when you need to forward the binary stream to a file or another
199 Used when you need to forward the binary stream to a file or another
200 network API. To do so, it parse the changegroup data, otherwise it will
200 network API. To do so, it parse the changegroup data, otherwise it will
201 block in case of sshrepo because it don't know the end of the stream.
201 block in case of sshrepo because it don't know the end of the stream.
202 """
202 """
203 # For changegroup 1 and 2, we expect 3 parts: changelog, manifestlog,
203 # For changegroup 1 and 2, we expect 3 parts: changelog, manifestlog,
204 # and a list of filelogs. For changegroup 3, we expect 4 parts:
204 # and a list of filelogs. For changegroup 3, we expect 4 parts:
205 # changelog, manifestlog, a list of tree manifestlogs, and a list of
205 # changelog, manifestlog, a list of tree manifestlogs, and a list of
206 # filelogs.
206 # filelogs.
207 #
207 #
208 # Changelog and manifestlog parts are terminated with empty chunks. The
208 # Changelog and manifestlog parts are terminated with empty chunks. The
209 # tree and file parts are a list of entry sections. Each entry section
209 # tree and file parts are a list of entry sections. Each entry section
210 # is a series of chunks terminating in an empty chunk. The list of these
210 # is a series of chunks terminating in an empty chunk. The list of these
211 # entry sections is terminated in yet another empty chunk, so we know
211 # entry sections is terminated in yet another empty chunk, so we know
212 # we've reached the end of the tree/file list when we reach an empty
212 # we've reached the end of the tree/file list when we reach an empty
213 # chunk that was proceeded by no non-empty chunks.
213 # chunk that was proceeded by no non-empty chunks.
214
214
215 parts = 0
215 parts = 0
216 while parts < 2 + self._grouplistcount:
216 while parts < 2 + self._grouplistcount:
217 noentries = True
217 noentries = True
218 while True:
218 while True:
219 chunk = getchunk(self)
219 chunk = getchunk(self)
220 if not chunk:
220 if not chunk:
221 # The first two empty chunks represent the end of the
221 # The first two empty chunks represent the end of the
222 # changelog and the manifestlog portions. The remaining
222 # changelog and the manifestlog portions. The remaining
223 # empty chunks represent either A) the end of individual
223 # empty chunks represent either A) the end of individual
224 # tree or file entries in the file list, or B) the end of
224 # tree or file entries in the file list, or B) the end of
225 # the entire list. It's the end of the entire list if there
225 # the entire list. It's the end of the entire list if there
226 # were no entries (i.e. noentries is True).
226 # were no entries (i.e. noentries is True).
227 if parts < 2:
227 if parts < 2:
228 parts += 1
228 parts += 1
229 elif noentries:
229 elif noentries:
230 parts += 1
230 parts += 1
231 break
231 break
232 noentries = False
232 noentries = False
233 yield chunkheader(len(chunk))
233 yield chunkheader(len(chunk))
234 pos = 0
234 pos = 0
235 while pos < len(chunk):
235 while pos < len(chunk):
236 next = pos + 2**20
236 next = pos + 2**20
237 yield chunk[pos:next]
237 yield chunk[pos:next]
238 pos = next
238 pos = next
239 yield closechunk()
239 yield closechunk()
240
240
241 def _unpackmanifests(self, repo, revmap, trp, prog):
241 def _unpackmanifests(self, repo, revmap, trp, prog):
242 self.callback = prog.increment
242 self.callback = prog.increment
243 # no need to check for empty manifest group here:
243 # no need to check for empty manifest group here:
244 # if the result of the merge of 1 and 2 is the same in 3 and 4,
244 # if the result of the merge of 1 and 2 is the same in 3 and 4,
245 # no new manifest will be created and the manifest group will
245 # no new manifest will be created and the manifest group will
246 # be empty during the pull
246 # be empty during the pull
247 self.manifestheader()
247 self.manifestheader()
248 deltas = self.deltaiter()
248 deltas = self.deltaiter()
249 repo.manifestlog.addgroup(deltas, revmap, trp)
249 repo.manifestlog.addgroup(deltas, revmap, trp)
250 prog.complete()
250 prog.complete()
251 self.callback = None
251 self.callback = None
252
252
253 def apply(self, repo, tr, srctype, url, targetphase=phases.draft,
253 def apply(self, repo, tr, srctype, url, targetphase=phases.draft,
254 expectedtotal=None):
254 expectedtotal=None):
255 """Add the changegroup returned by source.read() to this repo.
255 """Add the changegroup returned by source.read() to this repo.
256 srctype is a string like 'push', 'pull', or 'unbundle'. url is
256 srctype is a string like 'push', 'pull', or 'unbundle'. url is
257 the URL of the repo where this changegroup is coming from.
257 the URL of the repo where this changegroup is coming from.
258
258
259 Return an integer summarizing the change to this repo:
259 Return an integer summarizing the change to this repo:
260 - nothing changed or no source: 0
260 - nothing changed or no source: 0
261 - more heads than before: 1+added heads (2..n)
261 - more heads than before: 1+added heads (2..n)
262 - fewer heads than before: -1-removed heads (-2..-n)
262 - fewer heads than before: -1-removed heads (-2..-n)
263 - number of heads stays the same: 1
263 - number of heads stays the same: 1
264 """
264 """
265 repo = repo.unfiltered()
265 repo = repo.unfiltered()
266 def csmap(x):
266 def csmap(x):
267 repo.ui.debug("add changeset %s\n" % short(x))
267 repo.ui.debug("add changeset %s\n" % short(x))
268 return len(cl)
268 return len(cl)
269
269
270 def revmap(x):
270 def revmap(x):
271 return cl.rev(x)
271 return cl.rev(x)
272
272
273 changesets = files = revisions = 0
273 changesets = files = revisions = 0
274
274
275 try:
275 try:
276 # The transaction may already carry source information. In this
276 # The transaction may already carry source information. In this
277 # case we use the top level data. We overwrite the argument
277 # case we use the top level data. We overwrite the argument
278 # because we need to use the top level value (if they exist)
278 # because we need to use the top level value (if they exist)
279 # in this function.
279 # in this function.
280 srctype = tr.hookargs.setdefault('source', srctype)
280 srctype = tr.hookargs.setdefault('source', srctype)
281 url = tr.hookargs.setdefault('url', url)
281 url = tr.hookargs.setdefault('url', url)
282 repo.hook('prechangegroup',
282 repo.hook('prechangegroup',
283 throw=True, **pycompat.strkwargs(tr.hookargs))
283 throw=True, **pycompat.strkwargs(tr.hookargs))
284
284
285 # write changelog data to temp files so concurrent readers
285 # write changelog data to temp files so concurrent readers
286 # will not see an inconsistent view
286 # will not see an inconsistent view
287 cl = repo.changelog
287 cl = repo.changelog
288 cl.delayupdate(tr)
288 cl.delayupdate(tr)
289 oldheads = set(cl.heads())
289 oldheads = set(cl.heads())
290
290
291 trp = weakref.proxy(tr)
291 trp = weakref.proxy(tr)
292 # pull off the changeset group
292 # pull off the changeset group
293 repo.ui.status(_("adding changesets\n"))
293 repo.ui.status(_("adding changesets\n"))
294 clstart = len(cl)
294 clstart = len(cl)
295 progress = repo.ui.makeprogress(_('changesets'), unit=_('chunks'),
295 progress = repo.ui.makeprogress(_('changesets'), unit=_('chunks'),
296 total=expectedtotal)
296 total=expectedtotal)
297 self.callback = progress.increment
297 self.callback = progress.increment
298
298
299 efiles = set()
299 efiles = set()
300 def onchangelog(cl, node):
300 def onchangelog(cl, node):
301 efiles.update(cl.readfiles(node))
301 efiles.update(cl.readfiles(node))
302
302
303 self.changelogheader()
303 self.changelogheader()
304 deltas = self.deltaiter()
304 deltas = self.deltaiter()
305 cgnodes = cl.addgroup(deltas, csmap, trp, addrevisioncb=onchangelog)
305 cgnodes = cl.addgroup(deltas, csmap, trp, addrevisioncb=onchangelog)
306 efiles = len(efiles)
306 efiles = len(efiles)
307
307
308 if not cgnodes:
308 if not cgnodes:
309 repo.ui.develwarn('applied empty changegroup',
309 repo.ui.develwarn('applied empty changegroup',
310 config='warn-empty-changegroup')
310 config='warn-empty-changegroup')
311 clend = len(cl)
311 clend = len(cl)
312 changesets = clend - clstart
312 changesets = clend - clstart
313 progress.complete()
313 progress.complete()
314 self.callback = None
314 self.callback = None
315
315
316 # pull off the manifest group
316 # pull off the manifest group
317 repo.ui.status(_("adding manifests\n"))
317 repo.ui.status(_("adding manifests\n"))
318 # We know that we'll never have more manifests than we had
318 # We know that we'll never have more manifests than we had
319 # changesets.
319 # changesets.
320 progress = repo.ui.makeprogress(_('manifests'), unit=_('chunks'),
320 progress = repo.ui.makeprogress(_('manifests'), unit=_('chunks'),
321 total=changesets)
321 total=changesets)
322 self._unpackmanifests(repo, revmap, trp, progress)
322 self._unpackmanifests(repo, revmap, trp, progress)
323
323
324 needfiles = {}
324 needfiles = {}
325 if repo.ui.configbool('server', 'validate'):
325 if repo.ui.configbool('server', 'validate'):
326 cl = repo.changelog
326 cl = repo.changelog
327 ml = repo.manifestlog
327 ml = repo.manifestlog
328 # validate incoming csets have their manifests
328 # validate incoming csets have their manifests
329 for cset in pycompat.xrange(clstart, clend):
329 for cset in pycompat.xrange(clstart, clend):
330 mfnode = cl.changelogrevision(cset).manifest
330 mfnode = cl.changelogrevision(cset).manifest
331 mfest = ml[mfnode].readdelta()
331 mfest = ml[mfnode].readdelta()
332 # store file cgnodes we must see
332 # store file cgnodes we must see
333 for f, n in mfest.iteritems():
333 for f, n in mfest.iteritems():
334 needfiles.setdefault(f, set()).add(n)
334 needfiles.setdefault(f, set()).add(n)
335
335
336 # process the files
336 # process the files
337 repo.ui.status(_("adding file changes\n"))
337 repo.ui.status(_("adding file changes\n"))
338 newrevs, newfiles = _addchangegroupfiles(
338 newrevs, newfiles = _addchangegroupfiles(
339 repo, self, revmap, trp, efiles, needfiles)
339 repo, self, revmap, trp, efiles, needfiles)
340 revisions += newrevs
340 revisions += newrevs
341 files += newfiles
341 files += newfiles
342
342
343 deltaheads = 0
343 deltaheads = 0
344 if oldheads:
344 if oldheads:
345 heads = cl.heads()
345 heads = cl.heads()
346 deltaheads = len(heads) - len(oldheads)
346 deltaheads = len(heads) - len(oldheads)
347 for h in heads:
347 for h in heads:
348 if h not in oldheads and repo[h].closesbranch():
348 if h not in oldheads and repo[h].closesbranch():
349 deltaheads -= 1
349 deltaheads -= 1
350 htext = ""
350 htext = ""
351 if deltaheads:
351 if deltaheads:
352 htext = _(" (%+d heads)") % deltaheads
352 htext = _(" (%+d heads)") % deltaheads
353
353
354 repo.ui.status(_("added %d changesets"
354 repo.ui.status(_("added %d changesets"
355 " with %d changes to %d files%s\n")
355 " with %d changes to %d files%s\n")
356 % (changesets, revisions, files, htext))
356 % (changesets, revisions, files, htext))
357 repo.invalidatevolatilesets()
357 repo.invalidatevolatilesets()
358
358
359 if changesets > 0:
359 if changesets > 0:
360 if 'node' not in tr.hookargs:
360 if 'node' not in tr.hookargs:
361 tr.hookargs['node'] = hex(cl.node(clstart))
361 tr.hookargs['node'] = hex(cl.node(clstart))
362 tr.hookargs['node_last'] = hex(cl.node(clend - 1))
362 tr.hookargs['node_last'] = hex(cl.node(clend - 1))
363 hookargs = dict(tr.hookargs)
363 hookargs = dict(tr.hookargs)
364 else:
364 else:
365 hookargs = dict(tr.hookargs)
365 hookargs = dict(tr.hookargs)
366 hookargs['node'] = hex(cl.node(clstart))
366 hookargs['node'] = hex(cl.node(clstart))
367 hookargs['node_last'] = hex(cl.node(clend - 1))
367 hookargs['node_last'] = hex(cl.node(clend - 1))
368 repo.hook('pretxnchangegroup',
368 repo.hook('pretxnchangegroup',
369 throw=True, **pycompat.strkwargs(hookargs))
369 throw=True, **pycompat.strkwargs(hookargs))
370
370
371 added = [cl.node(r) for r in pycompat.xrange(clstart, clend)]
371 added = [cl.node(r) for r in pycompat.xrange(clstart, clend)]
372 phaseall = None
372 phaseall = None
373 if srctype in ('push', 'serve'):
373 if srctype in ('push', 'serve'):
374 # Old servers can not push the boundary themselves.
374 # Old servers can not push the boundary themselves.
375 # New servers won't push the boundary if changeset already
375 # New servers won't push the boundary if changeset already
376 # exists locally as secret
376 # exists locally as secret
377 #
377 #
378 # We should not use added here but the list of all change in
378 # We should not use added here but the list of all change in
379 # the bundle
379 # the bundle
380 if repo.publishing():
380 if repo.publishing():
381 targetphase = phaseall = phases.public
381 targetphase = phaseall = phases.public
382 else:
382 else:
383 # closer target phase computation
383 # closer target phase computation
384
384
385 # Those changesets have been pushed from the
385 # Those changesets have been pushed from the
386 # outside, their phases are going to be pushed
386 # outside, their phases are going to be pushed
387 # alongside. Therefor `targetphase` is
387 # alongside. Therefor `targetphase` is
388 # ignored.
388 # ignored.
389 targetphase = phaseall = phases.draft
389 targetphase = phaseall = phases.draft
390 if added:
390 if added:
391 phases.registernew(repo, tr, targetphase, added)
391 phases.registernew(repo, tr, targetphase, added)
392 if phaseall is not None:
392 if phaseall is not None:
393 phases.advanceboundary(repo, tr, phaseall, cgnodes)
393 phases.advanceboundary(repo, tr, phaseall, cgnodes)
394
394
395 if changesets > 0:
395 if changesets > 0:
396
396
397 def runhooks():
397 def runhooks():
398 # These hooks run when the lock releases, not when the
398 # These hooks run when the lock releases, not when the
399 # transaction closes. So it's possible for the changelog
399 # transaction closes. So it's possible for the changelog
400 # to have changed since we last saw it.
400 # to have changed since we last saw it.
401 if clstart >= len(repo):
401 if clstart >= len(repo):
402 return
402 return
403
403
404 repo.hook("changegroup", **pycompat.strkwargs(hookargs))
404 repo.hook("changegroup", **pycompat.strkwargs(hookargs))
405
405
406 for n in added:
406 for n in added:
407 args = hookargs.copy()
407 args = hookargs.copy()
408 args['node'] = hex(n)
408 args['node'] = hex(n)
409 del args['node_last']
409 del args['node_last']
410 repo.hook("incoming", **pycompat.strkwargs(args))
410 repo.hook("incoming", **pycompat.strkwargs(args))
411
411
412 newheads = [h for h in repo.heads()
412 newheads = [h for h in repo.heads()
413 if h not in oldheads]
413 if h not in oldheads]
414 repo.ui.log("incoming",
414 repo.ui.log("incoming",
415 "%d incoming changes - new heads: %s\n",
415 "%d incoming changes - new heads: %s\n",
416 len(added),
416 len(added),
417 ', '.join([hex(c[:6]) for c in newheads]))
417 ', '.join([hex(c[:6]) for c in newheads]))
418
418
419 tr.addpostclose('changegroup-runhooks-%020i' % clstart,
419 tr.addpostclose('changegroup-runhooks-%020i' % clstart,
420 lambda tr: repo._afterlock(runhooks))
420 lambda tr: repo._afterlock(runhooks))
421 finally:
421 finally:
422 repo.ui.flush()
422 repo.ui.flush()
423 # never return 0 here:
423 # never return 0 here:
424 if deltaheads < 0:
424 if deltaheads < 0:
425 ret = deltaheads - 1
425 ret = deltaheads - 1
426 else:
426 else:
427 ret = deltaheads + 1
427 ret = deltaheads + 1
428 return ret
428 return ret
429
429
430 def deltaiter(self):
430 def deltaiter(self):
431 """
431 """
432 returns an iterator of the deltas in this changegroup
432 returns an iterator of the deltas in this changegroup
433
433
434 Useful for passing to the underlying storage system to be stored.
434 Useful for passing to the underlying storage system to be stored.
435 """
435 """
436 chain = None
436 chain = None
437 for chunkdata in iter(lambda: self.deltachunk(chain), {}):
437 for chunkdata in iter(lambda: self.deltachunk(chain), {}):
438 # Chunkdata: (node, p1, p2, cs, deltabase, delta, flags)
438 # Chunkdata: (node, p1, p2, cs, deltabase, delta, flags)
439 yield chunkdata
439 yield chunkdata
440 chain = chunkdata[0]
440 chain = chunkdata[0]
441
441
442 class cg2unpacker(cg1unpacker):
442 class cg2unpacker(cg1unpacker):
443 """Unpacker for cg2 streams.
443 """Unpacker for cg2 streams.
444
444
445 cg2 streams add support for generaldelta, so the delta header
445 cg2 streams add support for generaldelta, so the delta header
446 format is slightly different. All other features about the data
446 format is slightly different. All other features about the data
447 remain the same.
447 remain the same.
448 """
448 """
449 deltaheader = _CHANGEGROUPV2_DELTA_HEADER
449 deltaheader = _CHANGEGROUPV2_DELTA_HEADER
450 deltaheadersize = struct.calcsize(deltaheader)
450 deltaheadersize = struct.calcsize(deltaheader)
451 version = '02'
451 version = '02'
452
452
453 def _deltaheader(self, headertuple, prevnode):
453 def _deltaheader(self, headertuple, prevnode):
454 node, p1, p2, deltabase, cs = headertuple
454 node, p1, p2, deltabase, cs = headertuple
455 flags = 0
455 flags = 0
456 return node, p1, p2, deltabase, cs, flags
456 return node, p1, p2, deltabase, cs, flags
457
457
458 class cg3unpacker(cg2unpacker):
458 class cg3unpacker(cg2unpacker):
459 """Unpacker for cg3 streams.
459 """Unpacker for cg3 streams.
460
460
461 cg3 streams add support for exchanging treemanifests and revlog
461 cg3 streams add support for exchanging treemanifests and revlog
462 flags. It adds the revlog flags to the delta header and an empty chunk
462 flags. It adds the revlog flags to the delta header and an empty chunk
463 separating manifests and files.
463 separating manifests and files.
464 """
464 """
465 deltaheader = _CHANGEGROUPV3_DELTA_HEADER
465 deltaheader = _CHANGEGROUPV3_DELTA_HEADER
466 deltaheadersize = struct.calcsize(deltaheader)
466 deltaheadersize = struct.calcsize(deltaheader)
467 version = '03'
467 version = '03'
468 _grouplistcount = 2 # One list of manifests and one list of files
468 _grouplistcount = 2 # One list of manifests and one list of files
469
469
470 def _deltaheader(self, headertuple, prevnode):
470 def _deltaheader(self, headertuple, prevnode):
471 node, p1, p2, deltabase, cs, flags = headertuple
471 node, p1, p2, deltabase, cs, flags = headertuple
472 return node, p1, p2, deltabase, cs, flags
472 return node, p1, p2, deltabase, cs, flags
473
473
474 def _unpackmanifests(self, repo, revmap, trp, prog):
474 def _unpackmanifests(self, repo, revmap, trp, prog):
475 super(cg3unpacker, self)._unpackmanifests(repo, revmap, trp, prog)
475 super(cg3unpacker, self)._unpackmanifests(repo, revmap, trp, prog)
476 for chunkdata in iter(self.filelogheader, {}):
476 for chunkdata in iter(self.filelogheader, {}):
477 # If we get here, there are directory manifests in the changegroup
477 # If we get here, there are directory manifests in the changegroup
478 d = chunkdata["filename"]
478 d = chunkdata["filename"]
479 repo.ui.debug("adding %s revisions\n" % d)
479 repo.ui.debug("adding %s revisions\n" % d)
480 dirlog = repo.manifestlog._revlog.dirlog(d)
480 dirlog = repo.manifestlog._revlog.dirlog(d)
481 deltas = self.deltaiter()
481 deltas = self.deltaiter()
482 if not dirlog.addgroup(deltas, revmap, trp):
482 if not dirlog.addgroup(deltas, revmap, trp):
483 raise error.Abort(_("received dir revlog group is empty"))
483 raise error.Abort(_("received dir revlog group is empty"))
484
484
485 class headerlessfixup(object):
485 class headerlessfixup(object):
486 def __init__(self, fh, h):
486 def __init__(self, fh, h):
487 self._h = h
487 self._h = h
488 self._fh = fh
488 self._fh = fh
489 def read(self, n):
489 def read(self, n):
490 if self._h:
490 if self._h:
491 d, self._h = self._h[:n], self._h[n:]
491 d, self._h = self._h[:n], self._h[n:]
492 if len(d) < n:
492 if len(d) < n:
493 d += readexactly(self._fh, n - len(d))
493 d += readexactly(self._fh, n - len(d))
494 return d
494 return d
495 return readexactly(self._fh, n)
495 return readexactly(self._fh, n)
496
496
497 def ellipsisdata(packer, rev, revlog_, p1, p2, data, linknode):
497 def ellipsisdata(packer, rev, revlog_, p1, p2, data, linknode):
498 n = revlog_.node(rev)
498 n = revlog_.node(rev)
499 p1n, p2n = revlog_.node(p1), revlog_.node(p2)
499 p1n, p2n = revlog_.node(p1), revlog_.node(p2)
500 flags = revlog_.flags(rev)
500 flags = revlog_.flags(rev)
501 flags |= revlog.REVIDX_ELLIPSIS
501 flags |= revlog.REVIDX_ELLIPSIS
502 meta = packer.builddeltaheader(
502 meta = packer.builddeltaheader(
503 n, p1n, p2n, nullid, linknode, flags)
503 n, p1n, p2n, nullid, linknode, flags)
504 # TODO: try and actually send deltas for ellipsis data blocks
504 # TODO: try and actually send deltas for ellipsis data blocks
505 diffheader = mdiff.trivialdiffheader(len(data))
505 diffheader = mdiff.trivialdiffheader(len(data))
506 l = len(meta) + len(diffheader) + len(data)
506 l = len(meta) + len(diffheader) + len(data)
507 return ''.join((chunkheader(l),
507 return ''.join((chunkheader(l),
508 meta,
508 meta,
509 diffheader,
509 diffheader,
510 data))
510 data))
511
511
512 class cg1packer(object):
512 class cg1packer(object):
513 deltaheader = _CHANGEGROUPV1_DELTA_HEADER
513 deltaheader = _CHANGEGROUPV1_DELTA_HEADER
514 version = '01'
514 version = '01'
515 def __init__(self, repo, filematcher, bundlecaps=None):
515 def __init__(self, repo, filematcher, bundlecaps=None):
516 """Given a source repo, construct a bundler.
516 """Given a source repo, construct a bundler.
517
517
518 filematcher is a matcher that matches on files to include in the
518 filematcher is a matcher that matches on files to include in the
519 changegroup. Used to facilitate sparse changegroups.
519 changegroup. Used to facilitate sparse changegroups.
520
520
521 bundlecaps is optional and can be used to specify the set of
521 bundlecaps is optional and can be used to specify the set of
522 capabilities which can be used to build the bundle. While bundlecaps is
522 capabilities which can be used to build the bundle. While bundlecaps is
523 unused in core Mercurial, extensions rely on this feature to communicate
523 unused in core Mercurial, extensions rely on this feature to communicate
524 capabilities to customize the changegroup packer.
524 capabilities to customize the changegroup packer.
525 """
525 """
526 assert filematcher
526 assert filematcher
527 self._filematcher = filematcher
527 self._filematcher = filematcher
528
528
529 # Set of capabilities we can use to build the bundle.
529 # Set of capabilities we can use to build the bundle.
530 if bundlecaps is None:
530 if bundlecaps is None:
531 bundlecaps = set()
531 bundlecaps = set()
532 self._bundlecaps = bundlecaps
532 self._bundlecaps = bundlecaps
533 # experimental config: bundle.reorder
533 # experimental config: bundle.reorder
534 reorder = repo.ui.config('bundle', 'reorder')
534 reorder = repo.ui.config('bundle', 'reorder')
535 if reorder == 'auto':
535 if reorder == 'auto':
536 reorder = None
536 reorder = None
537 else:
537 else:
538 reorder = stringutil.parsebool(reorder)
538 reorder = stringutil.parsebool(reorder)
539 self._repo = repo
539 self._repo = repo
540 self._reorder = reorder
540 self._reorder = reorder
541 if self._repo.ui.verbose and not self._repo.ui.debugflag:
541 if self._repo.ui.verbose and not self._repo.ui.debugflag:
542 self._verbosenote = self._repo.ui.note
542 self._verbosenote = self._repo.ui.note
543 else:
543 else:
544 self._verbosenote = lambda s: None
544 self._verbosenote = lambda s: None
545
545
546 def close(self):
546 def close(self):
547 # Ellipses serving mode.
547 # Ellipses serving mode.
548 getattr(self, 'clrev_to_localrev', {}).clear()
548 getattr(self, 'clrev_to_localrev', {}).clear()
549 if getattr(self, 'next_clrev_to_localrev', {}):
549 if getattr(self, 'next_clrev_to_localrev', {}):
550 self.clrev_to_localrev = self.next_clrev_to_localrev
550 self.clrev_to_localrev = self.next_clrev_to_localrev
551 del self.next_clrev_to_localrev
551 del self.next_clrev_to_localrev
552 self.changelog_done = True
552 self.changelog_done = True
553
553
554 return closechunk()
554 return closechunk()
555
555
556 def fileheader(self, fname):
556 def fileheader(self, fname):
557 return chunkheader(len(fname)) + fname
557 return chunkheader(len(fname)) + fname
558
558
559 # Extracted both for clarity and for overriding in extensions.
559 # Extracted both for clarity and for overriding in extensions.
560 def _sortgroup(self, revlog, nodelist, lookup):
560 def _sortgroup(self, revlog, nodelist, lookup):
561 """Sort nodes for change group and turn them into revnums."""
561 """Sort nodes for change group and turn them into revnums."""
562 # Ellipses serving mode.
562 # Ellipses serving mode.
563 #
563 #
564 # In a perfect world, we'd generate better ellipsis-ified graphs
564 # In a perfect world, we'd generate better ellipsis-ified graphs
565 # for non-changelog revlogs. In practice, we haven't started doing
565 # for non-changelog revlogs. In practice, we haven't started doing
566 # that yet, so the resulting DAGs for the manifestlog and filelogs
566 # that yet, so the resulting DAGs for the manifestlog and filelogs
567 # are actually full of bogus parentage on all the ellipsis
567 # are actually full of bogus parentage on all the ellipsis
568 # nodes. This has the side effect that, while the contents are
568 # nodes. This has the side effect that, while the contents are
569 # correct, the individual DAGs might be completely out of whack in
569 # correct, the individual DAGs might be completely out of whack in
570 # a case like 882681bc3166 and its ancestors (back about 10
570 # a case like 882681bc3166 and its ancestors (back about 10
571 # revisions or so) in the main hg repo.
571 # revisions or so) in the main hg repo.
572 #
572 #
573 # The one invariant we *know* holds is that the new (potentially
573 # The one invariant we *know* holds is that the new (potentially
574 # bogus) DAG shape will be valid if we order the nodes in the
574 # bogus) DAG shape will be valid if we order the nodes in the
575 # order that they're introduced in dramatis personae by the
575 # order that they're introduced in dramatis personae by the
576 # changelog, so what we do is we sort the non-changelog histories
576 # changelog, so what we do is we sort the non-changelog histories
577 # by the order in which they are used by the changelog.
577 # by the order in which they are used by the changelog.
578 if util.safehasattr(self, 'full_nodes') and self.clnode_to_rev:
578 if util.safehasattr(self, 'full_nodes') and self.clnode_to_rev:
579 key = lambda n: self.clnode_to_rev[lookup(n)]
579 key = lambda n: self.clnode_to_rev[lookup(n)]
580 return [revlog.rev(n) for n in sorted(nodelist, key=key)]
580 return [revlog.rev(n) for n in sorted(nodelist, key=key)]
581
581
582 # for generaldelta revlogs, we linearize the revs; this will both be
582 # for generaldelta revlogs, we linearize the revs; this will both be
583 # much quicker and generate a much smaller bundle
583 # much quicker and generate a much smaller bundle
584 if (revlog._generaldelta and self._reorder is None) or self._reorder:
584 if (revlog._generaldelta and self._reorder is None) or self._reorder:
585 dag = dagutil.revlogdag(revlog)
585 dag = dagutil.revlogdag(revlog)
586 return dag.linearize(set(revlog.rev(n) for n in nodelist))
586 return dag.linearize(set(revlog.rev(n) for n in nodelist))
587 else:
587 else:
588 return sorted([revlog.rev(n) for n in nodelist])
588 return sorted([revlog.rev(n) for n in nodelist])
589
589
590 def group(self, nodelist, revlog, lookup, units=None):
590 def group(self, nodelist, revlog, lookup, units=None):
591 """Calculate a delta group, yielding a sequence of changegroup chunks
591 """Calculate a delta group, yielding a sequence of changegroup chunks
592 (strings).
592 (strings).
593
593
594 Given a list of changeset revs, return a set of deltas and
594 Given a list of changeset revs, return a set of deltas and
595 metadata corresponding to nodes. The first delta is
595 metadata corresponding to nodes. The first delta is
596 first parent(nodelist[0]) -> nodelist[0], the receiver is
596 first parent(nodelist[0]) -> nodelist[0], the receiver is
597 guaranteed to have this parent as it has all history before
597 guaranteed to have this parent as it has all history before
598 these changesets. In the case firstparent is nullrev the
598 these changesets. In the case firstparent is nullrev the
599 changegroup starts with a full revision.
599 changegroup starts with a full revision.
600
600
601 If units is not None, progress detail will be generated, units specifies
601 If units is not None, progress detail will be generated, units specifies
602 the type of revlog that is touched (changelog, manifest, etc.).
602 the type of revlog that is touched (changelog, manifest, etc.).
603 """
603 """
604 # if we don't have any revisions touched by these changesets, bail
604 # if we don't have any revisions touched by these changesets, bail
605 if len(nodelist) == 0:
605 if len(nodelist) == 0:
606 yield self.close()
606 yield self.close()
607 return
607 return
608
608
609 revs = self._sortgroup(revlog, nodelist, lookup)
609 revs = self._sortgroup(revlog, nodelist, lookup)
610
610
611 # add the parent of the first rev
611 # add the parent of the first rev
612 p = revlog.parentrevs(revs[0])[0]
612 p = revlog.parentrevs(revs[0])[0]
613 revs.insert(0, p)
613 revs.insert(0, p)
614
614
615 # build deltas
615 # build deltas
616 progress = None
616 progress = None
617 if units is not None:
617 if units is not None:
618 progress = self._repo.ui.makeprogress(_('bundling'), unit=units,
618 progress = self._repo.ui.makeprogress(_('bundling'), unit=units,
619 total=(len(revs) - 1))
619 total=(len(revs) - 1))
620 for r in pycompat.xrange(len(revs) - 1):
620 for r in pycompat.xrange(len(revs) - 1):
621 if progress:
621 if progress:
622 progress.update(r + 1)
622 progress.update(r + 1)
623 prev, curr = revs[r], revs[r + 1]
623 prev, curr = revs[r], revs[r + 1]
624 linknode = lookup(revlog.node(curr))
624 linknode = lookup(revlog.node(curr))
625 for c in self.revchunk(revlog, curr, prev, linknode):
625 for c in self.revchunk(revlog, curr, prev, linknode):
626 yield c
626 yield c
627
627
628 if progress:
628 if progress:
629 progress.complete()
629 progress.complete()
630 yield self.close()
630 yield self.close()
631
631
632 # filter any nodes that claim to be part of the known set
632 # filter any nodes that claim to be part of the known set
633 def prune(self, revlog, missing, commonrevs):
633 def prune(self, revlog, missing, commonrevs):
634 # TODO this violates storage abstraction for manifests.
634 # TODO this violates storage abstraction for manifests.
635 if isinstance(revlog, manifest.manifestrevlog):
635 if isinstance(revlog, manifest.manifestrevlog):
636 if not self._filematcher.visitdir(revlog._dir[:-1] or '.'):
636 if not self._filematcher.visitdir(revlog._dir[:-1] or '.'):
637 return []
637 return []
638
638
639 rr, rl = revlog.rev, revlog.linkrev
639 rr, rl = revlog.rev, revlog.linkrev
640 return [n for n in missing if rl(rr(n)) not in commonrevs]
640 return [n for n in missing if rl(rr(n)) not in commonrevs]
641
641
642 def _packmanifests(self, dir, mfnodes, lookuplinknode):
642 def _packmanifests(self, dir, mfnodes, lookuplinknode):
643 """Pack flat manifests into a changegroup stream."""
643 """Pack flat manifests into a changegroup stream."""
644 assert not dir
644 assert not dir
645 for chunk in self.group(mfnodes, self._repo.manifestlog._revlog,
645 for chunk in self.group(mfnodes, self._repo.manifestlog._revlog,
646 lookuplinknode, units=_('manifests')):
646 lookuplinknode, units=_('manifests')):
647 yield chunk
647 yield chunk
648
648
649 def _manifestsdone(self):
649 def _manifestsdone(self):
650 return ''
650 return ''
651
651
652 def generate(self, commonrevs, clnodes, fastpathlinkrev, source):
652 def generate(self, commonrevs, clnodes, fastpathlinkrev, source):
653 '''yield a sequence of changegroup chunks (strings)'''
653 '''yield a sequence of changegroup chunks (strings)'''
654 repo = self._repo
654 repo = self._repo
655 cl = repo.changelog
655 cl = repo.changelog
656
656
657 clrevorder = {}
657 clrevorder = {}
658 mfs = {} # needed manifests
658 mfs = {} # needed manifests
659 fnodes = {} # needed file nodes
659 fnodes = {} # needed file nodes
660 mfl = repo.manifestlog
661 # TODO violates storage abstraction.
662 mfrevlog = mfl._revlog
660 changedfiles = set()
663 changedfiles = set()
661
664
662 # Callback for the changelog, used to collect changed files and manifest
665 ellipsesmode = util.safehasattr(self, 'full_nodes')
663 # nodes.
666
667 # Callback for the changelog, used to collect changed files and
668 # manifest nodes.
664 # Returns the linkrev node (identity in the changelog case).
669 # Returns the linkrev node (identity in the changelog case).
665 def lookupcl(x):
670 def lookupcl(x):
666 c = cl.read(x)
671 c = cl.read(x)
667 clrevorder[x] = len(clrevorder)
672 clrevorder[x] = len(clrevorder)
668 n = c[0]
673
669 # record the first changeset introducing this manifest version
674 if ellipsesmode:
670 mfs.setdefault(n, x)
675 # Only update mfs if x is going to be sent. Otherwise we
671 # Record a complete list of potentially-changed files in
676 # end up with bogus linkrevs specified for manifests and
672 # this manifest.
677 # we skip some manifest nodes that we should otherwise
673 changedfiles.update(c[3])
678 # have sent.
679 if (x in self.full_nodes
680 or cl.rev(x) in self.precomputed_ellipsis):
681 n = c[0]
682 # Record the first changeset introducing this manifest
683 # version.
684 mfs.setdefault(n, x)
685 # Set this narrow-specific dict so we have the lowest
686 # manifest revnum to look up for this cl revnum. (Part of
687 # mapping changelog ellipsis parents to manifest ellipsis
688 # parents)
689 self.next_clrev_to_localrev.setdefault(cl.rev(x),
690 mfrevlog.rev(n))
691 # We can't trust the changed files list in the changeset if the
692 # client requested a shallow clone.
693 if self.is_shallow:
694 changedfiles.update(mfl[c[0]].read().keys())
695 else:
696 changedfiles.update(c[3])
697 else:
698
699 n = c[0]
700 # record the first changeset introducing this manifest version
701 mfs.setdefault(n, x)
702 # Record a complete list of potentially-changed files in
703 # this manifest.
704 changedfiles.update(c[3])
705
674 return x
706 return x
675
707
676 self._verbosenote(_('uncompressed size of bundle content:\n'))
708 self._verbosenote(_('uncompressed size of bundle content:\n'))
677 size = 0
709 size = 0
678 for chunk in self.group(clnodes, cl, lookupcl, units=_('changesets')):
710 for chunk in self.group(clnodes, cl, lookupcl, units=_('changesets')):
679 size += len(chunk)
711 size += len(chunk)
680 yield chunk
712 yield chunk
681 self._verbosenote(_('%8.i (changelog)\n') % size)
713 self._verbosenote(_('%8.i (changelog)\n') % size)
682
714
683 # We need to make sure that the linkrev in the changegroup refers to
715 # We need to make sure that the linkrev in the changegroup refers to
684 # the first changeset that introduced the manifest or file revision.
716 # the first changeset that introduced the manifest or file revision.
685 # The fastpath is usually safer than the slowpath, because the filelogs
717 # The fastpath is usually safer than the slowpath, because the filelogs
686 # are walked in revlog order.
718 # are walked in revlog order.
687 #
719 #
688 # When taking the slowpath with reorder=None and the manifest revlog
720 # When taking the slowpath with reorder=None and the manifest revlog
689 # uses generaldelta, the manifest may be walked in the "wrong" order.
721 # uses generaldelta, the manifest may be walked in the "wrong" order.
690 # Without 'clrevorder', we would get an incorrect linkrev (see fix in
722 # Without 'clrevorder', we would get an incorrect linkrev (see fix in
691 # cc0ff93d0c0c).
723 # cc0ff93d0c0c).
692 #
724 #
693 # When taking the fastpath, we are only vulnerable to reordering
725 # When taking the fastpath, we are only vulnerable to reordering
694 # of the changelog itself. The changelog never uses generaldelta, so
726 # of the changelog itself. The changelog never uses generaldelta, so
695 # it is only reordered when reorder=True. To handle this case, we
727 # it is only reordered when reorder=True. To handle this case, we
696 # simply take the slowpath, which already has the 'clrevorder' logic.
728 # simply take the slowpath, which already has the 'clrevorder' logic.
697 # This was also fixed in cc0ff93d0c0c.
729 # This was also fixed in cc0ff93d0c0c.
698 fastpathlinkrev = fastpathlinkrev and not self._reorder
730 fastpathlinkrev = fastpathlinkrev and not self._reorder
699 # Treemanifests don't work correctly with fastpathlinkrev
731 # Treemanifests don't work correctly with fastpathlinkrev
700 # either, because we don't discover which directory nodes to
732 # either, because we don't discover which directory nodes to
701 # send along with files. This could probably be fixed.
733 # send along with files. This could probably be fixed.
702 fastpathlinkrev = fastpathlinkrev and (
734 fastpathlinkrev = fastpathlinkrev and (
703 'treemanifest' not in repo.requirements)
735 'treemanifest' not in repo.requirements)
704
736
705 for chunk in self.generatemanifests(commonrevs, clrevorder,
737 for chunk in self.generatemanifests(commonrevs, clrevorder,
706 fastpathlinkrev, mfs, fnodes, source):
738 fastpathlinkrev, mfs, fnodes, source):
707 yield chunk
739 yield chunk
740
741 if ellipsesmode:
742 mfdicts = None
743 if self.is_shallow:
744 mfdicts = [(self._repo.manifestlog[n].read(), lr)
745 for (n, lr) in mfs.iteritems()]
746
708 mfs.clear()
747 mfs.clear()
709 clrevs = set(cl.rev(x) for x in clnodes)
748 clrevs = set(cl.rev(x) for x in clnodes)
710
749
711 if not fastpathlinkrev:
750 if not fastpathlinkrev:
712 def linknodes(unused, fname):
751 def linknodes(unused, fname):
713 return fnodes.get(fname, {})
752 return fnodes.get(fname, {})
714 else:
753 else:
715 cln = cl.node
754 cln = cl.node
716 def linknodes(filerevlog, fname):
755 def linknodes(filerevlog, fname):
717 llr = filerevlog.linkrev
756 llr = filerevlog.linkrev
718 fln = filerevlog.node
757 fln = filerevlog.node
719 revs = ((r, llr(r)) for r in filerevlog)
758 revs = ((r, llr(r)) for r in filerevlog)
720 return dict((fln(r), cln(lr)) for r, lr in revs if lr in clrevs)
759 return dict((fln(r), cln(lr)) for r, lr in revs if lr in clrevs)
721
760
761 if ellipsesmode:
762 # We need to pass the mfdicts variable down into
763 # generatefiles(), but more than one command might have
764 # wrapped generatefiles so we can't modify the function
765 # signature. Instead, we pass the data to ourselves using an
766 # instance attribute. I'm sorry.
767 self._mfdicts = mfdicts
768
722 for chunk in self.generatefiles(changedfiles, linknodes, commonrevs,
769 for chunk in self.generatefiles(changedfiles, linknodes, commonrevs,
723 source):
770 source):
724 yield chunk
771 yield chunk
725
772
726 yield self.close()
773 yield self.close()
727
774
728 if clnodes:
775 if clnodes:
729 repo.hook('outgoing', node=hex(clnodes[0]), source=source)
776 repo.hook('outgoing', node=hex(clnodes[0]), source=source)
730
777
731 def generatemanifests(self, commonrevs, clrevorder, fastpathlinkrev, mfs,
778 def generatemanifests(self, commonrevs, clrevorder, fastpathlinkrev, mfs,
732 fnodes, source):
779 fnodes, source):
733 """Returns an iterator of changegroup chunks containing manifests.
780 """Returns an iterator of changegroup chunks containing manifests.
734
781
735 `source` is unused here, but is used by extensions like remotefilelog to
782 `source` is unused here, but is used by extensions like remotefilelog to
736 change what is sent based in pulls vs pushes, etc.
783 change what is sent based in pulls vs pushes, etc.
737 """
784 """
738 repo = self._repo
785 repo = self._repo
739 mfl = repo.manifestlog
786 mfl = repo.manifestlog
740 dirlog = mfl._revlog.dirlog
787 dirlog = mfl._revlog.dirlog
741 tmfnodes = {'': mfs}
788 tmfnodes = {'': mfs}
742
789
743 # Callback for the manifest, used to collect linkrevs for filelog
790 # Callback for the manifest, used to collect linkrevs for filelog
744 # revisions.
791 # revisions.
745 # Returns the linkrev node (collected in lookupcl).
792 # Returns the linkrev node (collected in lookupcl).
746 def makelookupmflinknode(dir, nodes):
793 def makelookupmflinknode(dir, nodes):
747 if fastpathlinkrev:
794 if fastpathlinkrev:
748 assert not dir
795 assert not dir
749 return mfs.__getitem__
796 return mfs.__getitem__
750
797
751 def lookupmflinknode(x):
798 def lookupmflinknode(x):
752 """Callback for looking up the linknode for manifests.
799 """Callback for looking up the linknode for manifests.
753
800
754 Returns the linkrev node for the specified manifest.
801 Returns the linkrev node for the specified manifest.
755
802
756 SIDE EFFECT:
803 SIDE EFFECT:
757
804
758 1) fclnodes gets populated with the list of relevant
805 1) fclnodes gets populated with the list of relevant
759 file nodes if we're not using fastpathlinkrev
806 file nodes if we're not using fastpathlinkrev
760 2) When treemanifests are in use, collects treemanifest nodes
807 2) When treemanifests are in use, collects treemanifest nodes
761 to send
808 to send
762
809
763 Note that this means manifests must be completely sent to
810 Note that this means manifests must be completely sent to
764 the client before you can trust the list of files and
811 the client before you can trust the list of files and
765 treemanifests to send.
812 treemanifests to send.
766 """
813 """
767 clnode = nodes[x]
814 clnode = nodes[x]
768 mdata = mfl.get(dir, x).readfast(shallow=True)
815 mdata = mfl.get(dir, x).readfast(shallow=True)
769 for p, n, fl in mdata.iterentries():
816 for p, n, fl in mdata.iterentries():
770 if fl == 't': # subdirectory manifest
817 if fl == 't': # subdirectory manifest
771 subdir = dir + p + '/'
818 subdir = dir + p + '/'
772 tmfclnodes = tmfnodes.setdefault(subdir, {})
819 tmfclnodes = tmfnodes.setdefault(subdir, {})
773 tmfclnode = tmfclnodes.setdefault(n, clnode)
820 tmfclnode = tmfclnodes.setdefault(n, clnode)
774 if clrevorder[clnode] < clrevorder[tmfclnode]:
821 if clrevorder[clnode] < clrevorder[tmfclnode]:
775 tmfclnodes[n] = clnode
822 tmfclnodes[n] = clnode
776 else:
823 else:
777 f = dir + p
824 f = dir + p
778 fclnodes = fnodes.setdefault(f, {})
825 fclnodes = fnodes.setdefault(f, {})
779 fclnode = fclnodes.setdefault(n, clnode)
826 fclnode = fclnodes.setdefault(n, clnode)
780 if clrevorder[clnode] < clrevorder[fclnode]:
827 if clrevorder[clnode] < clrevorder[fclnode]:
781 fclnodes[n] = clnode
828 fclnodes[n] = clnode
782 return clnode
829 return clnode
783 return lookupmflinknode
830 return lookupmflinknode
784
831
785 size = 0
832 size = 0
786 while tmfnodes:
833 while tmfnodes:
787 dir, nodes = tmfnodes.popitem()
834 dir, nodes = tmfnodes.popitem()
788 prunednodes = self.prune(dirlog(dir), nodes, commonrevs)
835 prunednodes = self.prune(dirlog(dir), nodes, commonrevs)
789 if not dir or prunednodes:
836 if not dir or prunednodes:
790 for x in self._packmanifests(dir, prunednodes,
837 for x in self._packmanifests(dir, prunednodes,
791 makelookupmflinknode(dir, nodes)):
838 makelookupmflinknode(dir, nodes)):
792 size += len(x)
839 size += len(x)
793 yield x
840 yield x
794 self._verbosenote(_('%8.i (manifests)\n') % size)
841 self._verbosenote(_('%8.i (manifests)\n') % size)
795 yield self._manifestsdone()
842 yield self._manifestsdone()
796
843
797 # The 'source' parameter is useful for extensions
844 # The 'source' parameter is useful for extensions
798 def generatefiles(self, changedfiles, linknodes, commonrevs, source):
845 def generatefiles(self, changedfiles, linknodes, commonrevs, source):
799 changedfiles = list(filter(self._filematcher, changedfiles))
846 changedfiles = list(filter(self._filematcher, changedfiles))
800
847
801 if getattr(self, 'is_shallow', False):
848 if getattr(self, 'is_shallow', False):
802 # See comment in generate() for why this sadness is a thing.
849 # See comment in generate() for why this sadness is a thing.
803 mfdicts = self._mfdicts
850 mfdicts = self._mfdicts
804 del self._mfdicts
851 del self._mfdicts
805 # In a shallow clone, the linknodes callback needs to also include
852 # In a shallow clone, the linknodes callback needs to also include
806 # those file nodes that are in the manifests we sent but weren't
853 # those file nodes that are in the manifests we sent but weren't
807 # introduced by those manifests.
854 # introduced by those manifests.
808 commonctxs = [self._repo[c] for c in commonrevs]
855 commonctxs = [self._repo[c] for c in commonrevs]
809 oldlinknodes = linknodes
856 oldlinknodes = linknodes
810 clrev = self._repo.changelog.rev
857 clrev = self._repo.changelog.rev
811
858
812 # Defining this function has a side-effect of overriding the
859 # Defining this function has a side-effect of overriding the
813 # function of the same name that was passed in as an argument.
860 # function of the same name that was passed in as an argument.
814 # TODO have caller pass in appropriate function.
861 # TODO have caller pass in appropriate function.
815 def linknodes(flog, fname):
862 def linknodes(flog, fname):
816 for c in commonctxs:
863 for c in commonctxs:
817 try:
864 try:
818 fnode = c.filenode(fname)
865 fnode = c.filenode(fname)
819 self.clrev_to_localrev[c.rev()] = flog.rev(fnode)
866 self.clrev_to_localrev[c.rev()] = flog.rev(fnode)
820 except error.ManifestLookupError:
867 except error.ManifestLookupError:
821 pass
868 pass
822 links = oldlinknodes(flog, fname)
869 links = oldlinknodes(flog, fname)
823 if len(links) != len(mfdicts):
870 if len(links) != len(mfdicts):
824 for mf, lr in mfdicts:
871 for mf, lr in mfdicts:
825 fnode = mf.get(fname, None)
872 fnode = mf.get(fname, None)
826 if fnode in links:
873 if fnode in links:
827 links[fnode] = min(links[fnode], lr, key=clrev)
874 links[fnode] = min(links[fnode], lr, key=clrev)
828 elif fnode:
875 elif fnode:
829 links[fnode] = lr
876 links[fnode] = lr
830 return links
877 return links
831
878
832 return self._generatefiles(changedfiles, linknodes, commonrevs, source)
879 return self._generatefiles(changedfiles, linknodes, commonrevs, source)
833
880
834 def _generatefiles(self, changedfiles, linknodes, commonrevs, source):
881 def _generatefiles(self, changedfiles, linknodes, commonrevs, source):
835 repo = self._repo
882 repo = self._repo
836 progress = repo.ui.makeprogress(_('bundling'), unit=_('files'),
883 progress = repo.ui.makeprogress(_('bundling'), unit=_('files'),
837 total=len(changedfiles))
884 total=len(changedfiles))
838 for i, fname in enumerate(sorted(changedfiles)):
885 for i, fname in enumerate(sorted(changedfiles)):
839 filerevlog = repo.file(fname)
886 filerevlog = repo.file(fname)
840 if not filerevlog:
887 if not filerevlog:
841 raise error.Abort(_("empty or missing file data for %s") %
888 raise error.Abort(_("empty or missing file data for %s") %
842 fname)
889 fname)
843
890
844 linkrevnodes = linknodes(filerevlog, fname)
891 linkrevnodes = linknodes(filerevlog, fname)
845 # Lookup for filenodes, we collected the linkrev nodes above in the
892 # Lookup for filenodes, we collected the linkrev nodes above in the
846 # fastpath case and with lookupmf in the slowpath case.
893 # fastpath case and with lookupmf in the slowpath case.
847 def lookupfilelog(x):
894 def lookupfilelog(x):
848 return linkrevnodes[x]
895 return linkrevnodes[x]
849
896
850 filenodes = self.prune(filerevlog, linkrevnodes, commonrevs)
897 filenodes = self.prune(filerevlog, linkrevnodes, commonrevs)
851 if filenodes:
898 if filenodes:
852 progress.update(i + 1, item=fname)
899 progress.update(i + 1, item=fname)
853 h = self.fileheader(fname)
900 h = self.fileheader(fname)
854 size = len(h)
901 size = len(h)
855 yield h
902 yield h
856 for chunk in self.group(filenodes, filerevlog, lookupfilelog):
903 for chunk in self.group(filenodes, filerevlog, lookupfilelog):
857 size += len(chunk)
904 size += len(chunk)
858 yield chunk
905 yield chunk
859 self._verbosenote(_('%8.i %s\n') % (size, fname))
906 self._verbosenote(_('%8.i %s\n') % (size, fname))
860 progress.complete()
907 progress.complete()
861
908
862 def deltaparent(self, revlog, rev, p1, p2, prev):
909 def deltaparent(self, revlog, rev, p1, p2, prev):
863 if not revlog.candelta(prev, rev):
910 if not revlog.candelta(prev, rev):
864 raise error.ProgrammingError('cg1 should not be used in this case')
911 raise error.ProgrammingError('cg1 should not be used in this case')
865 return prev
912 return prev
866
913
867 def revchunk(self, revlog, rev, prev, linknode):
914 def revchunk(self, revlog, rev, prev, linknode):
868 if util.safehasattr(self, 'full_nodes'):
915 if util.safehasattr(self, 'full_nodes'):
869 fn = self._revchunknarrow
916 fn = self._revchunknarrow
870 else:
917 else:
871 fn = self._revchunknormal
918 fn = self._revchunknormal
872
919
873 return fn(revlog, rev, prev, linknode)
920 return fn(revlog, rev, prev, linknode)
874
921
875 def _revchunknormal(self, revlog, rev, prev, linknode):
922 def _revchunknormal(self, revlog, rev, prev, linknode):
876 node = revlog.node(rev)
923 node = revlog.node(rev)
877 p1, p2 = revlog.parentrevs(rev)
924 p1, p2 = revlog.parentrevs(rev)
878 base = self.deltaparent(revlog, rev, p1, p2, prev)
925 base = self.deltaparent(revlog, rev, p1, p2, prev)
879
926
880 prefix = ''
927 prefix = ''
881 if revlog.iscensored(base) or revlog.iscensored(rev):
928 if revlog.iscensored(base) or revlog.iscensored(rev):
882 try:
929 try:
883 delta = revlog.revision(node, raw=True)
930 delta = revlog.revision(node, raw=True)
884 except error.CensoredNodeError as e:
931 except error.CensoredNodeError as e:
885 delta = e.tombstone
932 delta = e.tombstone
886 if base == nullrev:
933 if base == nullrev:
887 prefix = mdiff.trivialdiffheader(len(delta))
934 prefix = mdiff.trivialdiffheader(len(delta))
888 else:
935 else:
889 baselen = revlog.rawsize(base)
936 baselen = revlog.rawsize(base)
890 prefix = mdiff.replacediffheader(baselen, len(delta))
937 prefix = mdiff.replacediffheader(baselen, len(delta))
891 elif base == nullrev:
938 elif base == nullrev:
892 delta = revlog.revision(node, raw=True)
939 delta = revlog.revision(node, raw=True)
893 prefix = mdiff.trivialdiffheader(len(delta))
940 prefix = mdiff.trivialdiffheader(len(delta))
894 else:
941 else:
895 delta = revlog.revdiff(base, rev)
942 delta = revlog.revdiff(base, rev)
896 p1n, p2n = revlog.parents(node)
943 p1n, p2n = revlog.parents(node)
897 basenode = revlog.node(base)
944 basenode = revlog.node(base)
898 flags = revlog.flags(rev)
945 flags = revlog.flags(rev)
899 meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode, flags)
946 meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode, flags)
900 meta += prefix
947 meta += prefix
901 l = len(meta) + len(delta)
948 l = len(meta) + len(delta)
902 yield chunkheader(l)
949 yield chunkheader(l)
903 yield meta
950 yield meta
904 yield delta
951 yield delta
905
952
906 def _revchunknarrow(self, revlog, rev, prev, linknode):
953 def _revchunknarrow(self, revlog, rev, prev, linknode):
907 # build up some mapping information that's useful later. See
954 # build up some mapping information that's useful later. See
908 # the local() nested function below.
955 # the local() nested function below.
909 if not self.changelog_done:
956 if not self.changelog_done:
910 self.clnode_to_rev[linknode] = rev
957 self.clnode_to_rev[linknode] = rev
911 linkrev = rev
958 linkrev = rev
912 self.clrev_to_localrev[linkrev] = rev
959 self.clrev_to_localrev[linkrev] = rev
913 else:
960 else:
914 linkrev = self.clnode_to_rev[linknode]
961 linkrev = self.clnode_to_rev[linknode]
915 self.clrev_to_localrev[linkrev] = rev
962 self.clrev_to_localrev[linkrev] = rev
916
963
917 # This is a node to send in full, because the changeset it
964 # This is a node to send in full, because the changeset it
918 # corresponds to was a full changeset.
965 # corresponds to was a full changeset.
919 if linknode in self.full_nodes:
966 if linknode in self.full_nodes:
920 for x in self._revchunknormal(revlog, rev, prev, linknode):
967 for x in self._revchunknormal(revlog, rev, prev, linknode):
921 yield x
968 yield x
922 return
969 return
923
970
924 # At this point, a node can either be one we should skip or an
971 # At this point, a node can either be one we should skip or an
925 # ellipsis. If it's not an ellipsis, bail immediately.
972 # ellipsis. If it's not an ellipsis, bail immediately.
926 if linkrev not in self.precomputed_ellipsis:
973 if linkrev not in self.precomputed_ellipsis:
927 return
974 return
928
975
929 linkparents = self.precomputed_ellipsis[linkrev]
976 linkparents = self.precomputed_ellipsis[linkrev]
930 def local(clrev):
977 def local(clrev):
931 """Turn a changelog revnum into a local revnum.
978 """Turn a changelog revnum into a local revnum.
932
979
933 The ellipsis dag is stored as revnums on the changelog,
980 The ellipsis dag is stored as revnums on the changelog,
934 but when we're producing ellipsis entries for
981 but when we're producing ellipsis entries for
935 non-changelog revlogs, we need to turn those numbers into
982 non-changelog revlogs, we need to turn those numbers into
936 something local. This does that for us, and during the
983 something local. This does that for us, and during the
937 changelog sending phase will also expand the stored
984 changelog sending phase will also expand the stored
938 mappings as needed.
985 mappings as needed.
939 """
986 """
940 if clrev == nullrev:
987 if clrev == nullrev:
941 return nullrev
988 return nullrev
942
989
943 if not self.changelog_done:
990 if not self.changelog_done:
944 # If we're doing the changelog, it's possible that we
991 # If we're doing the changelog, it's possible that we
945 # have a parent that is already on the client, and we
992 # have a parent that is already on the client, and we
946 # need to store some extra mapping information so that
993 # need to store some extra mapping information so that
947 # our contained ellipsis nodes will be able to resolve
994 # our contained ellipsis nodes will be able to resolve
948 # their parents.
995 # their parents.
949 if clrev not in self.clrev_to_localrev:
996 if clrev not in self.clrev_to_localrev:
950 clnode = revlog.node(clrev)
997 clnode = revlog.node(clrev)
951 self.clnode_to_rev[clnode] = clrev
998 self.clnode_to_rev[clnode] = clrev
952 return clrev
999 return clrev
953
1000
954 # Walk the ellipsis-ized changelog breadth-first looking for a
1001 # Walk the ellipsis-ized changelog breadth-first looking for a
955 # change that has been linked from the current revlog.
1002 # change that has been linked from the current revlog.
956 #
1003 #
957 # For a flat manifest revlog only a single step should be necessary
1004 # For a flat manifest revlog only a single step should be necessary
958 # as all relevant changelog entries are relevant to the flat
1005 # as all relevant changelog entries are relevant to the flat
959 # manifest.
1006 # manifest.
960 #
1007 #
961 # For a filelog or tree manifest dirlog however not every changelog
1008 # For a filelog or tree manifest dirlog however not every changelog
962 # entry will have been relevant, so we need to skip some changelog
1009 # entry will have been relevant, so we need to skip some changelog
963 # nodes even after ellipsis-izing.
1010 # nodes even after ellipsis-izing.
964 walk = [clrev]
1011 walk = [clrev]
965 while walk:
1012 while walk:
966 p = walk[0]
1013 p = walk[0]
967 walk = walk[1:]
1014 walk = walk[1:]
968 if p in self.clrev_to_localrev:
1015 if p in self.clrev_to_localrev:
969 return self.clrev_to_localrev[p]
1016 return self.clrev_to_localrev[p]
970 elif p in self.full_nodes:
1017 elif p in self.full_nodes:
971 walk.extend([pp for pp in self._repo.changelog.parentrevs(p)
1018 walk.extend([pp for pp in self._repo.changelog.parentrevs(p)
972 if pp != nullrev])
1019 if pp != nullrev])
973 elif p in self.precomputed_ellipsis:
1020 elif p in self.precomputed_ellipsis:
974 walk.extend([pp for pp in self.precomputed_ellipsis[p]
1021 walk.extend([pp for pp in self.precomputed_ellipsis[p]
975 if pp != nullrev])
1022 if pp != nullrev])
976 else:
1023 else:
977 # In this case, we've got an ellipsis with parents
1024 # In this case, we've got an ellipsis with parents
978 # outside the current bundle (likely an
1025 # outside the current bundle (likely an
979 # incremental pull). We "know" that we can use the
1026 # incremental pull). We "know" that we can use the
980 # value of this same revlog at whatever revision
1027 # value of this same revlog at whatever revision
981 # is pointed to by linknode. "Know" is in scare
1028 # is pointed to by linknode. "Know" is in scare
982 # quotes because I haven't done enough examination
1029 # quotes because I haven't done enough examination
983 # of edge cases to convince myself this is really
1030 # of edge cases to convince myself this is really
984 # a fact - it works for all the (admittedly
1031 # a fact - it works for all the (admittedly
985 # thorough) cases in our testsuite, but I would be
1032 # thorough) cases in our testsuite, but I would be
986 # somewhat unsurprised to find a case in the wild
1033 # somewhat unsurprised to find a case in the wild
987 # where this breaks down a bit. That said, I don't
1034 # where this breaks down a bit. That said, I don't
988 # know if it would hurt anything.
1035 # know if it would hurt anything.
989 for i in pycompat.xrange(rev, 0, -1):
1036 for i in pycompat.xrange(rev, 0, -1):
990 if revlog.linkrev(i) == clrev:
1037 if revlog.linkrev(i) == clrev:
991 return i
1038 return i
992 # We failed to resolve a parent for this node, so
1039 # We failed to resolve a parent for this node, so
993 # we crash the changegroup construction.
1040 # we crash the changegroup construction.
994 raise error.Abort(
1041 raise error.Abort(
995 'unable to resolve parent while packing %r %r'
1042 'unable to resolve parent while packing %r %r'
996 ' for changeset %r' % (revlog.indexfile, rev, clrev))
1043 ' for changeset %r' % (revlog.indexfile, rev, clrev))
997
1044
998 return nullrev
1045 return nullrev
999
1046
1000 if not linkparents or (
1047 if not linkparents or (
1001 revlog.parentrevs(rev) == (nullrev, nullrev)):
1048 revlog.parentrevs(rev) == (nullrev, nullrev)):
1002 p1, p2 = nullrev, nullrev
1049 p1, p2 = nullrev, nullrev
1003 elif len(linkparents) == 1:
1050 elif len(linkparents) == 1:
1004 p1, = sorted(local(p) for p in linkparents)
1051 p1, = sorted(local(p) for p in linkparents)
1005 p2 = nullrev
1052 p2 = nullrev
1006 else:
1053 else:
1007 p1, p2 = sorted(local(p) for p in linkparents)
1054 p1, p2 = sorted(local(p) for p in linkparents)
1008 n = revlog.node(rev)
1055 n = revlog.node(rev)
1009
1056
1010 yield ellipsisdata(
1057 yield ellipsisdata(
1011 self, rev, revlog, p1, p2, revlog.revision(n), linknode)
1058 self, rev, revlog, p1, p2, revlog.revision(n), linknode)
1012
1059
1013 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1060 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1014 # do nothing with basenode, it is implicitly the previous one in HG10
1061 # do nothing with basenode, it is implicitly the previous one in HG10
1015 # do nothing with flags, it is implicitly 0 for cg1 and cg2
1062 # do nothing with flags, it is implicitly 0 for cg1 and cg2
1016 return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
1063 return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
1017
1064
1018 class cg2packer(cg1packer):
1065 class cg2packer(cg1packer):
1019 version = '02'
1066 version = '02'
1020 deltaheader = _CHANGEGROUPV2_DELTA_HEADER
1067 deltaheader = _CHANGEGROUPV2_DELTA_HEADER
1021
1068
1022 def __init__(self, repo, filematcher, bundlecaps=None):
1069 def __init__(self, repo, filematcher, bundlecaps=None):
1023 super(cg2packer, self).__init__(repo, filematcher,
1070 super(cg2packer, self).__init__(repo, filematcher,
1024 bundlecaps=bundlecaps)
1071 bundlecaps=bundlecaps)
1025
1072
1026 if self._reorder is None:
1073 if self._reorder is None:
1027 # Since generaldelta is directly supported by cg2, reordering
1074 # Since generaldelta is directly supported by cg2, reordering
1028 # generally doesn't help, so we disable it by default (treating
1075 # generally doesn't help, so we disable it by default (treating
1029 # bundle.reorder=auto just like bundle.reorder=False).
1076 # bundle.reorder=auto just like bundle.reorder=False).
1030 self._reorder = False
1077 self._reorder = False
1031
1078
1032 def deltaparent(self, revlog, rev, p1, p2, prev):
1079 def deltaparent(self, revlog, rev, p1, p2, prev):
1033 # Narrow ellipses mode.
1080 # Narrow ellipses mode.
1034 if util.safehasattr(self, 'full_nodes'):
1081 if util.safehasattr(self, 'full_nodes'):
1035 # TODO: send better deltas when in narrow mode.
1082 # TODO: send better deltas when in narrow mode.
1036 #
1083 #
1037 # changegroup.group() loops over revisions to send,
1084 # changegroup.group() loops over revisions to send,
1038 # including revisions we'll skip. What this means is that
1085 # including revisions we'll skip. What this means is that
1039 # `prev` will be a potentially useless delta base for all
1086 # `prev` will be a potentially useless delta base for all
1040 # ellipsis nodes, as the client likely won't have it. In
1087 # ellipsis nodes, as the client likely won't have it. In
1041 # the future we should do bookkeeping about which nodes
1088 # the future we should do bookkeeping about which nodes
1042 # have been sent to the client, and try to be
1089 # have been sent to the client, and try to be
1043 # significantly smarter about delta bases. This is
1090 # significantly smarter about delta bases. This is
1044 # slightly tricky because this same code has to work for
1091 # slightly tricky because this same code has to work for
1045 # all revlogs, and we don't have the linkrev/linknode here.
1092 # all revlogs, and we don't have the linkrev/linknode here.
1046 return p1
1093 return p1
1047
1094
1048 dp = revlog.deltaparent(rev)
1095 dp = revlog.deltaparent(rev)
1049 if dp == nullrev and revlog.storedeltachains:
1096 if dp == nullrev and revlog.storedeltachains:
1050 # Avoid sending full revisions when delta parent is null. Pick prev
1097 # Avoid sending full revisions when delta parent is null. Pick prev
1051 # in that case. It's tempting to pick p1 in this case, as p1 will
1098 # in that case. It's tempting to pick p1 in this case, as p1 will
1052 # be smaller in the common case. However, computing a delta against
1099 # be smaller in the common case. However, computing a delta against
1053 # p1 may require resolving the raw text of p1, which could be
1100 # p1 may require resolving the raw text of p1, which could be
1054 # expensive. The revlog caches should have prev cached, meaning
1101 # expensive. The revlog caches should have prev cached, meaning
1055 # less CPU for changegroup generation. There is likely room to add
1102 # less CPU for changegroup generation. There is likely room to add
1056 # a flag and/or config option to control this behavior.
1103 # a flag and/or config option to control this behavior.
1057 base = prev
1104 base = prev
1058 elif dp == nullrev:
1105 elif dp == nullrev:
1059 # revlog is configured to use full snapshot for a reason,
1106 # revlog is configured to use full snapshot for a reason,
1060 # stick to full snapshot.
1107 # stick to full snapshot.
1061 base = nullrev
1108 base = nullrev
1062 elif dp not in (p1, p2, prev):
1109 elif dp not in (p1, p2, prev):
1063 # Pick prev when we can't be sure remote has the base revision.
1110 # Pick prev when we can't be sure remote has the base revision.
1064 return prev
1111 return prev
1065 else:
1112 else:
1066 base = dp
1113 base = dp
1067 if base != nullrev and not revlog.candelta(base, rev):
1114 if base != nullrev and not revlog.candelta(base, rev):
1068 base = nullrev
1115 base = nullrev
1069 return base
1116 return base
1070
1117
1071 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1118 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1072 # Do nothing with flags, it is implicitly 0 in cg1 and cg2
1119 # Do nothing with flags, it is implicitly 0 in cg1 and cg2
1073 return struct.pack(self.deltaheader, node, p1n, p2n, basenode, linknode)
1120 return struct.pack(self.deltaheader, node, p1n, p2n, basenode, linknode)
1074
1121
1075 class cg3packer(cg2packer):
1122 class cg3packer(cg2packer):
1076 version = '03'
1123 version = '03'
1077 deltaheader = _CHANGEGROUPV3_DELTA_HEADER
1124 deltaheader = _CHANGEGROUPV3_DELTA_HEADER
1078
1125
1079 def _packmanifests(self, dir, mfnodes, lookuplinknode):
1126 def _packmanifests(self, dir, mfnodes, lookuplinknode):
1080 if dir:
1127 if dir:
1081 yield self.fileheader(dir)
1128 yield self.fileheader(dir)
1082
1129
1083 dirlog = self._repo.manifestlog._revlog.dirlog(dir)
1130 dirlog = self._repo.manifestlog._revlog.dirlog(dir)
1084 for chunk in self.group(mfnodes, dirlog, lookuplinknode,
1131 for chunk in self.group(mfnodes, dirlog, lookuplinknode,
1085 units=_('manifests')):
1132 units=_('manifests')):
1086 yield chunk
1133 yield chunk
1087
1134
1088 def _manifestsdone(self):
1135 def _manifestsdone(self):
1089 return self.close()
1136 return self.close()
1090
1137
1091 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1138 def builddeltaheader(self, node, p1n, p2n, basenode, linknode, flags):
1092 return struct.pack(
1139 return struct.pack(
1093 self.deltaheader, node, p1n, p2n, basenode, linknode, flags)
1140 self.deltaheader, node, p1n, p2n, basenode, linknode, flags)
1094
1141
1095 _packermap = {'01': (cg1packer, cg1unpacker),
1142 _packermap = {'01': (cg1packer, cg1unpacker),
1096 # cg2 adds support for exchanging generaldelta
1143 # cg2 adds support for exchanging generaldelta
1097 '02': (cg2packer, cg2unpacker),
1144 '02': (cg2packer, cg2unpacker),
1098 # cg3 adds support for exchanging revlog flags and treemanifests
1145 # cg3 adds support for exchanging revlog flags and treemanifests
1099 '03': (cg3packer, cg3unpacker),
1146 '03': (cg3packer, cg3unpacker),
1100 }
1147 }
1101
1148
1102 def allsupportedversions(repo):
1149 def allsupportedversions(repo):
1103 versions = set(_packermap.keys())
1150 versions = set(_packermap.keys())
1104 if not (repo.ui.configbool('experimental', 'changegroup3') or
1151 if not (repo.ui.configbool('experimental', 'changegroup3') or
1105 repo.ui.configbool('experimental', 'treemanifest') or
1152 repo.ui.configbool('experimental', 'treemanifest') or
1106 'treemanifest' in repo.requirements):
1153 'treemanifest' in repo.requirements):
1107 versions.discard('03')
1154 versions.discard('03')
1108 return versions
1155 return versions
1109
1156
1110 # Changegroup versions that can be applied to the repo
1157 # Changegroup versions that can be applied to the repo
1111 def supportedincomingversions(repo):
1158 def supportedincomingversions(repo):
1112 return allsupportedversions(repo)
1159 return allsupportedversions(repo)
1113
1160
1114 # Changegroup versions that can be created from the repo
1161 # Changegroup versions that can be created from the repo
1115 def supportedoutgoingversions(repo):
1162 def supportedoutgoingversions(repo):
1116 versions = allsupportedversions(repo)
1163 versions = allsupportedversions(repo)
1117 if 'treemanifest' in repo.requirements:
1164 if 'treemanifest' in repo.requirements:
1118 # Versions 01 and 02 support only flat manifests and it's just too
1165 # Versions 01 and 02 support only flat manifests and it's just too
1119 # expensive to convert between the flat manifest and tree manifest on
1166 # expensive to convert between the flat manifest and tree manifest on
1120 # the fly. Since tree manifests are hashed differently, all of history
1167 # the fly. Since tree manifests are hashed differently, all of history
1121 # would have to be converted. Instead, we simply don't even pretend to
1168 # would have to be converted. Instead, we simply don't even pretend to
1122 # support versions 01 and 02.
1169 # support versions 01 and 02.
1123 versions.discard('01')
1170 versions.discard('01')
1124 versions.discard('02')
1171 versions.discard('02')
1125 if repository.NARROW_REQUIREMENT in repo.requirements:
1172 if repository.NARROW_REQUIREMENT in repo.requirements:
1126 # Versions 01 and 02 don't support revlog flags, and we need to
1173 # Versions 01 and 02 don't support revlog flags, and we need to
1127 # support that for stripping and unbundling to work.
1174 # support that for stripping and unbundling to work.
1128 versions.discard('01')
1175 versions.discard('01')
1129 versions.discard('02')
1176 versions.discard('02')
1130 if LFS_REQUIREMENT in repo.requirements:
1177 if LFS_REQUIREMENT in repo.requirements:
1131 # Versions 01 and 02 don't support revlog flags, and we need to
1178 # Versions 01 and 02 don't support revlog flags, and we need to
1132 # mark LFS entries with REVIDX_EXTSTORED.
1179 # mark LFS entries with REVIDX_EXTSTORED.
1133 versions.discard('01')
1180 versions.discard('01')
1134 versions.discard('02')
1181 versions.discard('02')
1135
1182
1136 return versions
1183 return versions
1137
1184
1138 def localversion(repo):
1185 def localversion(repo):
1139 # Finds the best version to use for bundles that are meant to be used
1186 # Finds the best version to use for bundles that are meant to be used
1140 # locally, such as those from strip and shelve, and temporary bundles.
1187 # locally, such as those from strip and shelve, and temporary bundles.
1141 return max(supportedoutgoingversions(repo))
1188 return max(supportedoutgoingversions(repo))
1142
1189
1143 def safeversion(repo):
1190 def safeversion(repo):
1144 # Finds the smallest version that it's safe to assume clients of the repo
1191 # Finds the smallest version that it's safe to assume clients of the repo
1145 # will support. For example, all hg versions that support generaldelta also
1192 # will support. For example, all hg versions that support generaldelta also
1146 # support changegroup 02.
1193 # support changegroup 02.
1147 versions = supportedoutgoingversions(repo)
1194 versions = supportedoutgoingversions(repo)
1148 if 'generaldelta' in repo.requirements:
1195 if 'generaldelta' in repo.requirements:
1149 versions.discard('01')
1196 versions.discard('01')
1150 assert versions
1197 assert versions
1151 return min(versions)
1198 return min(versions)
1152
1199
1153 def getbundler(version, repo, bundlecaps=None, filematcher=None):
1200 def getbundler(version, repo, bundlecaps=None, filematcher=None):
1154 assert version in supportedoutgoingversions(repo)
1201 assert version in supportedoutgoingversions(repo)
1155
1202
1156 if filematcher is None:
1203 if filematcher is None:
1157 filematcher = matchmod.alwaysmatcher(repo.root, '')
1204 filematcher = matchmod.alwaysmatcher(repo.root, '')
1158
1205
1159 if version == '01' and not filematcher.always():
1206 if version == '01' and not filematcher.always():
1160 raise error.ProgrammingError('version 01 changegroups do not support '
1207 raise error.ProgrammingError('version 01 changegroups do not support '
1161 'sparse file matchers')
1208 'sparse file matchers')
1162
1209
1163 # Requested files could include files not in the local store. So
1210 # Requested files could include files not in the local store. So
1164 # filter those out.
1211 # filter those out.
1165 filematcher = matchmod.intersectmatchers(repo.narrowmatch(),
1212 filematcher = matchmod.intersectmatchers(repo.narrowmatch(),
1166 filematcher)
1213 filematcher)
1167
1214
1168 return _packermap[version][0](repo, filematcher=filematcher,
1215 return _packermap[version][0](repo, filematcher=filematcher,
1169 bundlecaps=bundlecaps)
1216 bundlecaps=bundlecaps)
1170
1217
1171 def getunbundler(version, fh, alg, extras=None):
1218 def getunbundler(version, fh, alg, extras=None):
1172 return _packermap[version][1](fh, alg, extras=extras)
1219 return _packermap[version][1](fh, alg, extras=extras)
1173
1220
1174 def _changegroupinfo(repo, nodes, source):
1221 def _changegroupinfo(repo, nodes, source):
1175 if repo.ui.verbose or source == 'bundle':
1222 if repo.ui.verbose or source == 'bundle':
1176 repo.ui.status(_("%d changesets found\n") % len(nodes))
1223 repo.ui.status(_("%d changesets found\n") % len(nodes))
1177 if repo.ui.debugflag:
1224 if repo.ui.debugflag:
1178 repo.ui.debug("list of changesets:\n")
1225 repo.ui.debug("list of changesets:\n")
1179 for node in nodes:
1226 for node in nodes:
1180 repo.ui.debug("%s\n" % hex(node))
1227 repo.ui.debug("%s\n" % hex(node))
1181
1228
1182 def makechangegroup(repo, outgoing, version, source, fastpath=False,
1229 def makechangegroup(repo, outgoing, version, source, fastpath=False,
1183 bundlecaps=None):
1230 bundlecaps=None):
1184 cgstream = makestream(repo, outgoing, version, source,
1231 cgstream = makestream(repo, outgoing, version, source,
1185 fastpath=fastpath, bundlecaps=bundlecaps)
1232 fastpath=fastpath, bundlecaps=bundlecaps)
1186 return getunbundler(version, util.chunkbuffer(cgstream), None,
1233 return getunbundler(version, util.chunkbuffer(cgstream), None,
1187 {'clcount': len(outgoing.missing) })
1234 {'clcount': len(outgoing.missing) })
1188
1235
1189 def makestream(repo, outgoing, version, source, fastpath=False,
1236 def makestream(repo, outgoing, version, source, fastpath=False,
1190 bundlecaps=None, filematcher=None):
1237 bundlecaps=None, filematcher=None):
1191 bundler = getbundler(version, repo, bundlecaps=bundlecaps,
1238 bundler = getbundler(version, repo, bundlecaps=bundlecaps,
1192 filematcher=filematcher)
1239 filematcher=filematcher)
1193
1240
1194 repo = repo.unfiltered()
1241 repo = repo.unfiltered()
1195 commonrevs = outgoing.common
1242 commonrevs = outgoing.common
1196 csets = outgoing.missing
1243 csets = outgoing.missing
1197 heads = outgoing.missingheads
1244 heads = outgoing.missingheads
1198 # We go through the fast path if we get told to, or if all (unfiltered
1245 # We go through the fast path if we get told to, or if all (unfiltered
1199 # heads have been requested (since we then know there all linkrevs will
1246 # heads have been requested (since we then know there all linkrevs will
1200 # be pulled by the client).
1247 # be pulled by the client).
1201 heads.sort()
1248 heads.sort()
1202 fastpathlinkrev = fastpath or (
1249 fastpathlinkrev = fastpath or (
1203 repo.filtername is None and heads == sorted(repo.heads()))
1250 repo.filtername is None and heads == sorted(repo.heads()))
1204
1251
1205 repo.hook('preoutgoing', throw=True, source=source)
1252 repo.hook('preoutgoing', throw=True, source=source)
1206 _changegroupinfo(repo, csets, source)
1253 _changegroupinfo(repo, csets, source)
1207 return bundler.generate(commonrevs, csets, fastpathlinkrev, source)
1254 return bundler.generate(commonrevs, csets, fastpathlinkrev, source)
1208
1255
1209 def _addchangegroupfiles(repo, source, revmap, trp, expectedfiles, needfiles):
1256 def _addchangegroupfiles(repo, source, revmap, trp, expectedfiles, needfiles):
1210 revisions = 0
1257 revisions = 0
1211 files = 0
1258 files = 0
1212 progress = repo.ui.makeprogress(_('files'), unit=_('files'),
1259 progress = repo.ui.makeprogress(_('files'), unit=_('files'),
1213 total=expectedfiles)
1260 total=expectedfiles)
1214 for chunkdata in iter(source.filelogheader, {}):
1261 for chunkdata in iter(source.filelogheader, {}):
1215 files += 1
1262 files += 1
1216 f = chunkdata["filename"]
1263 f = chunkdata["filename"]
1217 repo.ui.debug("adding %s revisions\n" % f)
1264 repo.ui.debug("adding %s revisions\n" % f)
1218 progress.increment()
1265 progress.increment()
1219 fl = repo.file(f)
1266 fl = repo.file(f)
1220 o = len(fl)
1267 o = len(fl)
1221 try:
1268 try:
1222 deltas = source.deltaiter()
1269 deltas = source.deltaiter()
1223 if not fl.addgroup(deltas, revmap, trp):
1270 if not fl.addgroup(deltas, revmap, trp):
1224 raise error.Abort(_("received file revlog group is empty"))
1271 raise error.Abort(_("received file revlog group is empty"))
1225 except error.CensoredBaseError as e:
1272 except error.CensoredBaseError as e:
1226 raise error.Abort(_("received delta base is censored: %s") % e)
1273 raise error.Abort(_("received delta base is censored: %s") % e)
1227 revisions += len(fl) - o
1274 revisions += len(fl) - o
1228 if f in needfiles:
1275 if f in needfiles:
1229 needs = needfiles[f]
1276 needs = needfiles[f]
1230 for new in pycompat.xrange(o, len(fl)):
1277 for new in pycompat.xrange(o, len(fl)):
1231 n = fl.node(new)
1278 n = fl.node(new)
1232 if n in needs:
1279 if n in needs:
1233 needs.remove(n)
1280 needs.remove(n)
1234 else:
1281 else:
1235 raise error.Abort(
1282 raise error.Abort(
1236 _("received spurious file revlog entry"))
1283 _("received spurious file revlog entry"))
1237 if not needs:
1284 if not needs:
1238 del needfiles[f]
1285 del needfiles[f]
1239 progress.complete()
1286 progress.complete()
1240
1287
1241 for f, needs in needfiles.iteritems():
1288 for f, needs in needfiles.iteritems():
1242 fl = repo.file(f)
1289 fl = repo.file(f)
1243 for n in needs:
1290 for n in needs:
1244 try:
1291 try:
1245 fl.rev(n)
1292 fl.rev(n)
1246 except error.LookupError:
1293 except error.LookupError:
1247 raise error.Abort(
1294 raise error.Abort(
1248 _('missing file data for %s:%s - run hg verify') %
1295 _('missing file data for %s:%s - run hg verify') %
1249 (f, hex(n)))
1296 (f, hex(n)))
1250
1297
1251 return revisions, files
1298 return revisions, files
1252
1299
1253 def _packellipsischangegroup(repo, common, match, relevant_nodes,
1300 def _packellipsischangegroup(repo, common, match, relevant_nodes,
1254 ellipsisroots, visitnodes, depth, source, version):
1301 ellipsisroots, visitnodes, depth, source, version):
1255 if version in ('01', '02'):
1302 if version in ('01', '02'):
1256 raise error.Abort(
1303 raise error.Abort(
1257 'ellipsis nodes require at least cg3 on client and server, '
1304 'ellipsis nodes require at least cg3 on client and server, '
1258 'but negotiated version %s' % version)
1305 'but negotiated version %s' % version)
1259 # We wrap cg1packer.revchunk, using a side channel to pass
1306 # We wrap cg1packer.revchunk, using a side channel to pass
1260 # relevant_nodes into that area. Then if linknode isn't in the
1307 # relevant_nodes into that area. Then if linknode isn't in the
1261 # set, we know we have an ellipsis node and we should defer
1308 # set, we know we have an ellipsis node and we should defer
1262 # sending that node's data. We override close() to detect
1309 # sending that node's data. We override close() to detect
1263 # pending ellipsis nodes and flush them.
1310 # pending ellipsis nodes and flush them.
1264 packer = getbundler(version, repo, filematcher=match)
1311 packer = getbundler(version, repo, filematcher=match)
1265 # Give the packer the list of nodes which should not be
1312 # Give the packer the list of nodes which should not be
1266 # ellipsis nodes. We store this rather than the set of nodes
1313 # ellipsis nodes. We store this rather than the set of nodes
1267 # that should be an ellipsis because for very large histories
1314 # that should be an ellipsis because for very large histories
1268 # we expect this to be significantly smaller.
1315 # we expect this to be significantly smaller.
1269 packer.full_nodes = relevant_nodes
1316 packer.full_nodes = relevant_nodes
1270 # Maps ellipsis revs to their roots at the changelog level.
1317 # Maps ellipsis revs to their roots at the changelog level.
1271 packer.precomputed_ellipsis = ellipsisroots
1318 packer.precomputed_ellipsis = ellipsisroots
1272 # Maps CL revs to per-revlog revisions. Cleared in close() at
1319 # Maps CL revs to per-revlog revisions. Cleared in close() at
1273 # the end of each group.
1320 # the end of each group.
1274 packer.clrev_to_localrev = {}
1321 packer.clrev_to_localrev = {}
1275 packer.next_clrev_to_localrev = {}
1322 packer.next_clrev_to_localrev = {}
1276 # Maps changelog nodes to changelog revs. Filled in once
1323 # Maps changelog nodes to changelog revs. Filled in once
1277 # during changelog stage and then left unmodified.
1324 # during changelog stage and then left unmodified.
1278 packer.clnode_to_rev = {}
1325 packer.clnode_to_rev = {}
1279 packer.changelog_done = False
1326 packer.changelog_done = False
1280 # If true, informs the packer that it is serving shallow content and might
1327 # If true, informs the packer that it is serving shallow content and might
1281 # need to pack file contents not introduced by the changes being packed.
1328 # need to pack file contents not introduced by the changes being packed.
1282 packer.is_shallow = depth is not None
1329 packer.is_shallow = depth is not None
1283
1330
1284 return packer.generate(common, visitnodes, False, source)
1331 return packer.generate(common, visitnodes, False, source)
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now