Debian Codegraph @

hgext/largefiles/reposetup.py

raw
1 # Copyright 2009-2010 Gregory P. Ward
2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
3 # Copyright 2010-2011 Fog Creek Software
4 # Copyright 2010-2011 Unity Technologies
5 #
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
8
9 '''setup for largefiles repositories: reposetup'''
10
11 from __future__ import annotations
12
13 import copy
14 import typing
15
16 from mercurial.i18n import _
17
18 from mercurial import (
19 error,
20 extensions,
21 localrepo,
22 match as matchmod,
23 scmutil,
24 util,
25 )
26
27 from mercurial.dirstateutils import timestamp
28
29 from . import (
30 lfcommands,
31 lfutil,
32 )
33
34 if typing.TYPE_CHECKING:
35 from mercurial.interfaces.types import (
36 FileStorageT,
37 HgPathT,
38 MatcherT,
39 StatusT,
40 )
41
42
43 def reposetup(ui, repo):
44 # wire repositories should be given new wireproto functions
45 # by "proto.wirereposetup()" via "hg.wirepeersetupfuncs"
46 if not repo.local():
47 return
48
49 class lfilesrepo(repo.__class__):
50 # the mark to examine whether "repo" object enables largefiles or not
51 _largefilesenabled = True
52
53 lfstatus = False
54
55 def file(self, path: HgPathT, writable: bool = False) -> FileStorageT:
56 fl = super().file(path, writable)
57 fl._revlog._large_file_enabled = True
58 return fl
59
60 @property
61 def manifestlog(self):
62 ml = super().manifestlog
63 ml._rootstore._revlog._large_file_enabled = True
64 return ml
65
66 # When lfstatus is set, return a context that gives the names
67 # of largefiles instead of their corresponding standins and
68 # identifies the largefiles as always binary, regardless of
69 # their actual contents.
70 def __getitem__(self, changeid):
71 ctx = super().__getitem__(changeid)
72 if self.lfstatus:
73
74 def files(orig):
75 filenames = orig()
76 return [lfutil.splitstandin(f) or f for f in filenames]
77
78 extensions.wrapfunction(ctx, 'files', files)
79
80 def manifest(orig):
81 man1 = orig()
82
83 class lfilesmanifest(man1.__class__):
84 def __contains__(self, filename):
85 orig = super().__contains__
86 return orig(filename) or orig(
87 lfutil.standin(filename)
88 )
89
90 man1.__class__ = lfilesmanifest
91 return man1
92
93 extensions.wrapfunction(ctx, 'manifest', manifest)
94
95 def filectx(orig, path, fileid=None, filelog=None):
96 try:
97 if filelog is not None:
98 result = orig(path, fileid, filelog)
99 else:
100 result = orig(path, fileid)
101 except error.LookupError:
102 # Adding a null character will cause Mercurial to
103 # identify this as a binary file.
104 if filelog is not None:
105 result = orig(lfutil.standin(path), fileid, filelog)
106 else:
107 result = orig(lfutil.standin(path), fileid)
108 olddata = result.data
109 result.data = lambda: olddata() + b'\0'
110 return result
111
112 extensions.wrapfunction(ctx, 'filectx', filectx)
113
114 return ctx
115
116 # Figure out the status of big files and insert them into the
117 # appropriate list in the result. Also removes standin files
118 # from the listing. Revert to the original status if
119 # self.lfstatus is False.
120 # XXX large file status is buggy when used on repo proxy.
121 # XXX this needs to be investigated.
122 @localrepo.unfilteredmethod
123 def status(
124 self,
125 node1=b'.',
126 node2=None,
127 match: MatcherT | None = None,
128 ignored: bool = False,
129 clean: bool = False,
130 unknown: bool = False,
131 listsubrepos: bool = False,
132 empty_dirs_keep_files: bool = False,
133 ) -> StatusT:
134 listignored, listclean, listunknown = ignored, clean, unknown
135 orig = super().status
136 if not self.lfstatus:
137 return orig(
138 node1,
139 node2,
140 match,
141 listignored,
142 listclean,
143 listunknown,
144 listsubrepos,
145 empty_dirs_keep_files,
146 )
147
148 # some calls in this function rely on the old version of status
149 self.lfstatus = False
150 ctx1 = self[node1]
151 ctx2 = self[node2]
152 working = ctx2.rev() is None
153 parentworking = working and ctx1 == self[b'.']
154
155 if match is None:
156 match = matchmod.always()
157
158 try:
159 # updating the dirstate is optional
160 # so we don't wait on the lock
161 wlock = self.wlock(False)
162 gotlock = True
163 except error.LockError:
164 wlock = util.nullcontextmanager()
165 gotlock = False
166 with wlock, self.dirstate.running_status(self):
167 # First check if paths or patterns were specified on the
168 # command line. If there were, and they don't match any
169 # largefiles, we should just bail here and let super
170 # handle it -- thus gaining a big performance boost.
171 lfdirstate = lfutil.openlfdirstate(ui, self)
172 if not match.always():
173 for f in lfdirstate:
174 if match(f):
175 break
176 else:
177 return orig(
178 node1,
179 node2,
180 match,
181 listignored,
182 listclean,
183 listunknown,
184 listsubrepos,
185 )
186
187 # Create a copy of match that matches standins instead
188 # of largefiles.
189 def tostandins(files):
190 if not working:
191 return files
192 newfiles = []
193 dirstate = self.dirstate
194 for f in files:
195 sf = lfutil.standin(f)
196 if sf in dirstate:
197 newfiles.append(sf)
198 elif dirstate.hasdir(sf):
199 # Directory entries could be regular or
200 # standin, check both
201 newfiles.extend((f, sf))
202 else:
203 newfiles.append(f)
204 return newfiles
205
206 m = copy.copy(match)
207 m._was_tampered_with = True
208 m._files = tostandins(m._files)
209
210 result = orig(
211 node1, node2, m, ignored, clean, unknown, listsubrepos
212 )
213 if working:
214
215 def sfindirstate(f):
216 sf = lfutil.standin(f)
217 dirstate = self.dirstate
218 return sf in dirstate or dirstate.hasdir(sf)
219
220 match._was_tampered_with = True
221 match._files = [f for f in match._files if sfindirstate(f)]
222 # Don't waste time getting the ignored and unknown
223 # files from lfdirstate
224 unsure, s, mtime_boundary = lfdirstate.status(
225 match,
226 subrepos=[],
227 ignored=False,
228 clean=listclean,
229 unknown=False,
230 )
231 (modified, added, removed, deleted, clean) = (
232 s.modified,
233 s.added,
234 s.removed,
235 s.deleted,
236 s.clean,
237 )
238 if parentworking:
239 wctx = repo[None]
240 for lfile in unsure:
241 standin = lfutil.standin(lfile)
242 if standin not in ctx1:
243 # from second parent
244 modified.append(lfile)
245 elif lfutil.readasstandin(
246 ctx1[standin]
247 ) != lfutil.hashfile(self.wjoin(lfile)):
248 modified.append(lfile)
249 else:
250 if listclean:
251 clean.append(lfile)
252 s = wctx[lfile].lstat()
253 mode = s.st_mode
254 size = s.st_size
255 mtime = timestamp.reliable_mtime_of(
256 s, mtime_boundary
257 )
258 if mtime is not None:
259 cache_data = (mode, size, mtime)
260 lfdirstate.set_clean(lfile, cache_data)
261 else:
262 tocheck = unsure + modified + added + clean
263 modified, added, clean = [], [], []
264 checkexec = self.dirstate._checkexec
265
266 for lfile in tocheck:
267 standin = lfutil.standin(lfile)
268 if standin in ctx1:
269 abslfile = self.wjoin(lfile)
270 if (
271 lfutil.readasstandin(ctx1[standin])
272 != lfutil.hashfile(abslfile)
273 ) or (
274 checkexec
275 and (b'x' in ctx1.flags(standin))
276 != bool(lfutil.getexecutable(abslfile))
277 ):
278 modified.append(lfile)
279 elif listclean:
280 clean.append(lfile)
281 else:
282 added.append(lfile)
283
284 # at this point, 'removed' contains largefiles
285 # marked as 'R' in the working context.
286 # then, largefiles not managed also in the target
287 # context should be excluded from 'removed'.
288 removed = [
289 lfile
290 for lfile in removed
291 if lfutil.standin(lfile) in ctx1
292 ]
293
294 # Standins no longer found in lfdirstate have been deleted
295 for standin in ctx1.walk(lfutil.getstandinmatcher(self)):
296 lfile = lfutil.splitstandin(standin)
297 if not match(lfile):
298 continue
299 if lfile not in lfdirstate:
300 deleted.append(lfile)
301 # Sync "largefile has been removed" back to the
302 # standin. Removing a file as a side effect of
303 # running status is gross, but the alternatives (if
304 # any) are worse.
305 self.wvfs.unlinkpath(standin, ignoremissing=True)
306
307 # Filter result lists
308 result = list(result)
309
310 # Largefiles are not really removed when they're
311 # still in the normal dirstate. Likewise, normal
312 # files are not really removed if they are still in
313 # lfdirstate. This happens in merges where files
314 # change type.
315 removed = [f for f in removed if f not in self.dirstate]
316 result[2] = [f for f in result[2] if f not in lfdirstate]
317
318 lfiles = set(lfdirstate)
319 # Unknown files
320 result[4] = set(result[4]).difference(lfiles)
321 # Ignored files
322 result[5] = set(result[5]).difference(lfiles)
323 # combine normal files and largefiles
324 normals = [
325 [fn for fn in filelist if not lfutil.isstandin(fn)]
326 for filelist in result
327 ]
328 lfstatus = (
329 modified,
330 added,
331 removed,
332 deleted,
333 [],
334 [],
335 clean,
336 )
337 result = [
338 sorted(list1 + list2)
339 for (list1, list2) in zip(normals, lfstatus)
340 ]
341 else: # not against working directory
342 result = [
343 [lfutil.splitstandin(f) or f for f in items]
344 for items in result
345 ]
346
347 if gotlock:
348 lfdirstate.write(self.currenttransaction())
349 else:
350 lfdirstate.invalidate()
351
352 self.lfstatus = True
353 return scmutil.status(*result)
354
355 def commitctx(self, ctx, *args, **kwargs):
356 node = super().commitctx(ctx, *args, **kwargs)
357
358 class lfilesctx(ctx.__class__):
359 def markcommitted(self, node):
360 orig = super().markcommitted
361 return lfutil.markcommitted(orig, self, node)
362
363 ctx.__class__ = lfilesctx
364 return node
365
366 # Before commit, largefile standins have not had their
367 # contents updated to reflect the hash of their largefile.
368 # Do that here.
369 def commit(
370 self,
371 text=b"",
372 user=None,
373 date=None,
374 match=None,
375 force=False,
376 editor=False,
377 extra=None,
378 ):
379 if extra is None:
380 extra = {}
381 orig = super().commit
382
383 with self.wlock():
384 lfcommithook = self._lfcommithooks[-1]
385 match = lfcommithook(self, match)
386 result = orig(
387 text=text,
388 user=user,
389 date=date,
390 match=match,
391 force=force,
392 editor=editor,
393 extra=extra,
394 )
395 return result
396
397 # TODO: _subdirlfs should be moved into "lfutil.py", because
398 # it is referred only from "lfutil.updatestandinsbymatch"
399 def _subdirlfs(self, files, lfiles):
400 """
401 Adjust matched file list
402 If we pass a directory to commit whose only committable files
403 are largefiles, the core commit code aborts before finding
404 the largefiles.
405 So we do the following:
406 For directories that only have largefiles as matches,
407 we explicitly add the largefiles to the match list and remove
408 the directory.
409 In other cases, we leave the match list unmodified.
410 """
411 actualfiles = []
412 dirs = []
413 regulars = []
414
415 for f in files:
416 if lfutil.isstandin(f + b'/'):
417 raise error.Abort(
418 _(b'file "%s" is a largefile standin') % f,
419 hint=b'commit the largefile itself instead',
420 )
421 # Scan directories
422 if self.wvfs.isdir(f):
423 dirs.append(f)
424 else:
425 regulars.append(f)
426
427 for f in dirs:
428 matcheddir = False
429 d = self.dirstate.normalize(f) + b'/'
430 # Check for matched normal files
431 for mf in regulars:
432 if self.dirstate.normalize(mf).startswith(d):
433 actualfiles.append(f)
434 matcheddir = True
435 break
436 if not matcheddir:
437 # If no normal match, manually append
438 # any matching largefiles
439 for lf in lfiles:
440 if self.dirstate.normalize(lf).startswith(d):
441 actualfiles.append(lf)
442 if not matcheddir:
443 # There may still be normal files in the dir, so
444 # add a directory to the list, which
445 # forces status/dirstate to walk all files and
446 # call the match function on the matcher, even
447 # on case sensitive filesystems.
448 actualfiles.append(b'.')
449 matcheddir = True
450 # Nothing in dir, so readd it
451 # and let commit reject it
452 if not matcheddir:
453 actualfiles.append(f)
454
455 # Always add normal files
456 actualfiles += regulars
457 return actualfiles
458
459 repo.__class__ = lfilesrepo
460
461 # stack of hooks being executed before committing.
462 # only last element ("_lfcommithooks[-1]") is used for each committing.
463 repo._lfcommithooks = [lfutil.updatestandinsbymatch]
464
465 # Stack of status writer functions taking "*msg, **opts" arguments
466 # like "ui.status()". Only last element ("_lfstatuswriters[-1]")
467 # is used to write status out.
468 repo._lfstatuswriters = [ui.status]
469
470 def prepushoutgoinghook(pushop):
471 """Push largefiles for pushop before pushing revisions."""
472 lfrevs = pushop.lfrevs
473 if lfrevs is None:
474 lfrevs = pushop.outgoing.missing
475 if lfrevs:
476 toupload = set()
477 addfunc = lambda fn, lfhash: toupload.add(lfhash)
478 lfutil.getlfilestoupload(pushop.repo, lfrevs, addfunc)
479 lfcommands.uploadlfiles(ui, pushop.repo, pushop.remote, toupload)
480
481 repo.prepushoutgoinghooks.add(b"largefiles", prepushoutgoinghook)
482
483 def checkrequireslfiles(ui, repo, **kwargs):
484 with repo.lock():
485 if b'largefiles' in repo.requirements:
486 return
487 marker = lfutil.shortnameslash
488 for entry in repo.store.data_entries():
489 # XXX note that this match is not rooted and can wrongly match
490 # directory ending with ".hglf"
491 if entry.is_revlog and marker in entry.target_id:
492 repo.requirements.add(b'largefiles')
493 scmutil.writereporequirements(repo)
494 break
495
496 ui.setconfig(
497 b'hooks', b'changegroup.lfiles', checkrequireslfiles, b'largefiles'
498 )
499 ui.setconfig(b'hooks', b'commit.lfiles', checkrequireslfiles, b'largefiles')