Debian Codegraph @

hgext/remotefilelog/shallowbundle.py

raw
1 # shallowbundle.py - bundle10 implementation for use with shallow repositories
2 #
3 # Copyright 2013 Facebook, Inc.
4 #
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.
7
8 from __future__ import annotations
9
10 from mercurial.i18n import _
11 from mercurial.node import bin, hex
12 from mercurial import (
13 bundlerepo,
14 changegroup,
15 error,
16 match,
17 mdiff,
18 )
19 from . import (
20 constants,
21 shallowutil,
22 )
23
24 NoFiles = 0
25 LocalFiles = 1
26 AllFiles = 2
27
28
29 class ShallowCGPacker(changegroup.cgpacker):
30 def generate(
31 self,
32 commonrevs,
33 clnodes,
34 fastpathlinkrev,
35 source,
36 changelog=True,
37 **kwargs,
38 ):
39 if shallowutil.isenabled(self._repo):
40 fastpathlinkrev = False
41
42 return super().generate(
43 commonrevs,
44 clnodes,
45 fastpathlinkrev,
46 source,
47 changelog,
48 **kwargs,
49 )
50
51 def generatefiles(self, changedfiles, *args, **kwargs):
52 try:
53 linknodes, commonrevs, source = args
54 except ValueError:
55 commonrevs, source, mfdicts, fastpathlinkrev, fnodes, clrevs = args
56 if shallowutil.isenabled(self._repo):
57 repo = self._repo
58 if isinstance(repo, bundlerepo.bundlerepository):
59 # If the bundle contains filelogs, we can't pull from it, since
60 # bundlerepo is heavily tied to revlogs. Instead require that
61 # the user use unbundle instead.
62 # Force load the filelog data.
63 bundlerepo.bundlerepository.file(repo, b'foo')
64 if repo._cgfilespos:
65 raise error.Abort(
66 b"cannot pull from full bundles",
67 hint=b"use `hg unbundle` instead",
68 )
69 return []
70 filestosend = self.shouldaddfilegroups(source)
71 if filestosend == NoFiles:
72 changedfiles = list(
73 # The ``repo`` field is typed on changegroup.cgpacker to be
74 # a standard repo, but the method is tacked onto the repo
75 # object in ``makechangegroup()`` below.
76 # pytype: disable=attribute-error
77 [f for f in changedfiles if not repo.shallowmatch(f)]
78 # pytype: enable=attribute-error
79 )
80
81 return super().generatefiles(changedfiles, *args, **kwargs)
82
83 def shouldaddfilegroups(self, source):
84 repo = self._repo
85 if not shallowutil.isenabled(repo):
86 return AllFiles
87
88 if source == b"push" or source == b"bundle":
89 return AllFiles
90
91 # We won't actually strip the files, but we should put them in any
92 # backup bundle generated by strip (especially for cases like narrow's
93 # `hg tracked --removeinclude`, as failing to do so means that the
94 # "saved" changesets during a strip won't have their files reapplied and
95 # thus their linknode adjusted, if necessary).
96 if source == b"strip":
97 cfg = repo.ui.config(b'remotefilelog', b'strip.includefiles')
98 if cfg == b'local':
99 return LocalFiles
100 elif cfg != b'none':
101 return AllFiles
102
103 caps = self._bundlecaps or []
104 if source == b"serve" or source == b"pull":
105 if constants.BUNDLE2_CAPABLITY in caps:
106 return LocalFiles
107 else:
108 # Serving to a full repo requires us to serve everything
109 repo.ui.warn(_(b"pulling from a shallow repo\n"))
110 return AllFiles
111
112 return NoFiles
113
114
115 def makechangegroup(orig, repo, outgoing, version, source, *args, **kwargs):
116 if not shallowutil.isenabled(repo):
117 return orig(repo, outgoing, version, source, *args, **kwargs)
118
119 original = repo.shallowmatch
120 try:
121 # if serving, only send files the clients has patterns for
122 if source == b'serve':
123 bundlecaps = kwargs.get('bundlecaps')
124 includepattern = None
125 excludepattern = None
126 for cap in bundlecaps or []:
127 if cap.startswith(b"includepattern="):
128 raw = cap[len(b"includepattern=") :]
129 if raw:
130 includepattern = raw.split(b'\0')
131 elif cap.startswith(b"excludepattern="):
132 raw = cap[len(b"excludepattern=") :]
133 if raw:
134 excludepattern = raw.split(b'\0')
135 if includepattern or excludepattern:
136 repo.shallowmatch = match.match(
137 repo.root, b'', None, includepattern, excludepattern
138 )
139 else:
140 repo.shallowmatch = match.always()
141 return orig(repo, outgoing, version, source, *args, **kwargs)
142 finally:
143 repo.shallowmatch = original
144
145
146 def wrap_bundler(orig, *args, **kwargs):
147 cg = orig(*args, **kwargs)
148
149 class Packer(ShallowCGPacker, cg.__class__):
150 pass
151
152 cg.__class__ = Packer
153 return cg
154
155
156 def addchangegroupfiles(
157 orig, repo, source, revmap, trp, expectedfiles, *args, **kwargs
158 ):
159 if not shallowutil.isenabled(repo):
160 return orig(repo, source, revmap, trp, expectedfiles, *args, **kwargs)
161
162 newfiles = 0
163 visited = set()
164 revisiondatas = {}
165 queue = []
166
167 # Normal Mercurial processes each file one at a time, adding all
168 # the new revisions for that file at once. In remotefilelog a file
169 # revision may depend on a different file's revision (in the case
170 # of a rename/copy), so we must lay all revisions down across all
171 # files in topological order.
172
173 # read all the file chunks but don't add them
174 progress = repo.ui.makeprogress(_(b'files'), total=expectedfiles)
175 while True:
176 chunkdata = source.filelogheader()
177 if not chunkdata:
178 break
179 f = chunkdata[b"filename"]
180 repo.ui.debug(b"adding %s revisions\n" % f)
181 progress.increment()
182
183 if not repo.shallowmatch(f):
184 fl = repo.file(f, writable=True)
185 deltas = source.deltaiter()
186 fl.addgroup(deltas, revmap, trp)
187 continue
188
189 chain = None
190 while True:
191 # returns: None or (
192 # node,
193 # p1,
194 # p2,
195 # cs,
196 # deltabase,
197 # delta,
198 # flags,
199 # sidedata,
200 # proto_flags
201 # )
202 revisiondata = source.deltachunk(chain)
203 if not revisiondata:
204 break
205
206 chain = revisiondata.node
207
208 revisiondatas[(f, chain)] = revisiondata
209 queue.append((f, chain))
210
211 if f not in visited:
212 newfiles += 1
213 visited.add(f)
214
215 if chain is None:
216 raise error.Abort(_(b"received file revlog group is empty"))
217
218 processed = set()
219
220 def available(f, node, depf, depnode):
221 if depnode != repo.nullid and (depf, depnode) not in processed:
222 if not (depf, depnode) in revisiondatas:
223 # It's not in the changegroup, assume it's already
224 # in the repo
225 return True
226 # re-add self to queue
227 queue.insert(0, (f, node))
228 # add dependency in front
229 queue.insert(0, (depf, depnode))
230 return False
231 return True
232
233 skipcount = 0
234
235 # Prefetch the non-bundled revisions that we will need
236 prefetchfiles = []
237 for f, node in queue:
238 revisiondata = revisiondatas[(f, node)]
239 # revisiondata: (node, p1, p2, cs, deltabase, delta, flags, sdata, pfl)
240 dependents = [revisiondata.p1, revisiondata.p2, revisiondata.delta_base]
241
242 for dependent in dependents:
243 if dependent == repo.nullid or (f, dependent) in revisiondatas:
244 continue
245 prefetchfiles.append((f, hex(dependent)))
246
247 repo.fileservice.prefetch(prefetchfiles)
248
249 # Apply the revisions in topological order such that a revision
250 # is only written once it's deltabase and parents have been written.
251 while queue:
252 f, node = queue.pop(0)
253 if (f, node) in processed:
254 continue
255
256 skipcount += 1
257 if skipcount > len(queue) + 1:
258 raise error.Abort(_(b"circular node dependency"))
259
260 fl = repo.file(f)
261
262 rdata = revisiondatas[(f, node)]
263 if not available(f, rdata.node, f, rdata.delta_base):
264 continue
265
266 base = fl.rawdata(rdata.delta_base)
267 text = mdiff.patch(base, rdata.delta)
268 if not isinstance(text, bytes):
269 text = bytes(text)
270
271 meta, text = shallowutil.parsemeta(text)
272 if b'copy' in meta:
273 copyfrom = meta[b'copy']
274 copynode = bin(meta[b'copyrev'])
275 if not available(f, rdata.node, copyfrom, copynode):
276 continue
277
278 for p in [rdata.p1, rdata.p2]:
279 if p != repo.nullid:
280 if not available(f, rdata.node, f, p):
281 continue
282
283 # XXX why don't we use the flag field !
284 fl.add(text, meta, trp, rdata.link_node, rdata.p1, rdata.p2)
285 processed.add((f, rdata.node))
286 skipcount = 0
287
288 progress.complete()
289
290 return len(revisiondatas), newfiles