Debian Codegraph @

hgext/lfs/wrapper.py

raw
1 # wrapper.py - methods wrapping core mercurial logic
2 #
3 # Copyright 2017 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 import hashlib
11 import typing
12
13 from mercurial.i18n import _
14 from mercurial.node import bin, hex, short
15
16 from mercurial import (
17 bundle2,
18 changegroup,
19 cmdutil,
20 context,
21 error,
22 exchange,
23 exthelper,
24 requirements as req_mod,
25 revlog,
26 scmutil,
27 vfs as vfsmod,
28 wireprotov1server,
29 )
30
31 from mercurial.upgrade_utils import (
32 actions as upgrade_actions,
33 engine as upgrade_engine,
34 )
35
36 from mercurial.utils import (
37 storageutil,
38 stringutil,
39 )
40
41 from ..largefiles import lfutil
42
43 from . import (
44 blobstore,
45 pointer,
46 )
47
48 if typing.TYPE_CHECKING:
49 from typing import (
50 Callable,
51 )
52 from mercurial.interfaces.types import (
53 RepoT,
54 RequirementSetT,
55 UiT,
56 )
57
58 eh = exthelper.exthelper()
59
60
61 @eh.wrapfunction(changegroup, 'allsupportedversions')
62 def allsupportedversions(
63 orig: Callable[[RepoT], set[bytes]], repo: RepoT
64 ) -> set[bytes]:
65 versions = orig(repo)
66 versions.add(b'03')
67 return versions
68
69
70 @eh.wrapfunction(wireprotov1server, '_capabilities')
71 def _capabilities(orig, repo, proto):
72 '''Wrap server command to announce lfs server capability'''
73 caps = orig(repo, proto)
74 if hasattr(repo.svfs, 'lfslocalblobstore'):
75 # Advertise a slightly different capability when lfs is *required*, so
76 # that the client knows it MUST load the extension. If lfs is not
77 # required on the server, there's no reason to autoload the extension
78 # on the client.
79 if req_mod.LFS_REQUIREMENT in repo.requirements:
80 caps.append(b'lfs-serve')
81
82 caps.append(b'lfs')
83 return caps
84
85
86 def bypasscheckhash(self, text):
87 return False
88
89
90 def readfromstore(self, text):
91 """Read filelog content from local blobstore transform for flagprocessor.
92
93 Default tranform for flagprocessor, returning contents from blobstore.
94 Returns a 2-typle (text, validatehash) where validatehash is True as the
95 contents of the blobstore should be checked using checkhash.
96 """
97 p = pointer.deserialize(text)
98 oid = p.oid()
99 store = self.opener.lfslocalblobstore
100 if not store.has(oid):
101 p.filename = self.filename
102 self.opener.lfsremoteblobstore.readbatch([p], store)
103
104 # The caller will validate the content
105 text = store.read(oid, verify=False)
106
107 # pack hg filelog metadata
108 hgmeta = {}
109 for k in p.keys():
110 if k.startswith(b'x-hg-'):
111 name = k[len(b'x-hg-') :]
112 hgmeta[name] = p[k]
113 if hgmeta or text.startswith(b'\1\n'):
114 text = storageutil.packmeta(hgmeta, text)
115
116 return (text, True)
117
118
119 def writetostore(self, text):
120 # hg filelog metadata (includes rename, etc)
121 hgmeta, offset = storageutil.parsemeta(text)
122 if offset and offset > 0:
123 # lfs blob does not contain hg filelog metadata
124 text = text[offset:]
125
126 # git-lfs only supports sha256
127 oid = hex(hashlib.sha256(text).digest())
128 self.opener.lfslocalblobstore.write(oid, text)
129
130 # replace contents with metadata
131 longoid = b'sha256:%s' % oid
132 metadata = pointer.gitlfspointer(oid=longoid, size=b'%d' % len(text))
133
134 # by default, we expect the content to be binary. however, LFS could also
135 # be used for non-binary content. add a special entry for non-binary data.
136 # this will be used by filectx.isbinary().
137 if not stringutil.binary(text):
138 # not hg filelog metadata (affecting commit hash), no "x-hg-" prefix
139 metadata[b'x-is-binary'] = b'0'
140
141 # translate hg filelog metadata to lfs metadata with "x-hg-" prefix
142 if hgmeta is not None:
143 for k, v in hgmeta.items():
144 metadata[b'x-hg-%s' % k] = v
145
146 rawtext = metadata.serialize()
147 return (rawtext, False)
148
149
150 def _islfs(rlog, node=None, rev=None):
151 if rev is None:
152 if node is None:
153 # both None - likely working copy content where node is not ready
154 return False
155 rev = rlog.rev(node)
156 else:
157 node = rlog.node(rev)
158 if node == rlog.nullid:
159 return False
160 flags = rlog.flags(rev)
161 return bool(flags & revlog.REVIDX_EXTSTORED)
162
163
164 # Wrapping may also be applied by remotefilelog
165 def filelogaddrevision(
166 orig,
167 self,
168 text,
169 transaction,
170 link,
171 p1,
172 p2,
173 cachedelta=None,
174 node=None,
175 flags=revlog.REVIDX_DEFAULT_FLAGS,
176 **kwds,
177 ):
178 # The matcher isn't available if reposetup() wasn't called.
179 lfstrack = self._revlog.opener.options.get(b'lfstrack')
180
181 if lfstrack:
182 textlen = len(text)
183 # exclude hg rename meta from file size
184 meta, offset = storageutil.parsemeta(text)
185 if offset:
186 textlen -= offset
187
188 if lfstrack(self._revlog.filename, textlen):
189 flags |= revlog.REVIDX_EXTSTORED
190
191 return orig(
192 self,
193 text,
194 transaction,
195 link,
196 p1,
197 p2,
198 cachedelta=cachedelta,
199 node=node,
200 flags=flags,
201 **kwds,
202 )
203
204
205 # Wrapping may also be applied by remotefilelog
206 def filelogrenamed(orig, self, node):
207 if _islfs(self._revlog, node):
208 rawtext = self._revlog.rawdata(node)
209 if not rawtext:
210 return False
211 metadata = pointer.deserialize(rawtext)
212 if b'x-hg-copy' in metadata and b'x-hg-copyrev' in metadata:
213 return metadata[b'x-hg-copy'], bin(metadata[b'x-hg-copyrev'])
214 else:
215 return False
216 return orig(self, node)
217
218
219 # Wrapping may also be applied by remotefilelog
220 def filelog_has_meta(orig, self, node):
221 if _islfs(self._revlog, node):
222 rawtext = self._revlog.rawdata(node)
223 if not rawtext:
224 return False
225 metadata = pointer.deserialize(rawtext)
226 for k in metadata:
227 if k.startswith(b'x-hg-'):
228 return True
229 return False
230 return orig(self, node)
231
232
233 # Wrapping may also be applied by remotefilelog
234 def filelogsize(orig, self, rev):
235 if _islfs(self._revlog, rev=rev):
236 # fast path: use lfs metadata to answer size
237 rawtext = self._revlog.rawdata(rev)
238 metadata = pointer.deserialize(rawtext)
239 return int(metadata[b'size'])
240 return orig(self, rev)
241
242
243 @eh.wrapfunction(revlog, '_verify_revision')
244 def _verify_revision(orig, rl, skipflags, state, node):
245 if _islfs(rl, node=node):
246 rawtext = rl.rawdata(node)
247 metadata = pointer.deserialize(rawtext)
248
249 # Don't skip blobs that are stored locally, as local verification is
250 # relatively cheap and there's no other way to verify the raw data in
251 # the revlog.
252 if rl.opener.lfslocalblobstore.has(metadata.oid()):
253 skipflags &= ~revlog.REVIDX_EXTSTORED
254 elif skipflags & revlog.REVIDX_EXTSTORED:
255 # The wrapped method will set `skipread`, but there's enough local
256 # info to check renames.
257 state[b'safe_renamed'].add(node)
258
259 orig(rl, skipflags, state, node)
260
261
262 @eh.wrapfunction(context.basefilectx, 'cmp')
263 def filectxcmp(orig, self, fctx):
264 """returns True if text is different than fctx"""
265 # some fctx (ex. hg-git) is not based on basefilectx and do not have islfs
266 if self.islfs() and getattr(fctx, 'islfs', lambda: False)():
267 # fast path: check LFS oid
268 p1 = pointer.deserialize(self.rawdata())
269 p2 = pointer.deserialize(fctx.rawdata())
270 return p1.oid() != p2.oid()
271 return orig(self, fctx)
272
273
274 @eh.wrapfunction(context.basefilectx, 'isbinary')
275 def filectxisbinary(orig, self):
276 if self.islfs():
277 # fast path: use lfs metadata to answer isbinary
278 metadata = pointer.deserialize(self.rawdata())
279 # if lfs metadata says nothing, assume it's binary by default
280 return bool(int(metadata.get(b'x-is-binary', 1)))
281 return orig(self)
282
283
284 def filectxislfs(self):
285 return _islfs(self.filelog()._revlog, self.filenode())
286
287
288 @eh.wrapfunction(cmdutil, '_updatecatformatter')
289 def _updatecatformatter(orig, fm, ctx, matcher, path, decode):
290 orig(fm, ctx, matcher, path, decode)
291 fm.data(rawdata=ctx[path].rawdata())
292
293
294 @eh.wrapfunction(scmutil, 'wrapconvertsink')
295 def convertsink(orig, sink):
296 sink = orig(sink)
297 if sink.repotype == b'hg':
298
299 class lfssink(sink.__class__):
300 def putcommit(
301 self,
302 files,
303 copies,
304 parents,
305 commit,
306 source,
307 revmap,
308 full,
309 cleanp2,
310 ):
311 pc = super().putcommit
312 node = pc(
313 files,
314 copies,
315 parents,
316 commit,
317 source,
318 revmap,
319 full,
320 cleanp2,
321 )
322
323 if req_mod.LFS_REQUIREMENT not in self.repo.requirements:
324 ctx = self.repo[node]
325
326 # The file list may contain removed files, so check for
327 # membership before assuming it is in the context.
328 if any(f in ctx and ctx[f].islfs() for f, n in files):
329 self.repo.requirements.add(req_mod.LFS_REQUIREMENT)
330 scmutil.writereporequirements(self.repo)
331
332 return node
333
334 sink.__class__ = lfssink
335
336 return sink
337
338
339 # bundlerepo uses "vfsmod.readonlyvfs(othervfs)", we need to make sure lfs
340 # options and blob stores are passed from othervfs to the new readonlyvfs.
341 @eh.wrapfunction(vfsmod.readonlyvfs, '__init__')
342 def vfsinit(orig, self, othervfs):
343 orig(self, othervfs)
344 # copy lfs related options
345 for k, v in othervfs.options.items():
346 if k.startswith(b'lfs'):
347 self.options[k] = v
348 # also copy lfs blobstores. note: this can run before reposetup, so lfs
349 # blobstore attributes are not always ready at this time.
350 for name in ['lfslocalblobstore', 'lfsremoteblobstore']:
351 if hasattr(othervfs, name):
352 setattr(self, name, getattr(othervfs, name))
353
354
355 def _prefetchfiles(repo, revmatches):
356 """Ensure that required LFS blobs are present, fetching them as a group if
357 needed."""
358 if not hasattr(repo.svfs, 'lfslocalblobstore'):
359 return
360
361 pointers = []
362 oids = set()
363 localstore = repo.svfs.lfslocalblobstore
364
365 for rev, match in revmatches:
366 ctx = repo[rev]
367 for f in ctx.walk(match):
368 p = pointerfromctx(ctx, f)
369 if p and p.oid() not in oids and not localstore.has(p.oid()):
370 p.filename = f
371 pointers.append(p)
372 oids.add(p.oid())
373
374 if pointers:
375 # Recalculating the repo store here allows 'paths.default' that is set
376 # on the repo by a clone command to be used for the update.
377 blobstore.remote(repo).readbatch(pointers, localstore)
378
379
380 def _canskipupload(repo):
381 # Skip if this hasn't been passed to reposetup()
382 if not hasattr(repo.svfs, 'lfsremoteblobstore'):
383 return True
384
385 # if remotestore is a null store, upload is a no-op and can be skipped
386 return isinstance(repo.svfs.lfsremoteblobstore, blobstore._nullremote)
387
388
389 def candownload(repo):
390 # Skip if this hasn't been passed to reposetup()
391 if not hasattr(repo.svfs, 'lfsremoteblobstore'):
392 return False
393
394 # if remotestore is a null store, downloads will lead to nothing
395 return not isinstance(repo.svfs.lfsremoteblobstore, blobstore._nullremote)
396
397
398 def uploadblobsfromrevs(repo, revs):
399 """upload lfs blobs introduced by revs"""
400 if _canskipupload(repo):
401 return
402 pointers = extractpointers(repo, revs)
403 uploadblobs(repo, pointers)
404
405
406 def prepush(pushop):
407 """Prepush hook.
408
409 Read through the revisions to push, looking for filelog entries that can be
410 deserialized into metadata so that we can block the push on their upload to
411 the remote blobstore.
412 """
413 return uploadblobsfromrevs(pushop.repo, pushop.outgoing.missing)
414
415
416 @eh.wrapfunction(exchange, 'push')
417 def push(orig, repo, remote, *args, **kwargs):
418 """bail on push if the extension isn't enabled on remote when needed, and
419 update the remote store based on the destination path."""
420 if req_mod.LFS_REQUIREMENT in repo.requirements:
421 # If the remote peer is for a local repo, the requirement tests in the
422 # base class method enforce lfs support. Otherwise, some revisions in
423 # this repo use lfs, and the remote repo needs the extension loaded.
424 if not remote.local() and not remote.capable(b'lfs'):
425 # This is a copy of the message in exchange.push() when requirements
426 # are missing between local repos.
427 m = _(b"required features are not supported in the destination: %s")
428 raise error.Abort(
429 m % b'lfs', hint=_(b'enable the lfs extension on the server')
430 )
431
432 # Repositories where this extension is disabled won't have the field.
433 # But if there's a requirement, then the extension must be loaded AND
434 # there may be blobs to push.
435 remotestore = repo.svfs.lfsremoteblobstore
436 try:
437 repo.svfs.lfsremoteblobstore = blobstore.remote(repo, remote.url())
438 return orig(repo, remote, *args, **kwargs)
439 finally:
440 repo.svfs.lfsremoteblobstore = remotestore
441 else:
442 return orig(repo, remote, *args, **kwargs)
443
444
445 # when writing a bundle via "hg bundle" command, upload related LFS blobs
446 @eh.wrapfunction(bundle2, 'writenewbundle')
447 def writenewbundle(
448 orig, ui, repo, source, filename, bundletype, outgoing, *args, **kwargs
449 ):
450 """upload LFS blobs added by outgoing revisions on 'hg bundle'"""
451 uploadblobsfromrevs(repo, outgoing.missing)
452 return orig(
453 ui, repo, source, filename, bundletype, outgoing, *args, **kwargs
454 )
455
456
457 def extractpointers(repo, revs):
458 """return a list of lfs pointers added by given revs"""
459 repo.ui.debug(b'lfs: computing set of blobs to upload\n')
460 pointers = {}
461
462 makeprogress = repo.ui.makeprogress
463 with makeprogress(
464 _(b'lfs search'), _(b'changesets'), len(revs)
465 ) as progress:
466 for r in revs:
467 ctx = repo[r]
468 for p in pointersfromctx(ctx).values():
469 pointers[p.oid()] = p
470 progress.increment()
471 return sorted(pointers.values(), key=lambda p: p.oid())
472
473
474 def pointerfromctx(ctx, f, removed=False):
475 """return a pointer for the named file from the given changectx, or None if
476 the file isn't LFS.
477
478 Optionally, the pointer for a file deleted from the context can be returned.
479 Since no such pointer is actually stored, and to distinguish from a non LFS
480 file, this pointer is represented by an empty dict.
481 """
482 _ctx = ctx
483 if f not in ctx:
484 if not removed:
485 return None
486 if f in ctx.p1():
487 _ctx = ctx.p1()
488 elif f in ctx.p2():
489 _ctx = ctx.p2()
490 else:
491 return None
492 fctx = _ctx[f]
493 if not _islfs(fctx.filelog()._revlog, fctx.filenode()):
494 return None
495 try:
496 p = pointer.deserialize(fctx.rawdata())
497 if ctx == _ctx:
498 return p
499 return {}
500 except pointer.InvalidPointer as ex:
501 raise error.Abort(
502 _(b'lfs: corrupted pointer (%s@%s): %s\n')
503 % (f, short(_ctx.node()), ex)
504 )
505
506
507 def pointersfromctx(ctx, removed=False):
508 """return a dict {path: pointer} for given single changectx.
509
510 If ``removed`` == True and the LFS file was removed from ``ctx``, the value
511 stored for the path is an empty dict.
512 """
513 result = {}
514 m = ctx.repo().narrowmatch()
515
516 # TODO: consider manifest.fastread() instead
517 for f in ctx.files():
518 if not m(f):
519 continue
520 p = pointerfromctx(ctx, f, removed=removed)
521 if p is not None:
522 result[f] = p
523 return result
524
525
526 def uploadblobs(repo, pointers):
527 """upload given pointers from local blobstore"""
528 if not pointers:
529 return
530
531 remoteblob = repo.svfs.lfsremoteblobstore
532 remoteblob.writebatch(pointers, repo.svfs.lfslocalblobstore)
533
534
535 @eh.wrapfunction(upgrade_engine, 'finishdatamigration')
536 def upgradefinishdatamigration(
537 orig: Callable[[UiT, RepoT, RepoT, RequirementSetT], None],
538 ui: UiT,
539 srcrepo: RepoT,
540 dstrepo: RepoT,
541 requirements: RequirementSetT,
542 ) -> None:
543 orig(ui, srcrepo, dstrepo, requirements)
544
545 # Skip if this hasn't been passed to reposetup()
546 if hasattr(srcrepo.svfs, 'lfslocalblobstore') and hasattr(
547 dstrepo.svfs, 'lfslocalblobstore'
548 ):
549 srclfsvfs = srcrepo.svfs.lfslocalblobstore.vfs
550 dstlfsvfs = dstrepo.svfs.lfslocalblobstore.vfs
551
552 for dirpath, dirs, files in srclfsvfs.walk():
553 for oid in files:
554 ui.write(_(b'copying lfs blob %s\n') % oid)
555 lfutil.link(srclfsvfs.join(oid), dstlfsvfs.join(oid))
556
557
558 @eh.wrapfunction(upgrade_actions, 'preservedrequirements')
559 @eh.wrapfunction(upgrade_actions, 'supporteddestrequirements')
560 def upgraderequirements(orig, repo):
561 reqs = orig(repo)
562 if req_mod.LFS_REQUIREMENT in repo.requirements:
563 reqs.add(req_mod.LFS_REQUIREMENT)
564 return reqs