Debian Codegraph @

hgext/largefiles/overrides.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 '''Overridden Mercurial commands and functions for the largefiles extension'''
10
11 from __future__ import annotations
12
13 import contextlib
14 import copy
15 import os
16 import typing
17
18 from mercurial.i18n import _
19
20 from mercurial.interfaces.types import MatcherT
21
22 from mercurial.hgweb import webcommands
23
24 from mercurial import (
25 archival,
26 cmdutil,
27 copies as copiesmod,
28 dirstate,
29 error,
30 exchange,
31 extensions,
32 exthelper,
33 filemerge,
34 logcmdutil,
35 match as matchmod,
36 merge,
37 merge_utils,
38 mergestate as mergestatemod,
39 pathutil,
40 pycompat,
41 scmutil,
42 smartset,
43 subrepo,
44 url as urlmod,
45 util,
46 )
47
48 from mercurial.cmd_impls import (
49 clone as clone_impl,
50 )
51 from mercurial.upgrade_utils import (
52 actions as upgrade_actions,
53 )
54
55 from mercurial.utils import urlutil
56
57 from . import (
58 lfcommands,
59 lfutil,
60 storefactory,
61 )
62
63 if typing.TYPE_CHECKING:
64 from mercurial.interfaces.types import (
65 RepoT,
66 UiT,
67 )
68
69 ACTION_ADD = merge_utils.ACTION_ADD
70 ACTION_DELETED_CHANGED = merge_utils.ACTION_DELETED_CHANGED
71 ACTION_GET = merge_utils.ACTION_GET
72 ACTION_KEEP = merge_utils.ACTION_KEEP
73 ACTION_REMOVE = merge_utils.ACTION_REMOVE
74
75 eh = exthelper.exthelper()
76
77 lfstatus = lfutil.lfstatus
78
79 MERGE_ACTION_LARGEFILE_MARK_REMOVED = merge_utils.MergeAction(b'lfmr')
80
81 # -- Utility functions: commonly/repeatedly needed functionality ---------------
82
83
84 def composelargefilematcher(match, manifest):
85 """create a matcher that matches only the largefiles in the original
86 matcher"""
87 m = copy.copy(match)
88 m._was_tampered_with = True
89 lfile = lambda f: lfutil.standin(f) in manifest
90 m._files = [lf for lf in m._files if lfile(lf)]
91 m._fileset = set(m._files)
92 m.always = lambda: False
93 origmatchfn = m.matchfn
94 m.matchfn = lambda f: lfile(f) and origmatchfn(f)
95 return m
96
97
98 def composenormalfilematcher(match, manifest, exclude=None):
99 excluded = set()
100 if exclude is not None:
101 excluded.update(exclude)
102
103 m = copy.copy(match)
104 m._was_tampered_with = True
105 notlfile = lambda f: not (
106 lfutil.isstandin(f) or lfutil.standin(f) in manifest or f in excluded
107 )
108 m._files = [lf for lf in m._files if notlfile(lf)]
109 m._fileset = set(m._files)
110 m.always = lambda: False
111 origmatchfn = m.matchfn
112 m.matchfn = lambda f: notlfile(f) and origmatchfn(f)
113 return m
114
115
116 def addlargefiles(ui, repo, isaddremove, matcher, uipathfn, **opts):
117 large = opts.get('large')
118 lfsize = lfutil.getminsize(
119 ui, lfutil.islfilesrepo(repo), opts.get('lfsize')
120 )
121
122 lfmatcher = None
123 if lfutil.islfilesrepo(repo):
124 lfpats = ui.configlist(lfutil.longname, b'patterns')
125 if lfpats:
126 lfmatcher = matchmod.match(repo.root, b'', list(lfpats))
127
128 lfnames = []
129 m = matcher
130
131 wctx = repo[None]
132 for f in wctx.walk(matchmod.badmatch(m, lambda x, y: None)):
133 exact = m.exact(f)
134 lfile = lfutil.standin(f) in wctx
135 nfile = f in wctx
136 exists = lfile or nfile
137
138 # Don't warn the user when they attempt to add a normal tracked file.
139 # The normal add code will do that for us.
140 if exact and exists:
141 if lfile:
142 ui.warn(_(b'%s already a largefile\n') % uipathfn(f))
143 continue
144
145 if (exact or not exists) and not lfutil.isstandin(f):
146 # In case the file was removed previously, but not committed
147 # (issue3507)
148 if not repo.wvfs.exists(f):
149 continue
150
151 abovemin = (
152 lfsize and repo.wvfs.lstat(f).st_size >= lfsize * 1024 * 1024
153 )
154 if large or abovemin or (lfmatcher and lfmatcher(f)):
155 lfnames.append(f)
156 if ui.verbose or not exact:
157 ui.status(_(b'adding %s as a largefile\n') % uipathfn(f))
158
159 bad = []
160
161 # Need to lock, otherwise there could be a race condition between
162 # when standins are created and added to the repo.
163 with repo.wlock():
164 if not opts.get('dry_run'):
165 standins = []
166 lfdirstate = lfutil.openlfdirstate(ui, repo)
167 for f in lfnames:
168 standinname = lfutil.standin(f)
169 lfutil.writestandin(
170 repo,
171 standinname,
172 hash=b'',
173 executable=lfutil.getexecutable(repo.wjoin(f)),
174 )
175 standins.append(standinname)
176 lfdirstate.set_tracked(f)
177 lfdirstate.write(repo.currenttransaction())
178 bad += [
179 lfutil.splitstandin(f)
180 for f in repo[None].add(standins)
181 if f in m.files()
182 ]
183
184 added = [f for f in lfnames if f not in bad]
185 return added, bad
186
187
188 def removelargefiles(ui, repo, isaddremove, matcher, uipathfn, dryrun, **opts):
189 after = opts.get('after')
190 m = composelargefilematcher(matcher, repo[None].manifest())
191 with lfstatus(repo):
192 s = repo.status(match=m, clean=not isaddremove)
193 manifest = repo[None].manifest()
194 modified, added, deleted, clean = (
195 [f for f in list if lfutil.standin(f) in manifest]
196 for list in (s.modified, s.added, s.deleted, s.clean)
197 )
198
199 def warn(files, msg):
200 for f in files:
201 ui.warn(msg % uipathfn(f))
202 return int(len(files) > 0)
203
204 if after:
205 remove = deleted
206 result = warn(
207 modified + added + clean, _(b'not removing %s: file still exists\n')
208 )
209 else:
210 remove = deleted + clean
211 result = warn(
212 modified,
213 _(
214 b'not removing %s: file is modified (use -f'
215 b' to force removal)\n'
216 ),
217 )
218 result = (
219 warn(
220 added,
221 _(
222 b'not removing %s: file has been marked for add'
223 b' (use forget to undo)\n'
224 ),
225 )
226 or result
227 )
228
229 # Need to lock because standin files are deleted then removed from the
230 # repository and we could race in-between.
231 with repo.wlock():
232 lfdirstate = lfutil.openlfdirstate(ui, repo)
233 for f in sorted(remove):
234 if ui.verbose or not m.exact(f):
235 ui.status(_(b'removing %s\n') % uipathfn(f))
236
237 if not dryrun:
238 if not after:
239 repo.wvfs.unlinkpath(f, ignoremissing=True)
240
241 if dryrun:
242 return result
243
244 remove = [lfutil.standin(f) for f in remove]
245 # If this is being called by addremove, let the original addremove
246 # function handle this.
247 if not isaddremove:
248 for f in remove:
249 repo.wvfs.unlinkpath(f, ignoremissing=True)
250 repo[None].forget(remove)
251
252 for f in remove:
253 lfdirstate.set_untracked(lfutil.splitstandin(f))
254
255 lfdirstate.write(repo.currenttransaction())
256
257 return result
258
259
260 # For overriding mercurial.hgweb.webcommands so that largefiles will
261 # appear at their right place in the manifests.
262 @eh.wrapfunction(webcommands, 'decodepath')
263 def decodepath(orig, path):
264 return lfutil.splitstandin(path) or path
265
266
267 # -- Wrappers: modify existing commands --------------------------------
268
269
270 @eh.wrapcommand(
271 b'add',
272 opts=[
273 (b'', b'large', None, _(b'add as largefile')),
274 (b'', b'normal', None, _(b'add as normal file')),
275 (
276 b'',
277 b'lfsize',
278 b'',
279 _(
280 b'add all files above this size (in megabytes) '
281 b'as largefiles (default: 10)'
282 ),
283 ),
284 ],
285 )
286 def overrideadd(orig, ui, repo, *pats, **opts):
287 if opts.get('normal') and opts.get('large'):
288 raise error.Abort(_(b'--normal cannot be used with --large'))
289 return orig(ui, repo, *pats, **opts)
290
291
292 @eh.wrapfunction(cmdutil, 'add')
293 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
294 # The --normal flag short circuits this override
295 if opts.get('normal'):
296 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
297
298 ladded, lbad = addlargefiles(ui, repo, False, matcher, uipathfn, **opts)
299 normalmatcher = composenormalfilematcher(
300 matcher, repo[None].manifest(), ladded
301 )
302 bad = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly, **opts)
303
304 bad.extend(f for f in lbad)
305 return bad
306
307
308 @eh.wrapfunction(cmdutil, 'remove')
309 def cmdutilremove(
310 orig, ui, repo, matcher, prefix, uipathfn, after, force, subrepos, dryrun
311 ):
312 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest())
313 result = orig(
314 ui,
315 repo,
316 normalmatcher,
317 prefix,
318 uipathfn,
319 after,
320 force,
321 subrepos,
322 dryrun,
323 )
324 return (
325 removelargefiles(
326 ui, repo, False, matcher, uipathfn, dryrun, after=after, force=force
327 )
328 or result
329 )
330
331
332 @eh.wrapfunction(dirstate.dirstate, '_changing')
333 @contextlib.contextmanager
334 def _changing(orig, self: dirstate.dirstate, repo: RepoT, change_type):
335 pre = sub_dirstate = getattr(self, '_sub_dirstate', None)
336 try:
337 lfd = getattr(self, '_large_file_dirstate', False)
338 if sub_dirstate is None and not lfd:
339 sub_dirstate = lfutil.openlfdirstate(repo.ui, repo)
340 self._sub_dirstate = sub_dirstate
341 if not lfd:
342 assert self._sub_dirstate is not None
343 with orig(self, repo, change_type):
344 if sub_dirstate is None:
345 yield
346 else:
347 with sub_dirstate._changing(repo, change_type):
348 yield
349 finally:
350 self._sub_dirstate = pre
351
352
353 @eh.wrapfunction(dirstate.dirstate, 'running_status')
354 @contextlib.contextmanager
355 def running_status(orig, self: dirstate.dirstate, repo: RepoT):
356 pre = sub_dirstate = getattr(self, '_sub_dirstate', None)
357 try:
358 lfd = getattr(self, '_large_file_dirstate', False)
359 if sub_dirstate is None and not lfd:
360 sub_dirstate = lfutil.openlfdirstate(repo.ui, repo)
361 self._sub_dirstate = sub_dirstate
362 if not lfd:
363 assert self._sub_dirstate is not None
364 with orig(self, repo):
365 if sub_dirstate is None:
366 yield
367 else:
368 with sub_dirstate.running_status(repo):
369 yield
370 finally:
371 self._sub_dirstate = pre
372
373
374 @eh.wrapfunction(subrepo.hgsubrepo, 'status')
375 def overridestatusfn(orig, repo, rev2, **opts):
376 with lfstatus(repo._repo):
377 return orig(repo, rev2, **opts)
378
379
380 @eh.wrapcommand(b'status')
381 def overridestatus(orig, ui, repo, *pats, **opts):
382 with lfstatus(repo):
383 return orig(ui, repo, *pats, **opts)
384
385
386 @eh.wrapfunction(subrepo.hgsubrepo, 'dirty')
387 def overridedirty(orig, repo, ignoreupdate=False, missing=False):
388 with lfstatus(repo._repo):
389 return orig(repo, ignoreupdate=ignoreupdate, missing=missing)
390
391
392 @eh.wrapcommand(b'log')
393 def overridelog(orig, ui, repo, *pats, **opts):
394 def overridematchandpats(
395 orig,
396 ctx,
397 pats=(),
398 opts=None,
399 globbed=False,
400 default=b'relpath',
401 badfn=None,
402 ):
403 """Matcher that merges root directory with .hglf, suitable for log.
404 It is still possible to match .hglf directly.
405 For any listed files run log on the standin too.
406 matchfn tries both the given filename and with .hglf stripped.
407 """
408 if opts is None:
409 opts = {}
410 matchandpats = orig(ctx, pats, opts, globbed, default, badfn=badfn)
411 m, p = copy.copy(matchandpats)
412
413 if m.always():
414 # We want to match everything anyway, so there's no benefit trying
415 # to add standins.
416 return matchandpats
417
418 pats = set(p)
419
420 def fixpats(pat, tostandin=lfutil.standin):
421 if pat.startswith(b'set:'):
422 return pat
423
424 kindpat = matchmod._patsplit(pat, None)
425
426 if kindpat[0] is not None:
427 return kindpat[0] + b':' + tostandin(kindpat[1])
428 return tostandin(kindpat[1])
429
430 cwd = repo.getcwd()
431 if cwd:
432 hglf = lfutil.shortname
433 back = util.pconvert(repo.pathto(hglf)[: -len(hglf)])
434
435 def tostandin(f):
436 # The file may already be a standin, so truncate the back
437 # prefix and test before mangling it. This avoids turning
438 # 'glob:../.hglf/foo*' into 'glob:../.hglf/../.hglf/foo*'.
439 if f.startswith(back) and lfutil.splitstandin(f[len(back) :]):
440 return f
441
442 # An absolute path is from outside the repo, so truncate the
443 # path to the root before building the standin. Otherwise cwd
444 # is somewhere in the repo, relative to root, and needs to be
445 # prepended before building the standin.
446 if os.path.isabs(cwd):
447 f = f[len(back) :]
448 else:
449 f = cwd + b'/' + f
450 return back + lfutil.standin(f)
451
452 else:
453
454 def tostandin(f):
455 if lfutil.isstandin(f):
456 return f
457 return lfutil.standin(f)
458
459 pats.update(fixpats(f, tostandin) for f in p)
460
461 m._was_tampered_with = True
462
463 for i in range(0, len(m._files)):
464 # Don't add '.hglf' to m.files, since that is already covered by '.'
465 if m._files[i] == b'.':
466 continue
467 standin = lfutil.standin(m._files[i])
468 # If the "standin" is a directory, append instead of replace to
469 # support naming a directory on the command line with only
470 # largefiles. The original directory is kept to support normal
471 # files.
472 if standin in ctx:
473 m._files[i] = standin
474 elif m._files[i] not in ctx and repo.wvfs.isdir(standin):
475 m._files.append(standin)
476
477 m._fileset = set(m._files)
478 m.always = lambda: False
479 origmatchfn = m.matchfn
480
481 def lfmatchfn(f):
482 lf = lfutil.splitstandin(f)
483 if lf is not None and origmatchfn(lf):
484 return True
485 r = origmatchfn(f)
486 return r
487
488 m.matchfn = lfmatchfn
489
490 ui.debug(b'updated patterns: %s\n' % b', '.join(sorted(pats)))
491 return m, pats
492
493 # For hg log --patch, the match object is used in two different senses:
494 # (1) to determine what revisions should be printed out, and
495 # (2) to determine what files to print out diffs for.
496 # The magic matchandpats override should be used for case (1) but not for
497 # case (2).
498 oldmatchandpats = scmutil.matchandpats
499
500 def overridemakefilematcher(orig, repo, pats, opts, badfn=None):
501 wctx = repo[None]
502 match, pats = oldmatchandpats(wctx, pats, opts, badfn=badfn)
503 return lambda ctx: match
504
505 wrappedmatchandpats = extensions.wrappedfunction(
506 scmutil, 'matchandpats', overridematchandpats
507 )
508 wrappedmakefilematcher = extensions.wrappedfunction(
509 logcmdutil, '_makenofollowfilematcher', overridemakefilematcher
510 )
511 with wrappedmatchandpats, wrappedmakefilematcher:
512 return orig(ui, repo, *pats, **opts)
513
514
515 @eh.wrapcommand(
516 b'verify',
517 opts=[
518 (
519 b'',
520 b'large',
521 None,
522 _(b'verify that all largefiles in current revision exists'),
523 ),
524 (
525 b'',
526 b'lfa',
527 None,
528 _(b'verify largefiles in all revisions, not just current'),
529 ),
530 (
531 b'',
532 b'lfc',
533 None,
534 _(b'verify local largefile contents, not just existence'),
535 ),
536 ],
537 )
538 def overrideverify(orig, ui, repo, *pats, **opts):
539 large = opts.pop('large', False)
540 all = opts.pop('lfa', False)
541 contents = opts.pop('lfc', False)
542
543 result = orig(ui, repo, *pats, **opts)
544 if large or all or contents:
545 result = result or lfcommands.verifylfiles(ui, repo, all, contents)
546 return result
547
548
549 @eh.wrapcommand(
550 b'debugstate',
551 opts=[(b'', b'large', None, _(b'display largefiles dirstate'))],
552 )
553 def overridedebugstate(orig, ui, repo, *pats, **opts):
554 large = opts.pop('large', False)
555 if large:
556
557 class fakerepo:
558 dirstate = lfutil.openlfdirstate(ui, repo)
559
560 orig(ui, fakerepo, *pats, **opts)
561 else:
562 orig(ui, repo, *pats, **opts)
563
564
565 # Before starting the manifest merge, merge.updates will call
566 # _checkunknownfile to check if there are any files in the merged-in
567 # changeset that collide with unknown files in the working copy.
568 #
569 # The largefiles are seen as unknown, so this prevents us from merging
570 # in a file 'foo' if we already have a largefile with the same name.
571 #
572 # The overridden function filters the unknown files by removing any
573 # largefiles. This makes the merge proceed and we can then handle this
574 # case further in the overridden calculateupdates function below.
575 @eh.wrapfunction(merge, '_checkunknownfile')
576 def overridecheckunknownfile(
577 origfn, dirstate, wvfs, dircache, wctx, mctx, f, f2=None
578 ):
579 if lfutil.standin(dirstate.normalize(f)) in wctx:
580 return False
581 return origfn(dirstate, wvfs, dircache, wctx, mctx, f, f2)
582
583
584 # The manifest merge handles conflicts on the manifest level. We want
585 # to handle changes in largefile-ness of files at this level too.
586 #
587 # The strategy is to run the original calculateupdates and then process
588 # the action list it outputs. There are two cases we need to deal with:
589 #
590 # 1. Normal file in p1, largefile in p2. Here the largefile is
591 # detected via its standin file, which will enter the working copy
592 # with a "get" action. It is not "merge" since the standin is all
593 # Mercurial is concerned with at this level -- the link to the
594 # existing normal file is not relevant here.
595 #
596 # 2. Largefile in p1, normal file in p2. Here we get a "merge" action
597 # since the largefile will be present in the working copy and
598 # different from the normal file in p2. Mercurial therefore
599 # triggers a merge action.
600 #
601 # In both cases, we prompt the user and emit new actions to either
602 # remove the standin (if the normal file was kept) or to remove the
603 # normal file and get the standin (if the largefile was kept). The
604 # default prompt answer is to use the largefile version since it was
605 # presumably changed on purpose.
606 #
607 # Finally, the merge_utils.update.apply_updates function will then take care of
608 # writing the files into the working copy and lfcommands.updatelfiles will
609 # update the largefiles.
610 @eh.wrapfunction(merge, 'calculateupdates')
611 def overridecalculateupdates(
612 origfn, repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs
613 ):
614 overwrite = force and not branchmerge
615 mresult = origfn(
616 repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs
617 )
618
619 if overwrite:
620 return mresult
621
622 # Convert to dictionary with filename as key and action as value.
623 lfiles = set()
624 for f in mresult.files():
625 splitstandin = lfutil.splitstandin(f)
626 if splitstandin is not None and splitstandin in p1:
627 lfiles.add(splitstandin)
628 elif lfutil.standin(f) in p1:
629 lfiles.add(f)
630
631 for lfile in sorted(lfiles):
632 standin = lfutil.standin(lfile)
633 (lm, largs, lmsg) = mresult.getfile(lfile, (None, None, None))
634 (sm, sargs, smsg) = mresult.getfile(standin, (None, None, None))
635
636 if sm in (ACTION_GET, ACTION_DELETED_CHANGED) and lm != ACTION_REMOVE:
637 if sm == ACTION_DELETED_CHANGED:
638 f1, f2, fa, move, anc = sargs
639 sargs = (p2[f2].flags(), False)
640 # Case 1: normal file in the working copy, largefile in
641 # the second parent
642 usermsg = (
643 _(
644 b'remote turned local normal file %s into a largefile\n'
645 b'use (l)argefile or keep (n)ormal file?'
646 b'$$ &Largefile $$ &Normal file'
647 )
648 % lfile
649 )
650 if repo.ui.promptchoice(usermsg, 0) == 0: # pick remote largefile
651 mresult.addfile(
652 lfile, ACTION_REMOVE, None, b'replaced by standin'
653 )
654 mresult.addfile(standin, ACTION_GET, sargs, b'replaces standin')
655 else: # keep local normal file
656 mresult.addfile(lfile, ACTION_KEEP, None, b'replaces standin')
657 if branchmerge:
658 mresult.addfile(
659 standin,
660 ACTION_KEEP,
661 None,
662 b'replaced by non-standin',
663 )
664 else:
665 mresult.addfile(
666 standin,
667 ACTION_REMOVE,
668 None,
669 b'replaced by non-standin',
670 )
671 if lm in (ACTION_GET, ACTION_DELETED_CHANGED) and sm != ACTION_REMOVE:
672 if lm == ACTION_DELETED_CHANGED:
673 f1, f2, fa, move, anc = largs
674 largs = (p2[f2].flags(), False)
675 # Case 2: largefile in the working copy, normal file in
676 # the second parent
677 usermsg = (
678 _(
679 b'remote turned local largefile %s into a normal file\n'
680 b'keep (l)argefile or use (n)ormal file?'
681 b'$$ &Largefile $$ &Normal file'
682 )
683 % lfile
684 )
685 if repo.ui.promptchoice(usermsg, 0) == 0: # keep local largefile
686 if branchmerge:
687 # largefile can be restored from standin safely
688 mresult.addfile(
689 lfile,
690 ACTION_KEEP,
691 None,
692 b'replaced by standin',
693 )
694 mresult.addfile(
695 standin, ACTION_KEEP, None, b'replaces standin'
696 )
697 else:
698 # "lfile" should be marked as "removed" without
699 # removal of itself
700 mresult.addfile(
701 lfile,
702 MERGE_ACTION_LARGEFILE_MARK_REMOVED,
703 None,
704 b'forget non-standin largefile',
705 )
706
707 # linear-merge should treat this largefile as 're-added'
708 mresult.addfile(standin, ACTION_ADD, None, b'keep standin')
709 else: # pick remote normal file
710 mresult.addfile(lfile, ACTION_GET, largs, b'replaces standin')
711 mresult.addfile(
712 standin,
713 ACTION_REMOVE,
714 None,
715 b'replaced by non-standin',
716 )
717
718 return mresult
719
720
721 @eh.wrapfunction(mergestatemod, 'recordupdates')
722 def mergerecordupdates(orig, repo, actions, branchmerge, getfiledata):
723 if MERGE_ACTION_LARGEFILE_MARK_REMOVED in actions:
724 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
725 for lfile, args, msg in actions[MERGE_ACTION_LARGEFILE_MARK_REMOVED]:
726 # this should be executed before 'orig', to execute 'remove'
727 # before all other actions
728 repo.dirstate.update_file(lfile, p1_tracked=True, wc_tracked=False)
729 # make sure lfile doesn't get synclfdirstate'd as normal
730 lfdirstate.update_file(lfile, p1_tracked=False, wc_tracked=True)
731
732 return orig(repo, actions, branchmerge, getfiledata)
733
734
735 # Override filemerge to prompt the user about how they wish to merge
736 # largefiles. This will handle identical edits without prompting the user.
737 @eh.wrapfunction(filemerge, 'filemerge')
738 def overridefilemerge(
739 origfn, repo, wctx, mynode, orig, fcd, fco, fca, labels=None
740 ):
741 if not lfutil.isstandin(orig) or fcd.isabsent() or fco.isabsent():
742 return origfn(repo, wctx, mynode, orig, fcd, fco, fca, labels=labels)
743
744 ahash = lfutil.readasstandin(fca).lower()
745 dhash = lfutil.readasstandin(fcd).lower()
746 ohash = lfutil.readasstandin(fco).lower()
747 if (
748 ohash != ahash
749 and ohash != dhash
750 and (
751 dhash == ahash
752 or repo.ui.promptchoice(
753 _(
754 b'largefile %s has a merge conflict\nancestor was %s\n'
755 b'you can keep (l)ocal %s or take (o)ther %s.\n'
756 b'what do you want to do?'
757 b'$$ &Local $$ &Other'
758 )
759 % (lfutil.splitstandin(orig), ahash, dhash, ohash),
760 0,
761 )
762 == 1
763 )
764 ):
765 repo.wwrite(fcd.path(), fco.data(), fco.flags())
766 return 0, False
767
768
769 @eh.wrapfunction(copiesmod, 'pathcopies')
770 def copiespathcopies(orig, ctx1, ctx2, match=None):
771 copies = orig(ctx1, ctx2, match=match)
772 updated = {}
773
774 for k, v in copies.items():
775 updated[lfutil.splitstandin(k) or k] = lfutil.splitstandin(v) or v
776
777 return updated
778
779
780 # Copy first changes the matchers to match standins instead of
781 # largefiles. Then it overrides util.copyfile in that function it
782 # checks if the destination largefile already exists. It also keeps a
783 # list of copied files so that the largefiles can be copied and the
784 # dirstate updated.
785 @eh.wrapfunction(cmdutil, 'copy')
786 def overridecopy(orig, ui, repo, pats, opts, rename=False):
787 # doesn't remove largefile on rename
788 if len(pats) < 2:
789 # this isn't legal, let the original function deal with it
790 return orig(ui, repo, pats, opts, rename)
791
792 # This could copy both lfiles and normal files in one command,
793 # but we don't want to do that. First replace their matcher to
794 # only match normal files and run it, then replace it to just
795 # match largefiles and run it again.
796 nonormalfiles = False
797 nolfiles = False
798 manifest = repo[None].manifest()
799
800 def normalfilesmatchfn(
801 orig,
802 ctx,
803 pats=(),
804 opts=None,
805 globbed=False,
806 default=b'relpath',
807 badfn=None,
808 ):
809 if opts is None:
810 opts = {}
811 match = orig(ctx, pats, opts, globbed, default, badfn=badfn)
812 return composenormalfilematcher(match, manifest)
813
814 with extensions.wrappedfunction(scmutil, 'match', normalfilesmatchfn):
815 try:
816 result = orig(ui, repo, pats, opts, rename)
817 except error.Abort as e:
818 if e.message != _(b'no files to copy'):
819 raise e
820 else:
821 nonormalfiles = True
822 result = 0
823
824 # The first rename can cause our current working directory to be removed.
825 # In that case there is nothing left to copy/rename so just quit.
826 try:
827 repo.getcwd()
828 except OSError:
829 return result
830
831 def makestandin(relpath):
832 path = pathutil.canonpath(repo.root, repo.getcwd(), relpath)
833 return repo.wvfs.join(lfutil.standin(path))
834
835 fullpats = scmutil.expandpats(pats)
836 dest = fullpats[-1]
837
838 if os.path.isdir(dest):
839 if not os.path.isdir(makestandin(dest)):
840 os.makedirs(makestandin(dest))
841
842 # When we call orig below it creates the standins but we don't add
843 # them to the dir state until later so lock during that time.
844 wlock = repo.wlock()
845
846 try:
847 manifest = repo[None].manifest()
848
849 def overridematch(
850 orig,
851 ctx,
852 pats=(),
853 opts=None,
854 globbed=False,
855 default=b'relpath',
856 badfn=None,
857 ):
858 if opts is None:
859 opts = {}
860 newpats = []
861 # The patterns were previously mangled to add the standin
862 # directory; we need to remove that now
863 for pat in pats:
864 if matchmod.patkind(pat) is None and lfutil.shortname in pat:
865 newpats.append(pat.replace(lfutil.shortname, b''))
866 else:
867 newpats.append(pat)
868 match = orig(ctx, newpats, opts, globbed, default, badfn=badfn)
869 m = copy.copy(match)
870 m._was_tampered_with = True
871 lfile = lambda f: lfutil.standin(f) in manifest
872 m._files = [lfutil.standin(f) for f in m._files if lfile(f)]
873 m._fileset = set(m._files)
874 origmatchfn = m.matchfn
875
876 def matchfn(f):
877 lfile = lfutil.splitstandin(f)
878 return (
879 lfile is not None
880 and (f in manifest)
881 and origmatchfn(lfile)
882 or None
883 )
884
885 m.matchfn = matchfn
886 return m
887
888 listpats = []
889 for pat in pats:
890 if matchmod.patkind(pat) is not None:
891 listpats.append(pat)
892 else:
893 listpats.append(makestandin(pat))
894
895 copiedfiles = []
896
897 def overridecopyfile(orig, src, dest, *args, **kwargs):
898 if lfutil.shortname in src and dest.startswith(
899 repo.wjoin(lfutil.shortname)
900 ):
901 destlfile = dest.replace(lfutil.shortname, b'')
902 if not opts[b'force'] and os.path.exists(destlfile):
903 raise OSError(
904 b'', _(b'destination largefile already exists')
905 )
906 copiedfiles.append((src, dest))
907 orig(src, dest, *args, **kwargs)
908
909 with extensions.wrappedfunction(util, 'copyfile', overridecopyfile):
910 with extensions.wrappedfunction(scmutil, 'match', overridematch):
911 result += orig(ui, repo, listpats, opts, rename)
912
913 lfdirstate = lfutil.openlfdirstate(ui, repo)
914 for src, dest in copiedfiles:
915 if lfutil.shortname in src and dest.startswith(
916 repo.wjoin(lfutil.shortname)
917 ):
918 srclfile = src.replace(repo.wjoin(lfutil.standin(b'')), b'')
919 destlfile = dest.replace(repo.wjoin(lfutil.standin(b'')), b'')
920 destlfiledir = repo.wvfs.dirname(repo.wjoin(destlfile)) or b'.'
921 if not os.path.isdir(destlfiledir):
922 os.makedirs(destlfiledir)
923 if rename:
924 os.rename(repo.wjoin(srclfile), repo.wjoin(destlfile))
925
926 # The file is gone, but this deletes any empty parent
927 # directories as a side-effect.
928 repo.wvfs.unlinkpath(srclfile, ignoremissing=True)
929 lfdirstate.set_untracked(srclfile)
930 else:
931 util.copyfile(repo.wjoin(srclfile), repo.wjoin(destlfile))
932
933 lfdirstate.set_tracked(destlfile)
934 lfdirstate.write(repo.currenttransaction())
935 except error.Abort as e:
936 if e.message != _(b'no files to copy'):
937 raise e
938 else:
939 nolfiles = True
940 finally:
941 wlock.release()
942
943 if nolfiles and nonormalfiles:
944 raise error.Abort(_(b'no files to copy'))
945
946 return result
947
948
949 # When the user calls revert, we have to be careful to not revert any
950 # changes to other largefiles accidentally. This means we have to keep
951 # track of the largefiles that are being reverted so we only pull down
952 # the necessary largefiles.
953 #
954 # Standins are only updated (to match the hash of largefiles) before
955 # commits. Update the standins then run the original revert, changing
956 # the matcher to hit standins instead of largefiles. Based on the
957 # resulting standins update the largefiles.
958 @eh.wrapfunction(cmdutil, 'revert')
959 def overriderevert(orig, ui, repo, ctx, *pats, **opts):
960 # Because we put the standins in a bad state (by updating them)
961 # and then return them to a correct state we need to lock to
962 # prevent others from changing them in their incorrect state.
963 with repo.wlock(), repo.dirstate.running_status(repo):
964 lfdirstate = lfutil.openlfdirstate(ui, repo)
965 s = lfutil.lfdirstatestatus(lfdirstate, repo)
966 lfdirstate.write(repo.currenttransaction())
967 for lfile in s.modified:
968 lfutil.updatestandin(repo, lfile, lfutil.standin(lfile))
969 for lfile in s.deleted:
970 fstandin = lfutil.standin(lfile)
971 if repo.wvfs.exists(fstandin):
972 repo.wvfs.unlink(fstandin)
973
974 oldstandins = lfutil.getstandinsstate(repo)
975
976 def overridematch(
977 orig,
978 mctx,
979 pats=(),
980 opts=None,
981 globbed=False,
982 default=b'relpath',
983 badfn=None,
984 ):
985 if opts is None:
986 opts = {}
987 match = orig(mctx, pats, opts, globbed, default, badfn=badfn)
988 m = copy.copy(match)
989 m._was_tampered_with = True
990
991 # revert supports recursing into subrepos, and though largefiles
992 # currently doesn't work correctly in that case, this match is
993 # called, so the lfdirstate above may not be the correct one for
994 # this invocation of match.
995 lfdirstate = lfutil.openlfdirstate(
996 mctx.repo().ui, mctx.repo(), False
997 )
998
999 wctx = repo[None]
1000 matchfiles = []
1001 for f in m._files:
1002 standin = lfutil.standin(f)
1003 if standin in ctx or standin in mctx:
1004 matchfiles.append(standin)
1005 elif standin in wctx or lfdirstate.get_entry(f).removed:
1006 continue
1007 else:
1008 matchfiles.append(f)
1009 m._files = matchfiles
1010 m._fileset = set(m._files)
1011 origmatchfn = m.matchfn
1012
1013 def matchfn(f):
1014 lfile = lfutil.splitstandin(f)
1015 if lfile is not None:
1016 return origmatchfn(lfile) and (f in ctx or f in mctx)
1017 return origmatchfn(f)
1018
1019 m.matchfn = matchfn
1020 return m
1021
1022 with extensions.wrappedfunction(scmutil, 'match', overridematch):
1023 orig(ui, repo, ctx, *pats, **opts)
1024
1025 newstandins = lfutil.getstandinsstate(repo)
1026 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1027 # lfdirstate should be 'normallookup'-ed for updated files,
1028 # because reverting doesn't touch dirstate for 'normal' files
1029 # when target revision is explicitly specified: in such case,
1030 # 'n' and valid timestamp in dirstate doesn't ensure 'clean'
1031 # of target (standin) file.
1032 lfcommands.updatelfiles(
1033 ui, repo, filelist, printmessage=False, normallookup=True
1034 )
1035
1036
1037 # after pulling changesets, we need to take some extra care to get
1038 # largefiles updated remotely
1039 @eh.wrapcommand(
1040 b'pull',
1041 opts=[
1042 (
1043 b'',
1044 b'all-largefiles',
1045 None,
1046 _(b'download all pulled versions of largefiles (DEPRECATED)'),
1047 ),
1048 (
1049 b'',
1050 b'lfrev',
1051 [],
1052 _(b'download largefiles for these revisions'),
1053 _(b'REV'),
1054 ),
1055 ],
1056 )
1057 def overridepull(orig, ui, repo, source=None, **opts):
1058 revsprepull = len(repo)
1059 if not source:
1060 source = b'default'
1061 repo.lfpullsource = source
1062 result = orig(ui, repo, source, **opts)
1063 revspostpull = len(repo)
1064 lfrevs = opts.get('lfrev', [])
1065 if opts.get('all_largefiles'):
1066 lfrevs.append(b'pulled()')
1067 if lfrevs and revspostpull > revsprepull:
1068 numcached = 0
1069 repo.firstpulled = revsprepull # for pulled() revset expression
1070 try:
1071 for rev in logcmdutil.revrange(repo, lfrevs):
1072 ui.note(_(b'pulling largefiles for revision %d\n') % rev)
1073 (cached, missing) = lfcommands.cachelfiles(ui, repo, rev)
1074 numcached += len(cached)
1075 finally:
1076 del repo.firstpulled
1077 ui.status(_(b"%d largefiles cached\n") % numcached)
1078 return result
1079
1080
1081 @eh.wrapcommand(
1082 b'push',
1083 opts=[
1084 (
1085 b'',
1086 b'lfrev',
1087 [],
1088 _(b'upload largefiles for these revisions'),
1089 _(b'REV'),
1090 )
1091 ],
1092 )
1093 def overridepush(orig, ui, repo, *args, **kwargs):
1094 """Override push command and store --lfrev parameters in opargs"""
1095 lfrevs = kwargs.pop('lfrev', None)
1096 if lfrevs:
1097 opargs = kwargs.setdefault('opargs', {})
1098 opargs[b'lfrevs'] = logcmdutil.revrange(repo, lfrevs)
1099 return orig(ui, repo, *args, **kwargs)
1100
1101
1102 @eh.wrapfunction(exchange, 'pushoperation')
1103 def exchangepushoperation(orig, *args, **kwargs):
1104 """Override pushoperation constructor and store lfrevs parameter"""
1105 lfrevs = kwargs.pop('lfrevs', None)
1106 pushop = orig(*args, **kwargs)
1107 pushop.lfrevs = lfrevs
1108 return pushop
1109
1110
1111 @eh.revsetpredicate(b'pulled()')
1112 def pulledrevsetsymbol(repo, subset, x):
1113 """Changesets that just has been pulled.
1114
1115 Only available with largefiles from pull --lfrev expressions.
1116
1117 .. container:: verbose
1118
1119 Some examples:
1120
1121 - pull largefiles for all new changesets::
1122
1123 hg pull -lfrev "pulled()"
1124
1125 - pull largefiles for all new branch heads::
1126
1127 hg pull -lfrev "head(pulled()) and not closed()"
1128
1129 """
1130
1131 try:
1132 firstpulled = repo.firstpulled
1133 except AttributeError:
1134 raise error.Abort(_(b"pulled() only available in --lfrev"))
1135 return smartset.baseset([r for r in subset if r >= firstpulled])
1136
1137
1138 @eh.wrapcommand(
1139 b'clone',
1140 opts=[
1141 (
1142 b'',
1143 b'all-largefiles',
1144 None,
1145 _(b'download all versions of all largefiles'),
1146 )
1147 ],
1148 )
1149 def overrideclone(orig, ui, source, dest=None, **opts):
1150 d = dest
1151 if d is None:
1152 d = clone_impl.default_dest(source)
1153 if opts.get('all_largefiles') and urlutil.url(d).scheme not in (
1154 b'file',
1155 None,
1156 ):
1157 raise error.Abort(
1158 _(b'--all-largefiles is incompatible with non-local destination %s')
1159 % d
1160 )
1161
1162 return orig(ui, source, dest, **opts)
1163
1164
1165 @eh.wrapfunction(clone_impl, 'clone')
1166 def hgclone(orig, ui, opts, *args, **kwargs):
1167 result = orig(ui, opts, *args, **kwargs)
1168
1169 if result is not None:
1170 sourcerepo, destrepo = result
1171 repo = destrepo.local()
1172
1173 # When cloning to a remote repo (like through SSH), no repo is available
1174 # from the peer. Therefore the largefiles can't be downloaded and the
1175 # hgrc can't be updated.
1176 if not repo:
1177 return result
1178
1179 # Caching is implicitly limited to 'rev' option, since the dest repo was
1180 # truncated at that point. The user may expect a download count with
1181 # this option, so attempt whether or not this is a largefile repo.
1182 if opts.get(b'all_largefiles'):
1183 success, missing = lfcommands.downloadlfiles(ui, repo)
1184
1185 if missing != 0:
1186 return None
1187
1188 return result
1189
1190
1191 @eh.wrapcommand(b'rebase', extension=b'rebase')
1192 def overriderebasecmd(orig, ui, repo, **opts):
1193 if not hasattr(repo, '_largefilesenabled'):
1194 return orig(ui, repo, **opts)
1195
1196 resuming = opts.get('continue')
1197 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1198 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1199 try:
1200 with ui.configoverride(
1201 {(b'rebase', b'experimental.inmemory'): False}, b"largefiles"
1202 ):
1203 return orig(ui, repo, **opts)
1204 finally:
1205 repo._lfstatuswriters.pop()
1206 repo._lfcommithooks.pop()
1207
1208
1209 @eh.extsetup
1210 def overriderebase(ui: UiT) -> None:
1211 try:
1212 rebase = extensions.find(b'rebase')
1213 except KeyError:
1214 pass
1215 else:
1216
1217 def _dorebase(orig, *args, **kwargs):
1218 kwargs['inmemory'] = False
1219 return orig(*args, **kwargs)
1220
1221 extensions.wrapfunction(rebase, '_dorebase', _dorebase)
1222
1223
1224 @eh.wrapcommand(b'archive')
1225 def overridearchivecmd(orig, ui, repo, dest, **opts):
1226 with lfstatus(repo.unfiltered()):
1227 return orig(ui, repo.unfiltered(), dest, **opts)
1228
1229
1230 @eh.wrapfunction(webcommands, 'archive')
1231 def hgwebarchive(orig, web):
1232 with lfstatus(web.repo):
1233 return orig(web)
1234
1235
1236 @eh.wrapfunction(archival, 'archive')
1237 def overridearchive(
1238 orig,
1239 repo,
1240 dest,
1241 node,
1242 kind,
1243 decode=True,
1244 match: MatcherT | None = None,
1245 prefix=b'',
1246 mtime=None,
1247 subrepos=None,
1248 ):
1249 # For some reason setting repo.lfstatus in hgwebarchive only changes the
1250 # unfiltered repo's attr, so check that as well.
1251 if not repo.lfstatus and not repo.unfiltered().lfstatus:
1252 return orig(
1253 repo, dest, node, kind, decode, match, prefix, mtime, subrepos
1254 )
1255
1256 # No need to lock because we are only reading history and
1257 # largefile caches, neither of which are modified.
1258 if node is not None:
1259 lfcommands.cachelfiles(repo.ui, repo, node)
1260
1261 if kind not in archival.archivers:
1262 raise error.Abort(_(b"unknown archive type '%s'") % kind)
1263
1264 if kind == b'files':
1265 if prefix:
1266 raise error.Abort(_(b'cannot give prefix when archiving to files'))
1267 else:
1268 prefix = archival.tidyprefix(dest, kind, prefix)
1269
1270 if not match:
1271 match = scmutil.matchall(repo)
1272 archiver = None
1273 ctx = repo[node]
1274
1275 def opencallback():
1276 """Return the archiver instance, creating it if necessary.
1277
1278 This function is called when the first actual entry is created.
1279 It may be called multiple times from different layers.
1280 When serving the archive via hgweb, no errors should happen after
1281 this point.
1282 """
1283 nonlocal archiver
1284 if archiver is None:
1285 if callable(dest):
1286 output = dest()
1287 else:
1288 output = dest
1289 archiver = archival.archivers[kind](output, mtime or ctx.date()[0])
1290 assert archiver is not None
1291
1292 if repo.ui.configbool(b"ui", b"archivemeta"):
1293 metaname = b'.hg_archival.txt'
1294 if match(metaname):
1295 write(
1296 metaname,
1297 0o644,
1298 False,
1299 lambda: archival.buildmetadata(ctx),
1300 )
1301 return archiver
1302
1303 def write(name, mode, islink, getdata):
1304 if not match(name):
1305 return
1306 data = getdata()
1307 if decode:
1308 data = repo.wwritedata(name, data)
1309 if archiver is None:
1310 opencallback()
1311 assert archiver is not None, "archive should be opened by now"
1312 archiver.addfile(prefix + name, mode, islink, data)
1313
1314 for f in ctx:
1315 ff = ctx.flags(f)
1316 getdata = ctx[f].data
1317 lfile = lfutil.splitstandin(f)
1318 if lfile is not None:
1319 if node is not None:
1320 path = lfutil.findfile(repo, getdata().strip())
1321
1322 if path is None:
1323 raise error.Abort(
1324 _(
1325 b'largefile %s not found in repo store or system cache'
1326 )
1327 % lfile
1328 )
1329 else:
1330 path = lfile
1331
1332 f = lfile
1333
1334 getdata = lambda: util.readfile(path)
1335 write(f, b'x' in ff and 0o755 or 0o644, b'l' in ff, getdata)
1336
1337 if subrepos:
1338 for subpath in sorted(ctx.substate):
1339 sub = ctx.workingsub(subpath)
1340 submatch = matchmod.subdirmatcher(subpath, match)
1341 subprefix = prefix + subpath + b'/'
1342
1343 # TODO: Only hgsubrepo instances have `_repo`, so figure out how to
1344 # infer and possibly set lfstatus in hgsubrepoarchive. That would
1345 # allow only hgsubrepos to set this, instead of the current scheme
1346 # where the parent sets this for the child.
1347 with (
1348 lfstatus(sub._repo)
1349 if hasattr(sub, '_repo')
1350 else util.nullcontextmanager()
1351 ):
1352 sub.archive(opencallback, subprefix, submatch)
1353
1354 if archiver:
1355 archiver.done()
1356
1357
1358 @eh.wrapfunction(subrepo.hgsubrepo, 'archive')
1359 def hgsubrepoarchive(orig, repo, opener, prefix, match: MatcherT, decode=True):
1360 lfenabled = hasattr(repo._repo, '_largefilesenabled')
1361 if not lfenabled or not repo._repo.lfstatus:
1362 return orig(repo, opener, prefix, match, decode)
1363
1364 repo._get(repo._state + (b'hg',))
1365 rev = repo._state[1]
1366 ctx = repo._repo[rev]
1367
1368 if ctx.node() is not None:
1369 lfcommands.cachelfiles(repo.ui, repo._repo, ctx.node())
1370
1371 archiver = None
1372
1373 def write(name, mode, islink, getdata):
1374 nonlocal archiver
1375 # At this point, the standin has been replaced with the largefile name,
1376 # so the normal matcher works here without the lfutil variants.
1377 if not match(f):
1378 return
1379 data = getdata()
1380 if decode:
1381 data = repo._repo.wwritedata(name, data)
1382
1383 if archiver is None:
1384 archiver = opener()
1385 archiver.addfile(prefix + name, mode, islink, data)
1386
1387 for f in ctx:
1388 ff = ctx.flags(f)
1389 getdata = ctx[f].data
1390 lfile = lfutil.splitstandin(f)
1391 if lfile is not None:
1392 if ctx.node() is not None:
1393 path = lfutil.findfile(repo._repo, getdata().strip())
1394
1395 if path is None:
1396 raise error.Abort(
1397 _(
1398 b'largefile %s not found in repo store or system cache'
1399 )
1400 % lfile
1401 )
1402 else:
1403 path = lfile
1404
1405 f = lfile
1406
1407 getdata = lambda: util.readfile(os.path.join(prefix, path))
1408
1409 write(f, b'x' in ff and 0o755 or 0o644, b'l' in ff, getdata)
1410
1411 for subpath in sorted(ctx.substate):
1412 sub = ctx.workingsub(subpath)
1413 submatch = matchmod.subdirmatcher(subpath, match)
1414 subprefix = prefix + subpath + b'/'
1415 # TODO: Only hgsubrepo instances have `_repo`, so figure out how to
1416 # infer and possibly set lfstatus at the top of this function. That
1417 # would allow only hgsubrepos to set this, instead of the current scheme
1418 # where the parent sets this for the child.
1419 with (
1420 lfstatus(sub._repo)
1421 if hasattr(sub, '_repo')
1422 else util.nullcontextmanager()
1423 ):
1424 sub.archive(opener, subprefix, submatch, decode)
1425
1426
1427 # If a largefile is modified, the change is not reflected in its
1428 # standin until a commit. scmutil.bail_if_changed() raises an exception
1429 # if the repo has uncommitted changes. Wrap it to also check if
1430 # largefiles were changed. This is used by bisect, backout and fetch.
1431 @eh.wrapfunction(scmutil, 'bail_if_changed')
1432 def overridebailifchanged(orig, repo: RepoT, *args, **kwargs) -> None:
1433 orig(repo, *args, **kwargs)
1434 with lfstatus(repo):
1435 s = repo.status()
1436 if s.modified or s.added or s.removed or s.deleted:
1437 raise error.Abort(_(b'uncommitted changes'))
1438
1439
1440 @eh.wrapfunction(cmdutil, 'postcommitstatus')
1441 def postcommitstatus(orig, repo, *args, **kwargs):
1442 with lfstatus(repo):
1443 return orig(repo, *args, **kwargs)
1444
1445
1446 @eh.wrapfunction(cmdutil, 'forget')
1447 def cmdutilforget(
1448 orig, ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
1449 ):
1450 normalmatcher = composenormalfilematcher(match, repo[None].manifest())
1451 bad, forgot = orig(
1452 ui,
1453 repo,
1454 normalmatcher,
1455 prefix,
1456 uipathfn,
1457 explicitonly,
1458 dryrun,
1459 interactive,
1460 )
1461 m = composelargefilematcher(match, repo[None].manifest())
1462
1463 with lfstatus(repo):
1464 s = repo.status(match=m, clean=True)
1465 manifest = repo[None].manifest()
1466 forget = sorted(s.modified + s.added + s.deleted + s.clean)
1467 forget = [f for f in forget if lfutil.standin(f) in manifest]
1468
1469 for f in forget:
1470 fstandin = lfutil.standin(f)
1471 if fstandin not in repo.dirstate and not repo.wvfs.isdir(fstandin):
1472 ui.warn(
1473 _(b'not removing %s: file is already untracked\n') % uipathfn(f)
1474 )
1475 bad.append(f)
1476
1477 for f in forget:
1478 if ui.verbose or not m.exact(f):
1479 ui.status(_(b'removing %s\n') % uipathfn(f))
1480
1481 # Need to lock because standin files are deleted then removed from the
1482 # repository and we could race in-between.
1483 with repo.wlock():
1484 lfdirstate = lfutil.openlfdirstate(ui, repo)
1485 for f in forget:
1486 lfdirstate.set_untracked(f)
1487 lfdirstate.write(repo.currenttransaction())
1488 standins = [lfutil.standin(f) for f in forget]
1489 for f in standins:
1490 repo.wvfs.unlinkpath(f, ignoremissing=True)
1491 rejected = repo[None].forget(standins)
1492
1493 bad.extend(f for f in rejected if f in m.files())
1494 forgot.extend(f for f in forget if f not in rejected)
1495 return bad, forgot
1496
1497
1498 def _getoutgoings(repo, other, missing, addfunc):
1499 """get pairs of filename and largefile hash in outgoing revisions
1500 in 'missing'.
1501
1502 largefiles already existing on 'other' repository are ignored.
1503
1504 'addfunc' is invoked with each unique pairs of filename and
1505 largefile hash value.
1506 """
1507 knowns = set()
1508 lfhashes = set()
1509
1510 def dedup(fn, lfhash):
1511 k = (fn, lfhash)
1512 if k not in knowns:
1513 knowns.add(k)
1514 lfhashes.add(lfhash)
1515
1516 lfutil.getlfilestoupload(repo, missing, dedup)
1517 if lfhashes:
1518 lfexists = storefactory.openstore(repo, other).exists(lfhashes)
1519 for fn, lfhash in knowns:
1520 if not lfexists[lfhash]: # lfhash doesn't exist on "other"
1521 addfunc(fn, lfhash)
1522
1523
1524 def outgoinghook(ui, repo, other, opts, missing):
1525 if opts.pop(b'large', None):
1526 lfhashes = set()
1527 if ui.debugflag:
1528 toupload = {}
1529
1530 def addfunc(fn, lfhash):
1531 if fn not in toupload:
1532 toupload[fn] = [] # pytype: disable=unsupported-operands
1533 toupload[fn].append(lfhash)
1534 lfhashes.add(lfhash)
1535
1536 def showhashes(fn):
1537 for lfhash in sorted(toupload[fn]):
1538 ui.debug(b' %s\n' % lfhash)
1539
1540 else:
1541 toupload = set()
1542
1543 def addfunc(fn, lfhash):
1544 toupload.add(fn)
1545 lfhashes.add(lfhash)
1546
1547 def showhashes(fn):
1548 pass
1549
1550 _getoutgoings(repo, other, missing, addfunc)
1551
1552 if not toupload:
1553 ui.status(_(b'largefiles: no files to upload\n'))
1554 else:
1555 ui.status(
1556 _(b'largefiles to upload (%d entities):\n') % (len(lfhashes))
1557 )
1558 for file in sorted(toupload):
1559 ui.status(lfutil.splitstandin(file) + b'\n')
1560 showhashes(file)
1561 ui.status(b'\n')
1562
1563
1564 @eh.wrapcommand(
1565 b'outgoing', opts=[(b'', b'large', None, _(b'display outgoing largefiles'))]
1566 )
1567 def _outgoingcmd(orig, *args, **kwargs):
1568 # Nothing to do here other than add the extra help option- the hook above
1569 # processes it.
1570 return orig(*args, **kwargs)
1571
1572
1573 def summaryremotehook(ui, repo, opts, changes):
1574 largeopt = opts.get(b'large', False)
1575 if changes is None:
1576 if largeopt:
1577 return (False, True) # only outgoing check is needed
1578 else:
1579 return (False, False)
1580 elif largeopt:
1581 url, branch, peer, outgoing = changes[1]
1582 if peer is None:
1583 # i18n: column positioning for "hg summary"
1584 ui.status(_(b'largefiles: (no remote repo)\n'))
1585 return
1586
1587 toupload = set()
1588 lfhashes = set()
1589
1590 def addfunc(fn, lfhash):
1591 toupload.add(fn)
1592 lfhashes.add(lfhash)
1593
1594 _getoutgoings(repo, peer, outgoing.missing, addfunc)
1595
1596 if not toupload:
1597 # i18n: column positioning for "hg summary"
1598 ui.status(_(b'largefiles: (no files to upload)\n'))
1599 else:
1600 # i18n: column positioning for "hg summary"
1601 ui.status(
1602 _(b'largefiles: %d entities for %d files to upload\n')
1603 % (len(lfhashes), len(toupload))
1604 )
1605
1606
1607 @eh.wrapcommand(
1608 b'summary', opts=[(b'', b'large', None, _(b'display outgoing largefiles'))]
1609 )
1610 def overridesummary(orig, ui, repo, *pats, **opts):
1611 with lfstatus(repo):
1612 orig(ui, repo, *pats, **opts)
1613
1614
1615 @eh.wrapfunction(scmutil, 'addremove')
1616 def scmutiladdremove(
1617 orig,
1618 repo,
1619 matcher,
1620 prefix,
1621 uipathfn,
1622 opts=None,
1623 open_tr=None,
1624 ):
1625 if opts is None:
1626 opts = {}
1627 if not lfutil.islfilesrepo(repo):
1628 return orig(repo, matcher, prefix, uipathfn, opts, open_tr=open_tr)
1629
1630 # open the transaction and changing_files context
1631 if open_tr is not None:
1632 open_tr()
1633
1634 # Get the list of missing largefiles so we can remove them
1635 with repo.dirstate.running_status(repo):
1636 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1637 unsure, s, mtime_boundary = lfdirstate.status(
1638 matchmod.always(),
1639 subrepos=[],
1640 ignored=False,
1641 clean=False,
1642 unknown=False,
1643 )
1644
1645 # Call into the normal remove code, but the removing of the standin, we want
1646 # to have handled by original addremove. Monkey patching here makes sure
1647 # we don't remove the standin in the largefiles code, preventing a very
1648 # confused state later.
1649 if s.deleted:
1650 m = copy.copy(matcher)
1651 m._was_tampered_with = True
1652
1653 # The m._files and m._map attributes are not changed to the deleted list
1654 # because that affects the m.exact() test, which in turn governs whether
1655 # or not the file name is printed, and how. Simply limit the original
1656 # matches to those in the deleted status list.
1657 matchfn = m.matchfn
1658 m.matchfn = lambda f: f in s.deleted and matchfn(f)
1659
1660 removelargefiles(
1661 repo.ui,
1662 repo,
1663 True,
1664 m,
1665 uipathfn,
1666 opts.get(b'dry_run'),
1667 **pycompat.strkwargs(opts),
1668 )
1669 # Call into the normal add code, and any files that *should* be added as
1670 # largefiles will be
1671 added, bad = addlargefiles(
1672 repo.ui, repo, True, matcher, uipathfn, **pycompat.strkwargs(opts)
1673 )
1674 # Now that we've handled largefiles, hand off to the original addremove
1675 # function to take care of the rest. Make sure it doesn't do anything with
1676 # largefiles by passing a matcher that will ignore them.
1677 matcher = composenormalfilematcher(matcher, repo[None].manifest(), added)
1678
1679 return orig(repo, matcher, prefix, uipathfn, opts, open_tr=open_tr)
1680
1681
1682 # Calling purge with --all will cause the largefiles to be deleted.
1683 # Override repo.status to prevent this from happening.
1684 @eh.wrapcommand(b'purge')
1685 def overridepurge(orig, ui, repo, *dirs, **opts):
1686 # XXX Monkey patching a repoview will not work. The assigned attribute will
1687 # be set on the unfiltered repo, but we will only lookup attributes in the
1688 # unfiltered repo if the lookup in the repoview object itself fails. As the
1689 # monkey patched method exists on the repoview class the lookup will not
1690 # fail. As a result, the original version will shadow the monkey patched
1691 # one, defeating the monkey patch.
1692 #
1693 # As a work around we use an unfiltered repo here. We should do something
1694 # cleaner instead.
1695 repo = repo.unfiltered()
1696 oldstatus = repo.status
1697
1698 def overridestatus(
1699 node1=b'.',
1700 node2=None,
1701 match=None,
1702 ignored=False,
1703 clean=False,
1704 unknown=False,
1705 listsubrepos=False,
1706 empty_dirs_keep_files=False,
1707 ):
1708 r = oldstatus(
1709 node1,
1710 node2,
1711 match,
1712 ignored,
1713 clean,
1714 unknown,
1715 listsubrepos,
1716 empty_dirs_keep_files,
1717 )
1718 lfdirstate = lfutil.openlfdirstate(ui, repo)
1719 unknown = [
1720 f for f in r.unknown if not lfdirstate.get_entry(f).any_tracked
1721 ]
1722 ignored = [
1723 f for f in r.ignored if not lfdirstate.get_entry(f).any_tracked
1724 ]
1725 return scmutil.status(
1726 r.modified, r.added, r.removed, r.deleted, unknown, ignored, r.clean
1727 )
1728
1729 repo.status = overridestatus
1730 orig(ui, repo, *dirs, **opts)
1731 repo.status = oldstatus
1732
1733
1734 @eh.wrapcommand(b'rollback')
1735 def overriderollback(orig, ui, repo, **opts):
1736 with repo.wlock():
1737 before = repo.dirstate.parents()
1738 orphans = {
1739 f
1740 for f in repo.dirstate
1741 if lfutil.isstandin(f) and not repo.dirstate.get_entry(f).removed
1742 }
1743 result = orig(ui, repo, **opts)
1744 after = repo.dirstate.parents()
1745 if before == after:
1746 return result # no need to restore standins
1747
1748 pctx = repo[b'.']
1749 for f in repo.dirstate:
1750 if lfutil.isstandin(f):
1751 orphans.discard(f)
1752 if repo.dirstate.get_entry(f).removed:
1753 repo.wvfs.unlinkpath(f, ignoremissing=True)
1754 elif f in pctx:
1755 fctx = pctx[f]
1756 repo.wwrite(f, fctx.data(), fctx.flags())
1757 else:
1758 # content of standin is not so important in 'a',
1759 # 'm' or 'n' (coming from the 2nd parent) cases
1760 lfutil.writestandin(repo, f, b'', False)
1761 for standin in orphans:
1762 repo.wvfs.unlinkpath(standin, ignoremissing=True)
1763
1764 return result
1765
1766
1767 @eh.wrapcommand(b'transplant', extension=b'transplant')
1768 def overridetransplant(orig, ui, repo, *revs, **opts):
1769 resuming = opts.get('continue')
1770 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1771 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1772 try:
1773 result = orig(ui, repo, *revs, **opts)
1774 finally:
1775 repo._lfstatuswriters.pop()
1776 repo._lfcommithooks.pop()
1777 return result
1778
1779
1780 @eh.wrapcommand(b'cat')
1781 def overridecat(orig, ui, repo, file1, *pats, **opts):
1782 ctx = logcmdutil.revsingle(repo, opts.get('rev'))
1783 err = 1
1784 notbad = set()
1785 m = scmutil.match(ctx, (file1,) + pats, pycompat.byteskwargs(opts))
1786 m._was_tampered_with = True
1787 origmatchfn = m.matchfn
1788
1789 def lfmatchfn(f):
1790 if origmatchfn(f):
1791 return True
1792 lf = lfutil.splitstandin(f)
1793 if lf is None:
1794 return False
1795 notbad.add(lf)
1796 return origmatchfn(lf)
1797
1798 m.matchfn = lfmatchfn
1799 origbadfn = m.bad
1800
1801 def lfbadfn(f, msg):
1802 if not f in notbad:
1803 origbadfn(f, msg)
1804
1805 m.bad = lfbadfn
1806
1807 origvisitdirfn = m.visitdir
1808
1809 def lfvisitdirfn(dir):
1810 if dir == lfutil.shortname:
1811 return True
1812 ret = origvisitdirfn(dir)
1813 if ret:
1814 return ret
1815 lf = lfutil.splitstandin(dir)
1816 if lf is None:
1817 return False
1818 return origvisitdirfn(lf)
1819
1820 m.visitdir = lfvisitdirfn
1821
1822 for f in ctx.walk(m):
1823 with cmdutil.makefileobj(ctx, opts.get('output'), pathname=f) as fp:
1824 lf = lfutil.splitstandin(f)
1825 if lf is None or origmatchfn(f):
1826 # duplicating unreachable code from commands.cat
1827 data = ctx[f].data()
1828 if opts.get('decode'):
1829 data = repo.wwritedata(f, data)
1830 fp.write(data)
1831 else:
1832 hash = lfutil.readasstandin(ctx[f])
1833 if not lfutil.inusercache(repo.ui, hash):
1834 store = storefactory.openstore(repo)
1835 success, missing = store.get([(lf, hash)])
1836 if len(success) != 1:
1837 raise error.Abort(
1838 _(
1839 b'largefile %s is not in cache and could not be '
1840 b'downloaded'
1841 )
1842 % lf
1843 )
1844 path = lfutil.usercachepath(repo.ui, hash)
1845 with open(path, "rb") as fpin:
1846 for chunk in util.filechunkiter(fpin):
1847 fp.write(chunk)
1848 err = 0
1849 return err
1850
1851
1852 @eh.wrapfunction(merge, '_update')
1853 def mergeupdate(orig, repo, node, branchmerge, force, *args, **kwargs):
1854 matcher = kwargs.get('matcher', None)
1855 # note if this is a partial update
1856 partial = matcher and not matcher.always()
1857 with repo.wlock(), repo.dirstate.changing_parents(repo):
1858 # branch | | |
1859 # merge | force | partial | action
1860 # -------+-------+---------+--------------
1861 # x | x | x | linear-merge
1862 # o | x | x | branch-merge
1863 # x | o | x | overwrite (as clean update)
1864 # o | o | x | force-branch-merge (*1)
1865 # x | x | o | (*)
1866 # o | x | o | (*)
1867 # x | o | o | overwrite (as revert)
1868 # o | o | o | (*)
1869 #
1870 # (*) don't care
1871 # (*1) deprecated, but used internally (e.g: "rebase --collapse")
1872 with repo.dirstate.running_status(repo):
1873 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1874 unsure, s, mtime_boundary = lfdirstate.status(
1875 matchmod.always(),
1876 subrepos=[],
1877 ignored=False,
1878 clean=True,
1879 unknown=False,
1880 )
1881 oldclean = set(s.clean)
1882 pctx = repo[b'.']
1883 dctx = repo[node]
1884 for lfile in unsure + s.modified:
1885 lfileabs = repo.wvfs.join(lfile)
1886 if not repo.wvfs.exists(lfileabs):
1887 continue
1888 lfhash = lfutil.hashfile(lfileabs)
1889 standin = lfutil.standin(lfile)
1890 lfutil.writestandin(
1891 repo, standin, lfhash, lfutil.getexecutable(lfileabs)
1892 )
1893 if standin in pctx and lfhash == lfutil.readasstandin(
1894 pctx[standin]
1895 ):
1896 oldclean.add(lfile)
1897 for lfile in s.added:
1898 fstandin = lfutil.standin(lfile)
1899 if fstandin not in dctx:
1900 # in this case, content of standin file is meaningless
1901 # (in dctx, lfile is unknown, or normal file)
1902 continue
1903 lfutil.updatestandin(repo, lfile, fstandin)
1904 # mark all clean largefiles as dirty, just in case the update gets
1905 # interrupted before largefiles and lfdirstate are synchronized
1906 for lfile in oldclean:
1907 entry = lfdirstate.get_entry(lfile)
1908 lfdirstate.hacky_extension_update_file(
1909 lfile,
1910 wc_tracked=entry.tracked,
1911 p1_tracked=entry.p1_tracked,
1912 p2_info=entry.p2_info,
1913 possibly_dirty=True,
1914 )
1915 lfdirstate.write(repo.currenttransaction())
1916
1917 oldstandins = lfutil.getstandinsstate(repo)
1918 wc = kwargs.get('wc')
1919 if wc and wc.isinmemory():
1920 # largefiles is not a good candidate for in-memory merge (large
1921 # files, custom dirstate, matcher usage).
1922 raise error.ProgrammingError(
1923 b'largefiles is not compatible with in-memory merge'
1924 )
1925 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1926
1927 newstandins = lfutil.getstandinsstate(repo)
1928 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1929
1930 # to avoid leaving all largefiles as dirty and thus rehash them, mark
1931 # all the ones that didn't change as clean
1932 for lfile in oldclean.difference(filelist):
1933 lfdirstate.update_file(lfile, p1_tracked=True, wc_tracked=True)
1934
1935 if branchmerge or force or partial:
1936 filelist.extend(s.deleted + s.removed)
1937
1938 lfcommands.updatelfiles(
1939 repo.ui, repo, filelist=filelist, normallookup=partial
1940 )
1941
1942 return result
1943
1944
1945 @eh.wrapfunction(scmutil, 'marktouched')
1946 def scmutilmarktouched(orig, repo, files, *args, **kwargs):
1947 result = orig(repo, files, *args, **kwargs)
1948
1949 filelist = []
1950 for f in files:
1951 lf = lfutil.splitstandin(f)
1952 if lf is not None:
1953 filelist.append(lf)
1954 if filelist:
1955 lfcommands.updatelfiles(
1956 repo.ui,
1957 repo,
1958 filelist=filelist,
1959 printmessage=False,
1960 normallookup=True,
1961 )
1962
1963 return result
1964
1965
1966 @eh.wrapfunction(upgrade_actions, 'preservedrequirements')
1967 @eh.wrapfunction(upgrade_actions, 'supporteddestrequirements')
1968 def upgraderequirements(orig, repo):
1969 reqs = orig(repo)
1970 if b'largefiles' in repo.requirements:
1971 reqs.add(b'largefiles')
1972 return reqs
1973
1974
1975 _lfscheme = b'largefile://'
1976
1977
1978 @eh.wrapfunction(urlmod, 'open')
1979 def openlargefile(orig, ui, url_, data=None, **kwargs):
1980 if url_.startswith(_lfscheme):
1981 if data:
1982 msg = b"cannot use data on a 'largefile://' url"
1983 raise error.ProgrammingError(msg)
1984 lfid = url_[len(_lfscheme) :]
1985 return storefactory.getlfile(ui, lfid)
1986 else:
1987 return orig(ui, url_, data=data, **kwargs)