Debian Codegraph @

hgext/largefiles/lfcommands.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 '''High-level command function for lfconvert, plus the cmdtable.'''
10
11 from __future__ import annotations
12
13 import binascii
14 import os
15 import shutil
16
17 from mercurial.i18n import _
18 from mercurial.node import (
19 bin,
20 hex,
21 )
22
23 from mercurial import (
24 cmdutil,
25 context,
26 error,
27 exthelper,
28 lock,
29 logcmdutil,
30 match as matchmod,
31 scmutil,
32 util,
33 )
34 from mercurial.repo import (
35 factory as repo_factory,
36 )
37 from mercurial.utils import hashutil
38
39 from ..convert import (
40 convcmd,
41 filemap,
42 )
43
44 from . import lfutil, storefactory
45
46 release = lock.release
47
48 # -- Commands ----------------------------------------------------------
49
50 eh = exthelper.exthelper()
51
52
53 @eh.command(
54 b'lfconvert',
55 [
56 (
57 b's',
58 b'size',
59 b'',
60 _(b'minimum size (MB) for files to be converted as largefiles'),
61 b'SIZE',
62 ),
63 (
64 b'',
65 b'to-normal',
66 False,
67 _(b'convert from a largefiles repo to a normal repo'),
68 ),
69 ],
70 _(b'hg lfconvert SOURCE DEST [FILE ...]'),
71 norepo=True,
72 inferrepo=True,
73 )
74 def lfconvert(ui, src, dest, *pats, **opts):
75 """convert a normal repository to a largefiles repository
76
77 Convert repository SOURCE to a new repository DEST, identical to
78 SOURCE except that certain files will be converted as largefiles:
79 specifically, any file that matches any PATTERN *or* whose size is
80 above the minimum size threshold is converted as a largefile. The
81 size used to determine whether or not to track a file as a
82 largefile is the size of the first version of the file. The
83 minimum size can be specified either with --size or in
84 configuration as ``largefiles.size``.
85
86 After running this command you will need to make sure that
87 largefiles is enabled anywhere you intend to push the new
88 repository.
89
90 Use --to-normal to convert largefiles back to normal files; after
91 this, the DEST repository can be used without largefiles at all."""
92
93 if opts['to_normal']:
94 tolfile = False
95 else:
96 tolfile = True
97 size = lfutil.getminsize(ui, True, opts.get('size'), default=None)
98
99 if not repo_factory.is_local(src):
100 raise error.Abort(_(b'%s is not a local Mercurial repo') % src)
101 if not repo_factory.is_local(dest):
102 raise error.Abort(_(b'%s is not a local Mercurial repo') % dest)
103
104 rsrc = repo_factory.repository(ui, src)
105 ui.status(_(b'initializing destination %s\n') % dest)
106 rdst = repo_factory.repository(ui, dest, create=True)
107
108 success = False
109 dstwlock = dstlock = None
110 try:
111 # Get a list of all changesets in the source. The easy way to do this
112 # is to simply walk the changelog, using changelog.nodesbetween().
113 # Take a look at mercurial/revlog.py:639 for more details.
114 # Use a generator instead of a list to decrease memory usage
115 ctxs = (
116 rsrc[ctx]
117 for ctx in rsrc.changelog.nodesbetween(None, rsrc.heads())[0]
118 )
119 revmap = {rsrc.nullid: rdst.nullid}
120 if tolfile:
121 # Lock destination to prevent modification while it is converted to.
122 # Don't need to lock src because we are just reading from its
123 # history which can't change.
124 dstwlock = rdst.wlock()
125 dstlock = rdst.lock()
126
127 lfiles = set()
128 normalfiles = set()
129 if not pats:
130 pats = ui.configlist(lfutil.longname, b'patterns')
131 if pats:
132 matcher = matchmod.match(rsrc.root, b'', list(pats))
133 else:
134 matcher = None
135
136 lfiletohash = {}
137 with ui.makeprogress(
138 _(b'converting revisions'),
139 unit=_(b'revisions'),
140 total=rsrc[b'tip'].rev(),
141 ) as progress:
142 for ctx in ctxs:
143 progress.update(ctx.rev())
144 _lfconvert_addchangeset(
145 rsrc,
146 rdst,
147 ctx,
148 revmap,
149 lfiles,
150 normalfiles,
151 matcher,
152 size,
153 lfiletohash,
154 )
155
156 if rdst.wvfs.exists(lfutil.shortname):
157 rdst.wvfs.rmtree(lfutil.shortname)
158
159 for f in lfiletohash.keys():
160 if rdst.wvfs.isfile(f):
161 rdst.wvfs.unlink(f)
162 try:
163 rdst.wvfs.removedirs(rdst.wvfs.dirname(f))
164 except OSError:
165 pass
166
167 # If there were any files converted to largefiles, add largefiles
168 # to the destination repository's requirements.
169 if lfiles:
170 rdst.requirements.add(b'largefiles')
171 scmutil.writereporequirements(rdst)
172 else:
173
174 class lfsource(filemap.filemap_source):
175 def __init__(self, ui, source):
176 super().__init__(ui, source, None)
177 self.filemapper.rename[lfutil.shortname] = b'.'
178
179 def getfile(self, name, rev):
180 realname, realrev = rev
181 f = super().getfile(name, rev)
182
183 if (
184 not realname.startswith(lfutil.shortnameslash)
185 or f[0] is None
186 ):
187 return f
188
189 # Substitute in the largefile data for the hash
190 hash = f[0].strip()
191 path = lfutil.findfile(rsrc, hash)
192
193 if path is None:
194 raise error.Abort(
195 _(b"missing largefile for '%s' in %s")
196 % (realname, realrev)
197 )
198 return util.readfile(path), f[1]
199
200 class converter(convcmd.converter):
201 def __init__(self, ui, source, dest, revmapfile, opts):
202 src = lfsource(ui, source)
203
204 super().__init__(ui, src, dest, revmapfile, opts)
205
206 found, missing = downloadlfiles(ui, rsrc)
207 if missing != 0:
208 raise error.Abort(_(b"all largefiles must be present locally"))
209
210 orig = convcmd.converter
211 convcmd.converter = converter
212
213 try:
214 convcmd.convert(
215 ui, src, dest, source_type=b'hg', dest_type=b'hg'
216 )
217 finally:
218 convcmd.converter = orig
219 success = True
220 finally:
221 if tolfile:
222 # XXX is this the right context semantically ?
223 with rdst.dirstate.changing_parents(rdst):
224 rdst.dirstate.clear()
225 release(dstlock, dstwlock)
226 if not success:
227 # we failed, remove the new directory
228 shutil.rmtree(rdst.root)
229
230
231 def _lfconvert_addchangeset(
232 rsrc, rdst, ctx, revmap, lfiles, normalfiles, matcher, size, lfiletohash
233 ):
234 # Convert src parents to dst parents
235 parents = _convertparents(ctx, revmap)
236
237 # Generate list of changed files
238 files = _getchangedfiles(ctx, parents)
239
240 dstfiles = []
241 for f in files:
242 if f not in lfiles and f not in normalfiles:
243 islfile = _islfile(f, ctx, matcher, size)
244 # If this file was renamed or copied then copy
245 # the largefile-ness of its predecessor
246 if f in ctx.manifest():
247 fctx = ctx.filectx(f)
248 renamed = fctx.copysource()
249 if renamed is None:
250 # the code below assumes renamed to be a boolean or a list
251 # and won't quite work with the value None
252 renamed = False
253 renamedlfile = renamed and renamed in lfiles
254 islfile |= renamedlfile
255 if b'l' in fctx.flags():
256 if renamedlfile:
257 raise error.Abort(
258 _(b'renamed/copied largefile %s becomes symlink')
259 % f
260 )
261 islfile = False
262 if islfile:
263 lfiles.add(f)
264 else:
265 normalfiles.add(f)
266
267 if f in lfiles:
268 fstandin = lfutil.standin(f)
269 dstfiles.append(fstandin)
270 # largefile in manifest if it has not been removed/renamed
271 if f in ctx.manifest():
272 fctx = ctx.filectx(f)
273 if b'l' in fctx.flags():
274 renamed = fctx.copysource()
275 if renamed and renamed in lfiles:
276 raise error.Abort(
277 _(b'largefile %s becomes symlink') % f
278 )
279
280 # largefile was modified, update standins
281 m = hashutil.sha1(b'')
282 m.update(ctx[f].data())
283 hash = hex(m.digest())
284 if f not in lfiletohash or lfiletohash[f] != hash:
285 rdst.wwrite(f, ctx[f].data(), ctx[f].flags())
286 executable = b'x' in ctx[f].flags()
287 lfutil.writestandin(rdst, fstandin, hash, executable)
288 lfiletohash[f] = hash
289 else:
290 # normal file
291 dstfiles.append(f)
292
293 def getfilectx(repo, memctx, f):
294 srcfname = lfutil.splitstandin(f)
295 if srcfname is not None:
296 # if the file isn't in the manifest then it was removed
297 # or renamed, return None to indicate this
298 try:
299 fctx = ctx.filectx(srcfname)
300 except error.LookupError:
301 return None
302 renamed = fctx.copysource()
303 if renamed:
304 # standin is always a largefile because largefile-ness
305 # doesn't change after rename or copy
306 renamed = lfutil.standin(renamed)
307
308 return context.memfilectx(
309 repo,
310 memctx,
311 f,
312 lfiletohash[srcfname] + b'\n',
313 b'l' in fctx.flags(),
314 b'x' in fctx.flags(),
315 renamed,
316 )
317 else:
318 return _getnormalcontext(repo, ctx, f, revmap)
319
320 # Commit
321 _commitcontext(rdst, parents, ctx, dstfiles, getfilectx, revmap)
322
323
324 def _commitcontext(rdst, parents, ctx, dstfiles, getfilectx, revmap):
325 mctx = context.memctx(
326 rdst,
327 parents,
328 ctx.description(),
329 dstfiles,
330 getfilectx,
331 ctx.user(),
332 ctx.date(),
333 ctx.extra(),
334 )
335 ret = rdst.commitctx(mctx)
336 lfutil.copyalltostore(rdst, ret)
337 rdst.setparents(ret)
338 revmap[ctx.node()] = rdst.changelog.tip()
339
340
341 # Generate list of changed files
342 def _getchangedfiles(ctx, parents):
343 files = set(ctx.files())
344 if ctx.repo().nullid not in parents:
345 mc = ctx.manifest()
346 for pctx in ctx.parents():
347 for fn in pctx.manifest().diff(mc):
348 files.add(fn)
349 return files
350
351
352 # Convert src parents to dst parents
353 def _convertparents(ctx, revmap):
354 parents = []
355 for p in ctx.parents():
356 parents.append(revmap[p.node()])
357 while len(parents) < 2:
358 parents.append(ctx.repo().nullid)
359 return parents
360
361
362 # Get memfilectx for a normal file
363 def _getnormalcontext(repo, ctx, f, revmap):
364 try:
365 fctx = ctx.filectx(f)
366 except error.LookupError:
367 return None
368 renamed = fctx.copysource()
369
370 data = fctx.data()
371 if f == b'.hgtags':
372 data = _converttags(repo.ui, revmap, data)
373 return context.memfilectx(
374 repo, ctx, f, data, b'l' in fctx.flags(), b'x' in fctx.flags(), renamed
375 )
376
377
378 # Remap tag data using a revision map
379 def _converttags(ui, revmap, data):
380 newdata = []
381 for line in data.splitlines():
382 try:
383 id, name = line.split(b' ', 1)
384 except ValueError:
385 ui.warn(_(b'skipping incorrectly formatted tag %s\n') % line)
386 continue
387 try:
388 newid = bin(id)
389 except binascii.Error:
390 ui.warn(_(b'skipping incorrectly formatted id %s\n') % id)
391 continue
392 try:
393 newdata.append(b'%s %s\n' % (hex(revmap[newid]), name))
394 except KeyError:
395 ui.warn(_(b'no mapping for id %s\n') % id)
396 continue
397 return b''.join(newdata)
398
399
400 def _islfile(file, ctx, matcher, size):
401 """Return true if file should be considered a largefile, i.e.
402 matcher matches it or it is larger than size."""
403 # never store special .hg* files as largefiles
404 if file == b'.hgtags' or file == b'.hgignore' or file == b'.hgsigs':
405 return False
406 if matcher and matcher(file):
407 return True
408 try:
409 return ctx.filectx(file).size() >= size * 1024 * 1024
410 except error.LookupError:
411 return False
412
413
414 def uploadlfiles(ui, rsrc, rdst, files):
415 '''upload largefiles to the central store'''
416
417 if not files:
418 return
419
420 store = storefactory.openstore(rsrc, rdst, put=True)
421
422 at = 0
423 ui.debug(b"sending statlfile command for %d largefiles\n" % len(files))
424 retval = store.exists(files)
425 files = [h for h in files if not retval[h]]
426 ui.debug(b"%d largefiles need to be uploaded\n" % len(files))
427
428 with ui.makeprogress(
429 _(b'uploading largefiles'), unit=_(b'files'), total=len(files)
430 ) as progress:
431 for hash in files:
432 progress.update(at)
433 source = lfutil.findfile(rsrc, hash)
434 if not source:
435 raise error.Abort(
436 _(
437 b'largefile %s missing from store'
438 b' (needs to be uploaded)'
439 )
440 % hash
441 )
442 # XXX check for errors here
443 store.put(source, hash)
444 at += 1
445
446
447 def verifylfiles(ui, repo, all=False, contents=False):
448 """Verify that every largefile revision in the current changeset
449 exists in the central store. With --contents, also verify that
450 the contents of each local largefile file revision are correct (SHA-1 hash
451 matches the revision ID). With --all, check every changeset in
452 this repository."""
453 if all:
454 revs = repo.revs(b'all()')
455 else:
456 revs = [b'.']
457
458 store = storefactory.openstore(repo)
459 return store.verify(revs, contents=contents)
460
461
462 def cachelfiles(ui, repo, node, filelist=None):
463 """cachelfiles ensures that all largefiles needed by the specified revision
464 are present in the repository's largefile cache.
465
466 returns a tuple (cached, missing). cached is the list of files downloaded
467 by this operation; missing is the list of files that were needed but could
468 not be found."""
469 lfiles = lfutil.listlfiles(repo, node)
470 if filelist:
471 lfiles = set(lfiles) & set(filelist)
472 toget = []
473
474 ctx = repo[node]
475 for lfile in lfiles:
476 try:
477 expectedhash = lfutil.readasstandin(ctx[lfutil.standin(lfile)])
478 except FileNotFoundError:
479 continue # node must be None and standin wasn't found in wctx
480 if not lfutil.findfile(repo, expectedhash):
481 toget.append((lfile, expectedhash))
482
483 if toget:
484 store = storefactory.openstore(repo)
485 ret = store.get(toget)
486 return ret
487
488 return ([], [])
489
490
491 def downloadlfiles(ui, repo):
492 tonode = repo.changelog.node
493 totalsuccess = 0
494 totalmissing = 0
495 for rev in repo.revs(b'file(%s)', b'path:' + lfutil.shortname):
496 success, missing = cachelfiles(ui, repo, tonode(rev))
497 totalsuccess += len(success)
498 totalmissing += len(missing)
499 ui.status(_(b"%d additional largefiles cached\n") % totalsuccess)
500 if totalmissing > 0:
501 ui.status(_(b"%d largefiles failed to download\n") % totalmissing)
502 return totalsuccess, totalmissing
503
504
505 def updatelfiles(
506 ui, repo, filelist=None, printmessage=None, normallookup=False
507 ):
508 """Update largefiles according to standins in the working directory
509
510 If ``printmessage`` is other than ``None``, it means "print (or
511 ignore, for false) message forcibly".
512 """
513 statuswriter = lfutil.getstatuswriter(ui, repo, printmessage)
514 with repo.wlock():
515 lfdirstate = lfutil.openlfdirstate(ui, repo)
516 lfiles = set(lfutil.listlfiles(repo)) | set(lfdirstate)
517
518 if filelist is not None:
519 filelist = set(filelist)
520 lfiles = [f for f in lfiles if f in filelist]
521
522 update = {}
523 dropped = set()
524 updated, removed = 0, 0
525 wvfs = repo.wvfs
526 wctx = repo[None]
527 for lfile in lfiles:
528 lfileorig = os.path.relpath(
529 scmutil.backuppath(ui, repo, lfile), start=repo.root
530 )
531 standin = lfutil.standin(lfile)
532 standinorig = os.path.relpath(
533 scmutil.backuppath(ui, repo, standin), start=repo.root
534 )
535 if wvfs.exists(standin):
536 if wvfs.exists(standinorig) and wvfs.exists(lfile):
537 shutil.copyfile(wvfs.join(lfile), wvfs.join(lfileorig))
538 wvfs.unlinkpath(standinorig)
539 expecthash = lfutil.readasstandin(wctx[standin])
540 if expecthash != b'':
541 if lfile not in wctx: # not switched to normal file
542 if repo.dirstate.get_entry(standin).any_tracked:
543 wvfs.unlinkpath(lfile, ignoremissing=True)
544 else:
545 dropped.add(lfile)
546
547 # allocate an entry in largefiles dirstate to prevent
548 # lfilesrepo.status() from reporting missing files as
549 # removed.
550 lfdirstate.hacky_extension_update_file(
551 lfile,
552 p1_tracked=True,
553 wc_tracked=True,
554 possibly_dirty=True,
555 )
556 update[lfile] = expecthash
557 else:
558 # Remove lfiles for which the standin is deleted, unless the
559 # lfile is added to the repository again. This happens when a
560 # largefile is converted back to a normal file: the standin
561 # disappears, but a new (normal) file appears as the lfile.
562 if (
563 wvfs.exists(lfile)
564 and repo.dirstate.normalize(lfile) not in wctx
565 ):
566 wvfs.unlinkpath(lfile)
567 removed += 1
568
569 # largefile processing might be slow and be interrupted - be prepared
570 lfdirstate.write(repo.currenttransaction())
571
572 if lfiles:
573 lfiles = [f for f in lfiles if f not in dropped]
574
575 for f in dropped:
576 repo.wvfs.unlinkpath(lfutil.standin(f))
577 # This needs to happen for dropped files, otherwise they stay in
578 # the M state.
579 lfdirstate._map.reset_state(f)
580
581 statuswriter(_(b'getting changed largefiles\n'))
582 cachelfiles(ui, repo, None, lfiles)
583
584 for lfile in lfiles:
585 update1 = 0
586
587 expecthash = update.get(lfile)
588 if expecthash:
589 if not lfutil.copyfromcache(repo, expecthash, lfile):
590 # failed ... but already removed and set to normallookup
591 continue
592 # Synchronize largefile dirstate to the last modified
593 # time of the file
594 lfdirstate.hacky_extension_update_file(
595 lfile,
596 p1_tracked=True,
597 wc_tracked=True,
598 )
599 update1 = 1
600
601 # copy the exec mode of largefile standin from the repository's
602 # dirstate to its state in the lfdirstate.
603 standin = lfutil.standin(lfile)
604 if wvfs.exists(standin):
605 # exec is decided by the users permissions using mask 0o100
606 standinexec = wvfs.stat(standin).st_mode & 0o100
607 st = wvfs.stat(lfile)
608 mode = st.st_mode
609 if standinexec != mode & 0o100:
610 # first remove all X bits, then shift all R bits to X
611 mode &= ~0o111
612 if standinexec:
613 mode |= (mode >> 2) & 0o111 & ~util.umask
614 wvfs.chmod(lfile, mode)
615 update1 = 1
616
617 updated += update1
618
619 lfutil.synclfdirstate(repo, lfdirstate, lfile, normallookup)
620
621 lfdirstate.write(repo.currenttransaction())
622 if lfiles:
623 statuswriter(
624 _(b'%d largefiles updated, %d removed\n') % (updated, removed)
625 )
626
627
628 @eh.command(
629 b'lfpull',
630 [(b'r', b'rev', [], _(b'pull largefiles for these revisions'))]
631 + cmdutil.remoteopts,
632 _(b'-r REV... [-e CMD] [--remotecmd CMD] [SOURCE]'),
633 )
634 def lfpull(ui, repo, source=b"default", **opts):
635 """pull largefiles for the specified revisions from the specified source
636
637 Pull largefiles that are referenced from local changesets but missing
638 locally, pulling from a remote repository to the local cache.
639
640 If SOURCE is omitted, the 'default' path will be used.
641 See :hg:`help urls` for more information.
642
643 .. container:: verbose
644
645 Some examples:
646
647 - pull largefiles for all branch heads::
648
649 hg lfpull -r "head() and not closed()"
650
651 - pull largefiles on the default branch::
652
653 hg lfpull -r "branch(default)"
654 """
655 repo.lfpullsource = source
656
657 revs = opts.get('rev', [])
658 if not revs:
659 raise error.Abort(_(b'no revisions specified'))
660 revs = logcmdutil.revrange(repo, revs)
661
662 numcached = 0
663 for rev in revs:
664 ui.note(_(b'pulling largefiles for revision %d\n') % rev)
665 (cached, missing) = cachelfiles(ui, repo, rev)
666 numcached += len(cached)
667 ui.status(_(b"%d largefiles cached\n") % numcached)
668
669
670 @eh.command(b'debuglfput', [] + cmdutil.remoteopts, _(b'FILE'))
671 def debuglfput(ui, repo, filepath, **kwargs):
672 hash = lfutil.hashfile(filepath)
673 storefactory.openstore(repo).put(filepath, hash)
674 ui.write(b'%s\n' % hash)
675 return 0