Debian Codegraph @

hgext/remotefilelog/__init__.py

raw
1 # __init__.py - remotefilelog extension
2 #
3 # Copyright 2013 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 """remotefilelog causes Mercurial to lazilly fetch file contents (EXPERIMENTAL)
8
9 This extension is HIGHLY EXPERIMENTAL. There are NO BACKWARDS COMPATIBILITY
10 GUARANTEES. This means that repositories created with this extension may
11 only be usable with the exact version of this extension/Mercurial that was
12 used. The extension attempts to enforce this in order to prevent repository
13 corruption.
14
15 remotefilelog works by fetching file contents lazily and storing them
16 in a cache on the client rather than in revlogs. This allows enormous
17 histories to be transferred only partially, making them easier to
18 operate on.
19
20 Configs:
21
22 ``packs.maxchainlen`` specifies the maximum delta chain length in pack files
23
24 ``packs.maxpacksize`` specifies the maximum pack file size
25
26 ``packs.maxpackfilecount`` specifies the maximum number of packs in the
27 shared cache (trees only for now)
28
29 ``remotefilelog.backgroundprefetch`` runs prefetch in background when True
30
31 ``remotefilelog.bgprefetchrevs`` specifies revisions to fetch on commit and
32 update, and on other commands that use them. Different from pullprefetch.
33
34 ``remotefilelog.gcrepack`` does garbage collection during repack when True
35
36 ``remotefilelog.nodettl`` specifies maximum TTL of a node in seconds before
37 it is garbage collected
38
39 ``remotefilelog.repackonhggc`` runs repack on hg gc when True
40
41 ``remotefilelog.prefetchdays`` specifies the maximum age of a commit in
42 days after which it is no longer prefetched.
43
44 ``remotefilelog.prefetchdelay`` specifies delay between background
45 prefetches in seconds after operations that change the working copy parent
46
47 ``remotefilelog.data.gencountlimit`` constraints the minimum number of data
48 pack files required to be considered part of a generation. In particular,
49 minimum number of packs files > gencountlimit.
50
51 ``remotefilelog.data.generations`` list for specifying the lower bound of
52 each generation of the data pack files. For example, list ['100MB','1MB']
53 or ['1MB', '100MB'] will lead to three generations: [0, 1MB), [
54 1MB, 100MB) and [100MB, infinity).
55
56 ``remotefilelog.data.maxrepackpacks`` the maximum number of pack files to
57 include in an incremental data repack.
58
59 ``remotefilelog.data.repackmaxpacksize`` the maximum size of a pack file for
60 it to be considered for an incremental data repack.
61
62 ``remotefilelog.data.repacksizelimit`` the maximum total size of pack files
63 to include in an incremental data repack.
64
65 ``remotefilelog.history.gencountlimit`` constraints the minimum number of
66 history pack files required to be considered part of a generation. In
67 particular, minimum number of packs files > gencountlimit.
68
69 ``remotefilelog.history.generations`` list for specifying the lower bound of
70 each generation of the history pack files. For example, list [
71 '100MB', '1MB'] or ['1MB', '100MB'] will lead to three generations: [
72 0, 1MB), [1MB, 100MB) and [100MB, infinity).
73
74 ``remotefilelog.history.maxrepackpacks`` the maximum number of pack files to
75 include in an incremental history repack.
76
77 ``remotefilelog.history.repackmaxpacksize`` the maximum size of a pack file
78 for it to be considered for an incremental history repack.
79
80 ``remotefilelog.history.repacksizelimit`` the maximum total size of pack
81 files to include in an incremental history repack.
82
83 ``remotefilelog.backgroundrepack`` automatically consolidate packs in the
84 background
85
86 ``remotefilelog.cachepath`` path to cache
87
88 ``remotefilelog.cachegroup`` if set, make cache directory sgid to this
89 group
90
91 ``remotefilelog.cacheprocess`` binary to invoke for fetching file data
92
93 ``remotefilelog.debug`` turn on remotefilelog-specific debug output
94
95 ``remotefilelog.excludepattern`` pattern of files to exclude from pulls
96
97 ``remotefilelog.includepattern`` pattern of files to include in pulls
98
99 ``remotefilelog.fetchwarning``: message to print when too many
100 single-file fetches occur
101
102 ``remotefilelog.getfilesstep`` number of files to request in a single RPC
103
104 ``remotefilelog.getfilestype`` if set to 'threaded' use threads to fetch
105 files, otherwise use optimistic fetching
106
107 ``remotefilelog.pullprefetch`` revset for selecting files that should be
108 eagerly downloaded rather than lazily
109
110 ``remotefilelog.reponame`` name of the repo. If set, used to partition
111 data from other repos in a shared store.
112
113 ``remotefilelog.server`` if true, enable server-side functionality
114
115 ``remotefilelog.servercachepath`` path for caching blobs on the server
116
117 ``remotefilelog.serverexpiration`` number of days to keep cached server
118 blobs
119
120 ``remotefilelog.validatecache`` if set, check cache entries for corruption
121 before returning blobs
122
123 ``remotefilelog.validatecachelog`` if set, check cache entries for
124 corruption before returning metadata
125
126 """
127
128 from __future__ import annotations
129
130 import os
131 import time
132 import traceback
133
134 from mercurial.node import (
135 hex,
136 wdirrev,
137 )
138 from mercurial.i18n import _
139 from mercurial import (
140 changegroup,
141 changelog,
142 commands,
143 configitems,
144 context,
145 copies,
146 debugcommands as hgdebugcommands,
147 dispatch,
148 error,
149 exchange,
150 extensions,
151 hg,
152 localrepo,
153 match as matchmod,
154 merge,
155 mergestate as mergestatemod,
156 patch,
157 pycompat,
158 registrar,
159 repair,
160 repoview,
161 revset,
162 revset_predicates,
163 scmutil,
164 smartset,
165 streamclone,
166 util,
167 )
168 from mercurial.merge_utils import (
169 update as update_util,
170 )
171 from mercurial.repo import (
172 factory as repo_factory,
173 )
174 from . import (
175 constants,
176 debugcommands,
177 fileserverclient,
178 remotefilectx,
179 remotefilelog,
180 remotefilelogserver,
181 repack as repackmod,
182 shallowbundle,
183 shallowrepo,
184 shallowstore,
185 shallowutil,
186 shallowverifier,
187 )
188
189
190 # ensures debug commands are registered
191 hgdebugcommands.command
192
193 cmdtable = {}
194 command = registrar.command(cmdtable)
195
196 configtable = {}
197 configitem = registrar.configitem(configtable)
198
199 configitem(b'remotefilelog', b'debug', default=False)
200
201 configitem(b'remotefilelog', b'reponame', default=b'')
202 configitem(b'remotefilelog', b'cachepath', default=None)
203 configitem(b'remotefilelog', b'cachegroup', default=None)
204 configitem(b'remotefilelog', b'cacheprocess', default=None)
205 configitem(b'remotefilelog', b'cacheprocess.includepath', default=None)
206 configitem(b"remotefilelog", b"cachelimit", default=b"1000 GB")
207
208 configitem(
209 b'remotefilelog',
210 b'fallbackpath',
211 default=configitems.dynamicdefault,
212 alias=[(b'remotefilelog', b'fallbackrepo')],
213 )
214
215 configitem(b'remotefilelog', b'validatecachelog', default=None)
216 configitem(b'remotefilelog', b'validatecache', default=b'on')
217 configitem(b'remotefilelog', b'server', default=None)
218 configitem(b'remotefilelog', b'servercachepath', default=None)
219 configitem(b"remotefilelog", b"serverexpiration", default=30)
220 configitem(b'remotefilelog', b'backgroundrepack', default=False)
221 configitem(b'remotefilelog', b'bgprefetchrevs', default=None)
222 configitem(b'remotefilelog', b'pullprefetch', default=None)
223 configitem(b'remotefilelog', b'backgroundprefetch', default=False)
224 configitem(b'remotefilelog', b'prefetchdelay', default=120)
225 configitem(b'remotefilelog', b'prefetchdays', default=14)
226 # Other values include 'local' or 'none'. Any unrecognized value is 'all'.
227 configitem(b'remotefilelog', b'strip.includefiles', default='all')
228
229 configitem(b'remotefilelog', b'getfilesstep', default=10000)
230 configitem(b'remotefilelog', b'getfilestype', default=b'optimistic')
231 configitem(b'remotefilelog', b'batchsize', configitems.dynamicdefault)
232 configitem(b'remotefilelog', b'fetchwarning', default=b'')
233
234 configitem(b'remotefilelog', b'includepattern', default=None)
235 configitem(b'remotefilelog', b'excludepattern', default=None)
236
237 configitem(b'remotefilelog', b'gcrepack', default=False)
238 configitem(b'remotefilelog', b'repackonhggc', default=False)
239 configitem(b'repack', b'chainorphansbysize', default=True, experimental=True)
240
241 configitem(b'packs', b'maxpacksize', default=0)
242 configitem(b'packs', b'maxchainlen', default=1000)
243
244 configitem(b'devel', b'remotefilelog.bg-wait', default=False)
245
246 # default TTL limit is 30 days
247 _defaultlimit = 60 * 60 * 24 * 30
248 configitem(b'remotefilelog', b'nodettl', default=_defaultlimit)
249
250 configitem(b'remotefilelog', b'data.gencountlimit', default=2),
251 configitem(
252 b'remotefilelog', b'data.generations', default=[b'1GB', b'100MB', b'1MB']
253 )
254 configitem(b'remotefilelog', b'data.maxrepackpacks', default=50)
255 configitem(b'remotefilelog', b'data.repackmaxpacksize', default=b'4GB')
256 configitem(b'remotefilelog', b'data.repacksizelimit', default=b'100MB')
257
258 configitem(b'remotefilelog', b'history.gencountlimit', default=2),
259 configitem(b'remotefilelog', b'history.generations', default=[b'100MB'])
260 configitem(b'remotefilelog', b'history.maxrepackpacks', default=50)
261 configitem(b'remotefilelog', b'history.repackmaxpacksize', default=b'400MB')
262 configitem(b'remotefilelog', b'history.repacksizelimit', default=b'100MB')
263
264 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
265 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
266 # be specifying the version(s) of Mercurial they are tested with, or
267 # leave the attribute unspecified.
268 testedwith = b'ships-with-hg-core'
269
270 repoclass = localrepo.localrepository
271 repoclass._basesupported.add(constants.SHALLOWREPO_REQUIREMENT)
272
273 isenabled = shallowutil.isenabled
274
275
276 def uisetup(ui):
277 """Wraps user facing Mercurial commands to swap them out with shallow
278 versions.
279 """
280 hg.wirepeersetupfuncs.append(fileserverclient.peersetup)
281
282 entry = extensions.wrapcommand(commands.table, b'clone', cloneshallow)
283 entry[1].append(
284 (
285 b'',
286 b'shallow',
287 None,
288 _(b"create a shallow clone which uses remote file history"),
289 )
290 )
291
292 extensions.wrapcommand(
293 commands.table, b'debugindex', debugcommands.debugindex
294 )
295 extensions.wrapcommand(
296 commands.table, b'debugindexdot', debugcommands.debugindexdot
297 )
298 extensions.wrapcommand(commands.table, b'log', log)
299 extensions.wrapcommand(commands.table, b'pull', pull)
300
301 # Prevent 'hg manifest --all'
302 def _manifest(orig, ui, repo, *args, **opts):
303 if isenabled(repo) and opts.get('all'):
304 raise error.Abort(_(b"--all is not supported in a shallow repo"))
305
306 return orig(ui, repo, *args, **opts)
307
308 extensions.wrapcommand(commands.table, b"manifest", _manifest)
309
310 # Wrap remotefilelog with lfs code
311 def _lfsloaded(loaded=False):
312 lfsmod = None
313 try:
314 lfsmod = extensions.find(b'lfs')
315 except KeyError:
316 pass
317 if lfsmod:
318 lfsmod.wrapfilelog(remotefilelog.remotefilelog)
319 fileserverclient._lfsmod = lfsmod
320
321 extensions.afterloaded(b'lfs', _lfsloaded)
322
323 # debugdata needs remotefilelog.len to work
324 extensions.wrapcommand(commands.table, b'debugdata', debugdatashallow)
325
326 extensions.wrapfunction(
327 changegroup, '_addchangegroupfiles', shallowbundle.addchangegroupfiles
328 )
329 extensions.wrapfunction(
330 changegroup, 'makechangegroup', shallowbundle.makechangegroup
331 )
332 extensions.wrapfunction(
333 changegroup, 'getbundler', shallowbundle.wrap_bundler
334 )
335 extensions.wrapfunction(localrepo, 'makestore', storewrapper)
336 extensions.wrapfunction(exchange, 'pull', exchangepull)
337 extensions.wrapfunction(update_util, 'apply_updates', apply_updates)
338 extensions.wrapfunction(merge, '_checkunknownfiles', checkunknownfiles)
339 extensions.wrapfunction(context.workingctx, '_checklookup', checklookup)
340 extensions.wrapfunction(scmutil, '_findrenames', findrenames)
341 extensions.wrapfunction(
342 copies, '_computeforwardmissing', computeforwardmissing
343 )
344 extensions.wrapfunction(dispatch, 'runcommand', runcommand)
345 extensions.wrapfunction(repair, '_collectbrokencsets', _collectbrokencsets)
346 extensions.wrapfunction(context.changectx, 'filectx', filectx)
347 extensions.wrapfunction(context.workingctx, 'filectx', workingfilectx)
348 extensions.wrapfunction(patch, 'trydiff', trydiff)
349 extensions.wrapfunction(hg, 'verify', _verify)
350 scmutil.fileprefetchhooks.add(b'remotefilelog', _fileprefetchhook)
351
352 # disappointing hacks below
353 extensions.wrapfunction(scmutil, 'getrenamedfn', getrenamedfn)
354 extensions.wrapfunction(revset_predicates, 'filelog', filelogrevset)
355 revset.symbols[b'filelog'] = revset_predicates.filelog
356
357
358 def cloneshallow(orig, ui, repo, *args, **opts):
359 if opts.get('shallow'):
360 repos = []
361
362 def pull_shallow(orig, self, *args, **kwargs):
363 if not isenabled(self):
364 repos.append(self.unfiltered())
365 # set up the client hooks so the post-clone update works
366 setupclient(self.ui, self.unfiltered())
367
368 # setupclient fixed the class on the repo itself
369 # but we also need to fix it on the repoview
370 if isinstance(self, repoview.repoview):
371 self.__class__.__bases__ = (
372 self.__class__.__bases__[0],
373 self.unfiltered().__class__,
374 )
375 self.requirements.add(constants.SHALLOWREPO_REQUIREMENT)
376 with self.lock():
377 # acquire store lock before writing requirements as some
378 # requirements might be written to .hg/store/requires
379 scmutil.writereporequirements(self)
380
381 # Since setupclient hadn't been called, exchange.pull was not
382 # wrapped. So we need to manually invoke our version of it.
383 return exchangepull(orig, self, *args, **kwargs)
384 else:
385 return orig(self, *args, **kwargs)
386
387 extensions.wrapfunction(exchange, 'pull', pull_shallow)
388
389 # Wrap the stream logic to add requirements and to pass include/exclude
390 # patterns around.
391 def setup_streamout(repo, remote):
392 # Replace remote.stream_out with a version that sends file
393 # patterns.
394 def stream_out_shallow(orig):
395 caps = remote.capabilities()
396 if constants.NETWORK_CAP_LEGACY_SSH_GETFILES in caps:
397 opts = {}
398 if repo.includepattern:
399 opts['includepattern'] = b'\0'.join(repo.includepattern)
400 if repo.excludepattern:
401 opts['excludepattern'] = b'\0'.join(repo.excludepattern)
402 return remote._callstream(b'stream_out_shallow', **opts)
403 else:
404 return orig()
405
406 extensions.wrapfunction(remote, 'stream_out', stream_out_shallow)
407
408 def stream_wrap(orig, op):
409 setup_streamout(op.repo, op.remote)
410 return orig(op)
411
412 extensions.wrapfunction(
413 streamclone, 'maybeperformlegacystreamclone', stream_wrap
414 )
415
416 def canperformstreamclone(orig, pullop, bundle2=False):
417 # remotefilelog is currently incompatible with the
418 # bundle2 flavor of streamclones, so force us to use
419 # v1 instead.
420 if b'v2' in pullop.remotebundle2caps.get(b'stream', []):
421 pullop.remotebundle2caps[b'stream'] = []
422 if bundle2:
423 return False, None
424 supported, requirements = orig(pullop, bundle2=bundle2)
425 if requirements is not None:
426 requirements.add(constants.SHALLOWREPO_REQUIREMENT)
427 return supported, requirements
428
429 extensions.wrapfunction(
430 streamclone, 'canperformstreamclone', canperformstreamclone
431 )
432
433 try:
434 orig(ui, repo, *args, **opts)
435 finally:
436 if opts.get('shallow'):
437 for r in repos:
438 if hasattr(r, 'fileservice'):
439 r.fileservice.close()
440
441
442 def debugdatashallow(orig, *args, **kwds):
443 oldlen = remotefilelog.remotefilelog.__len__
444 try:
445 remotefilelog.remotefilelog.__len__ = lambda x: 1
446 return orig(*args, **kwds)
447 finally:
448 remotefilelog.remotefilelog.__len__ = oldlen
449
450
451 def reposetup(ui, repo):
452 if not repo.local():
453 return
454
455 # put here intentionally bc doesnt work in uisetup
456 ui.setconfig(b'hooks', b'update.prefetch', wcpprefetch)
457 ui.setconfig(b'hooks', b'commit.prefetch', wcpprefetch)
458
459 isserverenabled = ui.configbool(b'remotefilelog', b'server')
460 isshallowclient = isenabled(repo)
461
462 if isserverenabled and isshallowclient:
463 raise RuntimeError(b"Cannot be both a server and shallow client.")
464
465 if isshallowclient:
466 setupclient(ui, repo)
467
468 if isserverenabled:
469 remotefilelogserver.setupserver(ui, repo)
470
471
472 def setupclient(ui, repo):
473 if not isinstance(repo, localrepo.localrepository):
474 return
475
476 # Even clients get the server setup since they need to have the
477 # wireprotocol endpoints registered.
478 remotefilelogserver.onetimesetup(ui)
479 onetimeclientsetup(ui)
480
481 shallowrepo.wraprepo(repo)
482 repo.store = shallowstore.wrapstore(repo.store)
483
484
485 def storewrapper(orig, ui, requirements, path, vfstype, try_pending):
486 s = orig(ui, requirements, path, vfstype, try_pending)
487 if constants.SHALLOWREPO_REQUIREMENT in requirements:
488 s = shallowstore.wrapstore(s)
489
490 return s
491
492
493 # prefetch files before update
494 def apply_updates(
495 orig, repo, mresult, wctx, mctx, overwrite, wantfiledata, **opts
496 ):
497 if isenabled(repo):
498 manifest = mctx.manifest()
499 files = []
500 for f, args, msg in mresult.getactions([mergestatemod.ACTION_GET]):
501 files.append((f, hex(manifest[f])))
502 # batch fetch the needed files from the server
503 repo.fileservice.prefetch(files)
504 return orig(repo, mresult, wctx, mctx, overwrite, wantfiledata, **opts)
505
506
507 # Prefetch merge checkunknownfiles
508 def checkunknownfiles(orig, repo, wctx, mctx, force, mresult, *args, **kwargs):
509 if isenabled(repo):
510 files = []
511 sparsematch = repo.maybesparsematch(mctx.rev())
512 for f, (m, actionargs, msg) in mresult.filemap():
513 if sparsematch and not sparsematch(f):
514 continue
515 if m in (
516 mergestatemod.ACTION_CREATED,
517 mergestatemod.ACTION_DELETED_CHANGED,
518 mergestatemod.ACTION_CREATED_MERGE,
519 ):
520 files.append((f, hex(mctx.filenode(f))))
521 elif m == mergestatemod.ACTION_LOCAL_DIR_RENAME_GET:
522 f2 = actionargs[0]
523 files.append((f2, hex(mctx.filenode(f2))))
524 # batch fetch the needed files from the server
525 repo.fileservice.prefetch(files)
526 return orig(repo, wctx, mctx, force, mresult, *args, **kwargs)
527
528
529 # Prefetch files before status attempts to look at their size and contents
530 def checklookup(orig, self, files, mtime_boundary):
531 repo = self._repo
532 if isenabled(repo):
533 prefetchfiles = []
534 for parent in self._parents:
535 for f in files:
536 if f in parent:
537 prefetchfiles.append((f, hex(parent.filenode(f))))
538 # batch fetch the needed files from the server
539 repo.fileservice.prefetch(prefetchfiles)
540 return orig(self, files, mtime_boundary)
541
542
543 # Prefetch the logic that compares added and removed files for renames
544 def findrenames(orig, repo, matcher, added, removed, *args, **kwargs):
545 if isenabled(repo):
546 files = []
547 pmf = repo[b'.'].manifest()
548 for f in removed:
549 if f in pmf:
550 files.append((f, hex(pmf[f])))
551 # batch fetch the needed files from the server
552 repo.fileservice.prefetch(files)
553 return orig(repo, matcher, added, removed, *args, **kwargs)
554
555
556 # prefetch files before pathcopies check
557 def computeforwardmissing(orig, a, b, match=None):
558 missing = orig(a, b, match=match)
559 repo = a._repo
560 if isenabled(repo):
561 mb = b.manifest()
562
563 files = []
564 sparsematch = repo.maybesparsematch(b.rev())
565 if sparsematch:
566 sparsemissing = set()
567 for f in missing:
568 if sparsematch(f):
569 files.append((f, hex(mb[f])))
570 sparsemissing.add(f)
571 missing = sparsemissing
572
573 # batch fetch the needed files from the server
574 repo.fileservice.prefetch(files)
575 return missing
576
577
578 # close cache miss server connection after the command has finished
579 def runcommand(orig, lui, repo, *args, **kwargs):
580 fileservice = None
581 # repo can be None when running in chg:
582 # - at startup, reposetup was called because serve is not norepo
583 # - a norepo command like "help" is called
584 if repo and isenabled(repo):
585 fileservice = repo.fileservice
586 try:
587 return orig(lui, repo, *args, **kwargs)
588 finally:
589 if fileservice:
590 fileservice.close()
591
592
593 # prevent strip from stripping remotefilelogs
594 def _collectbrokencsets(orig, repo, files, striprev):
595 if isenabled(repo):
596 files = [f for f in files if not repo.shallowmatch(f)]
597 return orig(repo, files, striprev)
598
599
600 # changectx wrappers
601 def filectx(orig, self, path, fileid=None, filelog=None):
602 if fileid is None:
603 fileid = self.filenode(path)
604 if isenabled(self._repo) and self._repo.shallowmatch(path):
605 return remotefilectx.remotefilectx(
606 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
607 )
608 return orig(self, path, fileid=fileid, filelog=filelog)
609
610
611 def workingfilectx(orig, self, path, filelog=None):
612 if isenabled(self._repo) and self._repo.shallowmatch(path):
613 return remotefilectx.remoteworkingfilectx(
614 self._repo, path, workingctx=self, filelog=filelog
615 )
616 return orig(self, path, filelog=filelog)
617
618
619 # prefetch required revisions before a diff
620 def trydiff(
621 orig,
622 repo,
623 revs,
624 ctx1,
625 ctx2,
626 modified,
627 added,
628 removed,
629 copy,
630 getfilectx,
631 *args,
632 **kwargs,
633 ):
634 if isenabled(repo):
635 prefetch = []
636 mf1 = ctx1.manifest()
637 for fname in modified + added + removed:
638 if fname in mf1:
639 fnode = getfilectx(fname, ctx1).filenode()
640 # fnode can be None if it's a edited working ctx file
641 if fnode:
642 prefetch.append((fname, hex(fnode)))
643 if fname not in removed:
644 fnode = getfilectx(fname, ctx2).filenode()
645 if fnode:
646 prefetch.append((fname, hex(fnode)))
647
648 repo.fileservice.prefetch(prefetch)
649
650 return orig(
651 repo,
652 revs,
653 ctx1,
654 ctx2,
655 modified,
656 added,
657 removed,
658 copy,
659 getfilectx,
660 *args,
661 **kwargs,
662 )
663
664
665 # Prevent verify from processing files
666 # a stub for mercurial.hg.verify()
667 def _verify(orig, repo, level=None):
668 lock = repo.lock()
669 try:
670 return shallowverifier.shallowverifier(repo).verify()
671 finally:
672 lock.release()
673
674
675 clientonetime = False
676
677
678 def onetimeclientsetup(ui):
679 global clientonetime
680 if clientonetime:
681 return
682 clientonetime = True
683
684 # Don't commit filelogs until we know the commit hash, since the hash
685 # is present in the filelog blob.
686 # This violates Mercurial's filelog->manifest->changelog write order,
687 # but is generally fine for client repos.
688 pendingfilecommits = []
689
690 def addrawrevision(
691 orig,
692 self,
693 rawtext,
694 transaction,
695 link,
696 p1,
697 p2,
698 node,
699 flags,
700 cachedelta=None,
701 _metatuple=None,
702 ):
703 if isinstance(link, int):
704 pendingfilecommits.append(
705 (
706 self,
707 rawtext,
708 transaction,
709 link,
710 p1,
711 p2,
712 node,
713 flags,
714 cachedelta,
715 _metatuple,
716 )
717 )
718 return node
719 else:
720 return orig(
721 self,
722 rawtext,
723 transaction,
724 link,
725 p1,
726 p2,
727 node,
728 flags,
729 cachedelta,
730 _metatuple=_metatuple,
731 )
732
733 extensions.wrapfunction(
734 remotefilelog.remotefilelog, 'addrawrevision', addrawrevision
735 )
736
737 def changelogadd(orig, self, *args, **kwargs):
738 oldlen = len(self)
739 node = orig(self, *args, **kwargs)
740 newlen = len(self)
741 if oldlen != newlen:
742 for oldargs in pendingfilecommits:
743 log, rt, tr, link, p1, p2, n, fl, c, m = oldargs
744 linknode = self.node(link)
745 if linknode == node:
746 log.addrawrevision(rt, tr, linknode, p1, p2, n, fl, c, m)
747 else:
748 raise error.ProgrammingError(
749 b'pending multiple integer revisions are not supported'
750 )
751 else:
752 # "link" is actually wrong here (it is set to len(changelog))
753 # if changelog remains unchanged, skip writing file revisions
754 # but still do a sanity check about pending multiple revisions
755 if len({x[3] for x in pendingfilecommits}) > 1:
756 raise error.ProgrammingError(
757 b'pending multiple integer revisions are not supported'
758 )
759 del pendingfilecommits[:]
760 return node
761
762 extensions.wrapfunction(changelog.changelog, 'add', changelogadd)
763
764
765 def getrenamedfn(orig, repo, endrev=None):
766 if not isenabled(repo) or copies.usechangesetcentricalgo(repo):
767 return orig(repo, endrev)
768
769 rcache = {}
770
771 def getrenamed(fn, rev):
772 """looks up all renames for a file (up to endrev) the first
773 time the file is given. It indexes on the changerev and only
774 parses the manifest if linkrev != changerev.
775 Returns rename info for fn at changerev rev."""
776 if rev in rcache.setdefault(fn, {}):
777 return rcache[fn][rev]
778
779 try:
780 fctx = repo[rev].filectx(fn)
781 for ancestor in fctx.ancestors():
782 if ancestor.path() == fn:
783 renamed = ancestor.renamed()
784 rcache[fn][ancestor.rev()] = renamed and renamed[0]
785
786 renamed = fctx.renamed()
787 return renamed and renamed[0]
788 except error.LookupError:
789 return None
790
791 return getrenamed
792
793
794 def filelogrevset(orig, repo, subset, x):
795 """``filelog(pattern)``
796 Changesets connected to the specified filelog.
797
798 For performance reasons, ``filelog()`` does not show every changeset
799 that affects the requested file(s). See :hg:`help log` for details. For
800 a slower, more accurate result, use ``file()``.
801 """
802
803 if not isenabled(repo):
804 return orig(repo, subset, x)
805
806 # i18n: "filelog" is a keyword
807 pat = revset.getstring(x, _(b"filelog requires a pattern"))
808 m = matchmod.match(
809 repo.root, repo.getcwd(), [pat], default=b'relpath', ctx=repo[None]
810 )
811 s = set()
812
813 if not matchmod.patkind(pat):
814 # slow
815 for r in subset:
816 ctx = repo[r]
817 cfiles = ctx.files()
818 for f in m.files():
819 if f in cfiles:
820 s.add(ctx.rev())
821 break
822 else:
823 # partial
824 files = (f for f in repo[None] if m(f))
825 for f in files:
826 fctx = repo[None].filectx(f)
827 s.add(fctx.linkrev())
828 for actx in fctx.ancestors():
829 s.add(actx.linkrev())
830
831 return smartset.baseset([r for r in subset if r in s])
832
833
834 @command(b'gc', [], _(b'hg gc [REPO...]'), norepo=True)
835 def gc(ui, *args, **opts):
836 """garbage collect the client and server filelog caches"""
837 cachepaths = set()
838
839 # get the system client cache
840 systemcache = shallowutil.getcachepath(ui, allowempty=True)
841 if systemcache:
842 cachepaths.add(systemcache)
843
844 # get repo client and server cache
845 repopaths = []
846 pwd = ui.environ.get(b'PWD')
847 if pwd:
848 repopaths.append(pwd)
849
850 repopaths.extend(args)
851 repos = []
852 for repopath in repopaths:
853 try:
854 repo = repo_factory.peer(ui, {}, repopath)
855 repos.append(repo)
856
857 repocache = shallowutil.getcachepath(repo.ui, allowempty=True)
858 if repocache:
859 cachepaths.add(repocache)
860 except error.RepoError:
861 pass
862
863 # gc client cache
864 for cachepath in cachepaths:
865 gcclient(ui, cachepath)
866
867 # gc server cache
868 for repo in repos:
869 remotefilelogserver.gcserver(ui, repo._repo)
870
871
872 def gcclient(ui, cachepath):
873 # get list of repos that use this cache
874 repospath = os.path.join(cachepath, b'repos')
875 if not os.path.exists(repospath):
876 ui.warn(_(b"no known cache at %s\n") % cachepath)
877 return
878
879 with open(repospath, 'rb') as reposfile:
880 repos = {r[:-1] for r in reposfile.readlines()}
881
882 # build list of useful files
883 validrepos = []
884 keepkeys = set()
885
886 sharedcache = None
887 filesrepacked = False
888
889 count = 0
890 progress = ui.makeprogress(
891 _(b"analyzing repositories"), unit=b"repos", total=len(repos)
892 )
893 for path in repos:
894 progress.update(count)
895 count += 1
896 try:
897 path = util.expandpath(os.path.normpath(path))
898 except TypeError as e:
899 ui.warn(_(b"warning: malformed path: %r:%s\n") % (path, e))
900 traceback.print_exc()
901 continue
902 try:
903 peer = repo_factory.peer(ui, {}, path)
904 repo = peer._repo
905 except error.RepoError:
906 continue
907
908 validrepos.append(path)
909
910 # Protect against any repo or config changes that have happened since
911 # this repo was added to the repos file. We'd rather this loop succeed
912 # and too much be deleted, than the loop fail and nothing gets deleted.
913 if not isenabled(repo):
914 continue
915
916 if not hasattr(repo, 'name'):
917 ui.warn(
918 _(b"repo %s is a misconfigured remotefilelog repo\n") % path
919 )
920 continue
921
922 # If garbage collection on repack and repack on hg gc are enabled
923 # then loose files are repacked and garbage collected.
924 # Otherwise regular garbage collection is performed.
925 repackonhggc = repo.ui.configbool(b'remotefilelog', b'repackonhggc')
926 gcrepack = repo.ui.configbool(b'remotefilelog', b'gcrepack')
927 if repackonhggc and gcrepack:
928 try:
929 repackmod.incrementalrepack(repo)
930 filesrepacked = True
931 continue
932 except (OSError, repackmod.RepackAlreadyRunning):
933 # If repack cannot be performed due to not enough disk space
934 # continue doing garbage collection of loose files w/o repack
935 pass
936
937 reponame = repo.name
938 if not sharedcache:
939 sharedcache = repo.sharedstore
940
941 # Compute a keepset which is not garbage collected
942 def keyfn(fname, fnode):
943 return fileserverclient.getcachekey(reponame, fname, hex(fnode))
944
945 keepkeys = repackmod.keepset(repo, keyfn=keyfn, lastkeepkeys=keepkeys)
946
947 progress.complete()
948
949 # write list of valid repos back
950 oldumask = os.umask(0o002)
951 try:
952 with open(repospath, 'wb') as reposfile:
953 reposfile.writelines([(b"%s\n" % r) for r in validrepos])
954 finally:
955 os.umask(oldumask)
956
957 # prune cache
958 if sharedcache is not None:
959 sharedcache.gc(keepkeys)
960 elif not filesrepacked:
961 ui.warn(_(b"warning: no valid repos in repofile\n"))
962
963
964 def log(orig, ui, repo, *pats, **opts):
965 if not isenabled(repo):
966 return orig(ui, repo, *pats, **opts)
967
968 follow = opts.get('follow')
969 revs = opts.get('rev')
970 if pats:
971 # Force slowpath for non-follow patterns and follows that start from
972 # non-working-copy-parent revs.
973 if not follow or revs:
974 # This forces the slowpath
975 opts['removed'] = True
976
977 # If this is a non-follow log without any revs specified, recommend that
978 # the user add -f to speed it up.
979 if not follow and not revs:
980 match = scmutil.match(repo[b'.'], pats, pycompat.byteskwargs(opts))
981 isfile = not match.anypats()
982 if isfile:
983 for file in match.files():
984 if not os.path.isfile(repo.wjoin(file)):
985 isfile = False
986 break
987
988 if isfile:
989 ui.warn(
990 _(
991 b"warning: file log can be slow on large repos - "
992 + b"use -f to speed it up\n"
993 )
994 )
995
996 return orig(ui, repo, *pats, **opts)
997
998
999 def revdatelimit(ui, revset):
1000 """Update revset so that only changesets no older than 'prefetchdays' days
1001 are included. The default value is set to 14 days. If 'prefetchdays' is set
1002 to zero or negative value then date restriction is not applied.
1003 """
1004 days = ui.configint(b'remotefilelog', b'prefetchdays')
1005 if days > 0:
1006 revset = b'(%s) & date(-%s)' % (revset, days)
1007 return revset
1008
1009
1010 def readytofetch(repo):
1011 """Check that enough time has passed since the last background prefetch.
1012 This only relates to prefetches after operations that change the working
1013 copy parent. Default delay between background prefetches is 2 minutes.
1014 """
1015 timeout = repo.ui.configint(b'remotefilelog', b'prefetchdelay')
1016 fname = repo.vfs.join(b'lastprefetch')
1017
1018 ready = False
1019 with open(fname, 'a'):
1020 # the with construct above is used to avoid race conditions
1021 modtime = os.path.getmtime(fname)
1022 if (time.time() - modtime) > timeout:
1023 os.utime(fname, None)
1024 ready = True
1025
1026 return ready
1027
1028
1029 def wcpprefetch(ui, repo, **kwargs):
1030 """Prefetches in background revisions specified by bgprefetchrevs revset.
1031 Does background repack if backgroundrepack flag is set in config.
1032 """
1033 shallow = isenabled(repo)
1034 bgprefetchrevs = ui.config(b'remotefilelog', b'bgprefetchrevs')
1035 isready = readytofetch(repo)
1036
1037 if not (shallow and bgprefetchrevs and isready):
1038 return
1039
1040 bgrepack = repo.ui.configbool(b'remotefilelog', b'backgroundrepack')
1041 # update a revset with a date limit
1042 bgprefetchrevs = revdatelimit(ui, bgprefetchrevs)
1043
1044 def anon(unused_success):
1045 if hasattr(repo, 'ranprefetch') and repo.ranprefetch:
1046 return
1047 repo.ranprefetch = True
1048 repo.backgroundprefetch(bgprefetchrevs, repack=bgrepack)
1049
1050 repo._afterlock(anon)
1051
1052
1053 def pull(orig, ui, repo, *pats, **opts):
1054 result = orig(ui, repo, *pats, **opts)
1055
1056 if isenabled(repo):
1057 # prefetch if it's configured
1058 prefetchrevset = ui.config(b'remotefilelog', b'pullprefetch')
1059 bgrepack = repo.ui.configbool(b'remotefilelog', b'backgroundrepack')
1060 bgprefetch = repo.ui.configbool(b'remotefilelog', b'backgroundprefetch')
1061
1062 if prefetchrevset:
1063 ui.status(_(b"prefetching file contents\n"))
1064 revs = scmutil.revrange(repo, [prefetchrevset])
1065 base = repo[b'.'].rev()
1066 if bgprefetch:
1067 repo.backgroundprefetch(prefetchrevset, repack=bgrepack)
1068 else:
1069 repo.prefetch(revs, base=base)
1070 if bgrepack:
1071 repackmod.backgroundrepack(repo, incremental=True)
1072 elif bgrepack:
1073 repackmod.backgroundrepack(repo, incremental=True)
1074
1075 return result
1076
1077
1078 def exchangepull(orig, repo, remote, *args, **kwargs):
1079 # Hook into the callstream/getbundle to insert bundle capabilities
1080 # during a pull.
1081 def localgetbundle(
1082 orig, source, heads=None, common=None, bundlecaps=None, **kwargs
1083 ):
1084 if not bundlecaps:
1085 bundlecaps = set()
1086 bundlecaps.add(constants.BUNDLE2_CAPABLITY)
1087 return orig(
1088 source, heads=heads, common=common, bundlecaps=bundlecaps, **kwargs
1089 )
1090
1091 if hasattr(remote, '_callstream'):
1092 remote._localrepo = repo
1093 elif hasattr(remote, 'getbundle'):
1094 extensions.wrapfunction(remote, 'getbundle', localgetbundle)
1095
1096 return orig(repo, remote, *args, **kwargs)
1097
1098
1099 def _fileprefetchhook(repo, revmatches):
1100 if isenabled(repo):
1101 allfiles = []
1102 for rev, match in revmatches:
1103 if rev == wdirrev or rev is None:
1104 continue
1105 ctx = repo[rev]
1106 mf = ctx.manifest()
1107 sparsematch = repo.maybesparsematch(ctx.rev())
1108 for path in ctx.walk(match):
1109 if (not sparsematch or sparsematch(path)) and path in mf:
1110 allfiles.append((path, hex(mf[path])))
1111 repo.fileservice.prefetch(allfiles)
1112
1113
1114 @command(
1115 b'debugremotefilelog',
1116 [
1117 (b'd', b'decompress', None, _(b'decompress the filelog first')),
1118 ],
1119 _(b'hg debugremotefilelog <path>'),
1120 norepo=True,
1121 )
1122 def debugremotefilelog(ui, path, **opts):
1123 return debugcommands.debugremotefilelog(ui, path, **opts)
1124
1125
1126 @command(
1127 b'verifyremotefilelog',
1128 [
1129 (b'd', b'decompress', None, _(b'decompress the filelogs first')),
1130 ],
1131 _(b'hg verifyremotefilelogs <directory>'),
1132 norepo=True,
1133 )
1134 def verifyremotefilelog(ui, path, **opts):
1135 return debugcommands.verifyremotefilelog(ui, path, **opts)
1136
1137
1138 @command(
1139 b'debugdatapack',
1140 [
1141 (b'', b'long', None, _(b'print the long hashes')),
1142 (b'', b'node', b'', _(b'dump the contents of node'), b'NODE'),
1143 ],
1144 _(b'hg debugdatapack <paths>'),
1145 norepo=True,
1146 )
1147 def debugdatapack(ui, *paths, **opts):
1148 return debugcommands.debugdatapack(ui, *paths, **opts)
1149
1150
1151 @command(b'debughistorypack', [], _(b'hg debughistorypack <path>'), norepo=True)
1152 def debughistorypack(ui, path, **opts):
1153 return debugcommands.debughistorypack(ui, path)
1154
1155
1156 @command(b'debugkeepset', [], _(b'hg debugkeepset'))
1157 def debugkeepset(ui, repo, **opts):
1158 # The command is used to measure keepset computation time
1159 def keyfn(fname, fnode):
1160 return fileserverclient.getcachekey(repo.name, fname, hex(fnode))
1161
1162 repackmod.keepset(repo, keyfn)
1163 return
1164
1165
1166 @command(b'debugwaitonrepack', [], _(b'hg debugwaitonrepack'))
1167 def debugwaitonrepack(ui, repo, **opts):
1168 return debugcommands.debugwaitonrepack(repo)
1169
1170
1171 @command(b'debugwaitonprefetch', [], _(b'hg debugwaitonprefetch'))
1172 def debugwaitonprefetch(ui, repo, **opts):
1173 return debugcommands.debugwaitonprefetch(repo)
1174
1175
1176 def resolveprefetchopts(ui, opts):
1177 if not opts.get(b'rev'):
1178 revset = [b'.', b'draft()']
1179
1180 prefetchrevset = ui.config(b'remotefilelog', b'pullprefetch', None)
1181 if prefetchrevset:
1182 revset.append(b'(%s)' % prefetchrevset)
1183 bgprefetchrevs = ui.config(b'remotefilelog', b'bgprefetchrevs', None)
1184 if bgprefetchrevs:
1185 revset.append(b'(%s)' % bgprefetchrevs)
1186 revset = b'+'.join(revset)
1187
1188 # update a revset with a date limit
1189 revset = revdatelimit(ui, revset)
1190
1191 opts[b'rev'] = [revset]
1192
1193 if not opts.get(b'base'):
1194 opts[b'base'] = None
1195
1196 return opts
1197
1198
1199 @command(
1200 b'prefetch',
1201 [
1202 (b'r', b'rev', [], _(b'prefetch the specified revisions'), _(b'REV')),
1203 (b'', b'repack', False, _(b'run repack after prefetch')),
1204 (b'b', b'base', b'', _(b"rev that is assumed to already be local")),
1205 ]
1206 + commands.walkopts,
1207 _(b'hg prefetch [OPTIONS] [FILE...]'),
1208 helpcategory=command.CATEGORY_MAINTENANCE,
1209 )
1210 def prefetch(ui, repo, *pats, **opts):
1211 """prefetch file revisions from the server
1212
1213 Prefetchs file revisions for the specified revs and stores them in the
1214 local remotefilelog cache. If no rev is specified, the default rev is
1215 used which is the union of dot, draft, pullprefetch and bgprefetchrev.
1216 File names or patterns can be used to limit which files are downloaded.
1217
1218 Return 0 on success.
1219 """
1220 opts = pycompat.byteskwargs(opts)
1221 if not isenabled(repo):
1222 raise error.Abort(_(b"repo is not shallow"))
1223
1224 opts = resolveprefetchopts(ui, opts)
1225 revs = scmutil.revrange(repo, opts.get(b'rev'))
1226 repo.prefetch(revs, opts.get(b'base'), pats, opts)
1227
1228 # Run repack in background
1229 if opts.get(b'repack'):
1230 repackmod.backgroundrepack(repo, incremental=True)
1231
1232
1233 @command(
1234 b'repack',
1235 [
1236 (b'', b'background', None, _(b'run in a background process'), None),
1237 (b'', b'incremental', None, _(b'do an incremental repack'), None),
1238 (
1239 b'',
1240 b'packsonly',
1241 None,
1242 _(b'only repack packs (skip loose objects)'),
1243 None,
1244 ),
1245 ],
1246 _(b'hg repack [OPTIONS]'),
1247 )
1248 def repack_(ui, repo, *pats, **opts):
1249 if opts.get('background'):
1250 repackmod.backgroundrepack(
1251 repo,
1252 incremental=opts.get('incremental'),
1253 packsonly=opts.get('packsonly', False),
1254 )
1255 return
1256
1257 options = {b'packsonly': opts.get('packsonly')}
1258
1259 try:
1260 if opts.get('incremental'):
1261 repackmod.incrementalrepack(repo, options=options)
1262 else:
1263 repackmod.fullrepack(repo, options=options)
1264 except repackmod.RepackAlreadyRunning as ex:
1265 # Don't propogate the exception if the repack is already in
1266 # progress, since we want the command to exit 0.
1267 repo.ui.warn(b'%s\n' % ex)