| 1 |
# lfs - hash-preserving large file support using Git-LFS protocol |
| 2 |
# |
| 3 |
# Copyright 2017 Facebook, Inc. |
| 4 |
# |
| 5 |
# This software may be used and distributed according to the terms of the |
| 6 |
# GNU General Public License version 2 or any later version. |
| 7 |
|
| 8 |
"""lfs - large file support (EXPERIMENTAL) |
| 9 |
|
| 10 |
This extension allows large files to be tracked outside of the normal |
| 11 |
repository storage and stored on a centralized server, similar to the |
| 12 |
``largefiles`` extension. The ``git-lfs`` protocol is used when |
| 13 |
communicating with the server, so existing git infrastructure can be |
| 14 |
harnessed. Even though the files are stored outside of the repository, |
| 15 |
they are still integrity checked in the same manner as normal files. |
| 16 |
|
| 17 |
The files stored outside of the repository are downloaded on demand, |
| 18 |
which reduces the time to clone, and possibly the local disk usage. |
| 19 |
This changes fundamental workflows in a DVCS, so careful thought |
| 20 |
should be given before deploying it. :hg:`convert` can be used to |
| 21 |
convert LFS repositories to normal repositories that no longer |
| 22 |
require this extension, and do so without changing the commit hashes. |
| 23 |
This allows the extension to be disabled if the centralized workflow |
| 24 |
becomes burdensome. However, the pre and post convert clones will |
| 25 |
not be able to communicate with each other unless the extension is |
| 26 |
enabled on both. |
| 27 |
|
| 28 |
To start a new repository, or to add LFS files to an existing one, just |
| 29 |
create an ``.hglfs`` file as described below in the root directory of |
| 30 |
the repository. Typically, this file should be put under version |
| 31 |
control, so that the settings will propagate to other repositories with |
| 32 |
push and pull. During any commit, Mercurial will consult this file to |
| 33 |
determine if an added or modified file should be stored externally. The |
| 34 |
type of storage depends on the characteristics of the file at each |
| 35 |
commit. A file that is near a size threshold may switch back and forth |
| 36 |
between LFS and normal storage, as needed. |
| 37 |
|
| 38 |
Alternately, both normal repositories and largefile controlled |
| 39 |
repositories can be converted to LFS by using :hg:`convert` and the |
| 40 |
``lfs.track`` config option described below. The ``.hglfs`` file |
| 41 |
should then be created and added, to control subsequent LFS selection. |
| 42 |
The hashes are also unchanged in this case. The LFS and non-LFS |
| 43 |
repositories can be distinguished because the LFS repository will |
| 44 |
abort any command if this extension is disabled. |
| 45 |
|
| 46 |
Committed LFS files are held locally, until the repository is pushed. |
| 47 |
Prior to pushing the normal repository data, the LFS files that are |
| 48 |
tracked by the outgoing commits are automatically uploaded to the |
| 49 |
configured central server. No LFS files are transferred on |
| 50 |
:hg:`pull` or :hg:`clone`. Instead, the files are downloaded on |
| 51 |
demand as they need to be read, if a cached copy cannot be found |
| 52 |
locally. Both committing and downloading an LFS file will link the |
| 53 |
file to a usercache, to speed up future access. See the `usercache` |
| 54 |
config setting described below. |
| 55 |
|
| 56 |
The extension reads its configuration from a versioned ``.hglfs`` |
| 57 |
configuration file found in the root of the working directory. The |
| 58 |
``.hglfs`` file uses the same syntax as all other Mercurial |
| 59 |
configuration files. It uses a single section, ``[track]``. |
| 60 |
|
| 61 |
The ``[track]`` section specifies which files are stored as LFS (or |
| 62 |
not). Each line is keyed by a file pattern, with a predicate value. |
| 63 |
The first file pattern match is used, so put more specific patterns |
| 64 |
first. The available predicates are ``all()``, ``none()``, and |
| 65 |
``size()``. See "hg help filesets.size" for the latter. |
| 66 |
|
| 67 |
Example versioned ``.hglfs`` file:: |
| 68 |
|
| 69 |
[track] |
| 70 |
# No Makefile or python file, anywhere, will be LFS |
| 71 |
**Makefile = none() |
| 72 |
**.py = none() |
| 73 |
|
| 74 |
**.zip = all() |
| 75 |
**.exe = size(">1MB") |
| 76 |
|
| 77 |
# Catchall for everything not matched above |
| 78 |
** = size(">10MB") |
| 79 |
|
| 80 |
Configs:: |
| 81 |
|
| 82 |
[lfs] |
| 83 |
# Remote endpoint. Multiple protocols are supported: |
| 84 |
# - http(s)://user:[email protected]/path |
| 85 |
# git-lfs endpoint |
| 86 |
# - file:///tmp/path |
| 87 |
# local filesystem, usually for testing |
| 88 |
# if unset, lfs will assume the remote repository also handles blob storage |
| 89 |
# for http(s) URLs. Otherwise, lfs will prompt to set this when it must |
| 90 |
# use this value. |
| 91 |
# (default: unset) |
| 92 |
url = https://example.com/repo.git/info/lfs |
| 93 |
|
| 94 |
# Which files to track in LFS. Path tests are "**.extname" for file |
| 95 |
# extensions, and "path:under/some/directory" for path prefix. Both |
| 96 |
# are relative to the repository root. |
| 97 |
# File size can be tested with the "size()" fileset, and tests can be |
| 98 |
# joined with fileset operators. (See "hg help filesets.operators".) |
| 99 |
# |
| 100 |
# Some examples: |
| 101 |
# - all() # everything |
| 102 |
# - none() # nothing |
| 103 |
# - size(">20MB") # larger than 20MB |
| 104 |
# - !**.txt # anything not a *.txt file |
| 105 |
# - **.zip | **.tar.gz | **.7z # some types of compressed files |
| 106 |
# - path:bin # files under "bin" in the project root |
| 107 |
# - (**.php & size(">2MB")) | (**.js & size(">5MB")) | **.tar.gz |
| 108 |
# | (path:bin & !path:/bin/README) | size(">1GB") |
| 109 |
# (default: none()) |
| 110 |
# |
| 111 |
# This is ignored if there is a tracked '.hglfs' file, and this setting |
| 112 |
# will eventually be deprecated and removed. |
| 113 |
track = size(">10M") |
| 114 |
|
| 115 |
# how many times to retry before giving up on transferring an object |
| 116 |
retry = 5 |
| 117 |
|
| 118 |
# the local directory to store lfs files for sharing across local clones. |
| 119 |
# If not set, the cache is located in an OS specific cache location. |
| 120 |
usercache = /path/to/global/cache |
| 121 |
""" |
| 122 |
|
| 123 |
from __future__ import annotations |
| 124 |
|
| 125 |
import sys |
| 126 |
|
| 127 |
from mercurial.i18n import _ |
| 128 |
from mercurial.node import bin |
| 129 |
|
| 130 |
from mercurial import ( |
| 131 |
bundlecaches, |
| 132 |
cmd_impls, |
| 133 |
config, |
| 134 |
context, |
| 135 |
error, |
| 136 |
extensions, |
| 137 |
exthelper, |
| 138 |
filelog, |
| 139 |
filesetlang, |
| 140 |
localrepo, |
| 141 |
logcmdutil, |
| 142 |
merge, |
| 143 |
minifileset, |
| 144 |
pycompat, |
| 145 |
revlog, |
| 146 |
scmutil, |
| 147 |
templateutil, |
| 148 |
util, |
| 149 |
) |
| 150 |
|
| 151 |
from mercurial.interfaces import repository |
| 152 |
from mercurial.repo import vfs_options as repo_vfs_opts |
| 153 |
|
| 154 |
from . import ( |
| 155 |
blobstore, |
| 156 |
wireprotolfsserver, |
| 157 |
wrapper, |
| 158 |
) |
| 159 |
|
| 160 |
# Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for |
| 161 |
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should |
| 162 |
# be specifying the version(s) of Mercurial they are tested with, or |
| 163 |
# leave the attribute unspecified. |
| 164 |
testedwith = b'ships-with-hg-core' |
| 165 |
|
| 166 |
eh = exthelper.exthelper() |
| 167 |
eh.merge(wrapper.eh) |
| 168 |
eh.merge(wireprotolfsserver.eh) |
| 169 |
|
| 170 |
cmdtable = eh.cmdtable |
| 171 |
configtable = eh.configtable |
| 172 |
extsetup = eh.finalextsetup |
| 173 |
uisetup = eh.finaluisetup |
| 174 |
filesetpredicate = eh.filesetpredicate |
| 175 |
reposetup = eh.finalreposetup |
| 176 |
templatekeyword = eh.templatekeyword |
| 177 |
|
| 178 |
eh.configitem( |
| 179 |
b'experimental', |
| 180 |
b'lfs.serve', |
| 181 |
default=True, |
| 182 |
) |
| 183 |
eh.configitem( |
| 184 |
b'experimental', |
| 185 |
b'lfs.user-agent', |
| 186 |
default=None, |
| 187 |
) |
| 188 |
eh.configitem( |
| 189 |
b'experimental', |
| 190 |
b'lfs.disableusercache', |
| 191 |
default=False, |
| 192 |
) |
| 193 |
eh.configitem( |
| 194 |
b'experimental', |
| 195 |
b'lfs.worker-enable', |
| 196 |
default=True, |
| 197 |
) |
| 198 |
|
| 199 |
eh.configitem( |
| 200 |
b'lfs', |
| 201 |
b'url', |
| 202 |
default=None, |
| 203 |
) |
| 204 |
eh.configitem( |
| 205 |
b'lfs', |
| 206 |
b'usercache', |
| 207 |
default=None, |
| 208 |
) |
| 209 |
# Deprecated |
| 210 |
eh.configitem( |
| 211 |
b'lfs', |
| 212 |
b'threshold', |
| 213 |
default=None, |
| 214 |
) |
| 215 |
eh.configitem( |
| 216 |
b'lfs', |
| 217 |
b'track', |
| 218 |
default=b'none()', |
| 219 |
) |
| 220 |
eh.configitem( |
| 221 |
b'lfs', |
| 222 |
b'retry', |
| 223 |
default=5, |
| 224 |
) |
| 225 |
|
| 226 |
lfsprocessor = ( |
| 227 |
wrapper.readfromstore, |
| 228 |
wrapper.writetostore, |
| 229 |
wrapper.bypasscheckhash, |
| 230 |
) |
| 231 |
|
| 232 |
|
| 233 |
def featuresetup(ui, supported): |
| 234 |
# don't die on seeing a repo with the lfs requirement |
| 235 |
supported |= {b'lfs'} |
| 236 |
|
| 237 |
|
| 238 |
@eh.uisetup |
| 239 |
def _uisetup(ui): |
| 240 |
merge.MAYBE_USE_RUST_UPDATE = False |
| 241 |
localrepo.featuresetupfuncs.add(featuresetup) |
| 242 |
|
| 243 |
|
| 244 |
@eh.reposetup |
| 245 |
def _reposetup(ui, repo): |
| 246 |
# Nothing to do with a remote repo |
| 247 |
if not repo.local(): |
| 248 |
return |
| 249 |
|
| 250 |
repo.svfs.lfslocalblobstore = blobstore.local(repo) |
| 251 |
repo.svfs.lfsremoteblobstore = blobstore.remote(repo) |
| 252 |
|
| 253 |
class lfsrepo(repo.__class__): |
| 254 |
@localrepo.unfilteredmethod |
| 255 |
def commitctx(self, ctx, error=False, origctx=None): |
| 256 |
repo.svfs.options[b'lfstrack'] = _trackedmatcher(self) |
| 257 |
return super().commitctx(ctx, error, origctx=origctx) |
| 258 |
|
| 259 |
repo.__class__ = lfsrepo |
| 260 |
|
| 261 |
if b'lfs' not in repo.requirements: |
| 262 |
|
| 263 |
def checkrequireslfs(ui, repo, **kwargs): |
| 264 |
with repo.lock(): |
| 265 |
if b'lfs' in repo.requirements: |
| 266 |
return 0 |
| 267 |
|
| 268 |
last = kwargs.get('node_last') |
| 269 |
if last: |
| 270 |
s = repo.set(b'%n:%n', bin(kwargs['node']), bin(last)) |
| 271 |
else: |
| 272 |
s = repo.set(b'%n', bin(kwargs['node'])) |
| 273 |
match = repo._storenarrowmatch |
| 274 |
for ctx in s: |
| 275 |
# TODO: is there a way to just walk the files in the commit? |
| 276 |
if any( |
| 277 |
ctx[f].islfs() |
| 278 |
for f in ctx.files() |
| 279 |
if f in ctx and match(f) |
| 280 |
): |
| 281 |
repo.requirements.add(b'lfs') |
| 282 |
repo.features.add(repository.REPO_FEATURE_LFS) |
| 283 |
scmutil.writereporequirements(repo) |
| 284 |
repo.prepushoutgoinghooks.add(b'lfs', wrapper.prepush) |
| 285 |
break |
| 286 |
|
| 287 |
ui.setconfig(b'hooks', b'commit.lfs', checkrequireslfs, b'lfs') |
| 288 |
ui.setconfig( |
| 289 |
b'hooks', b'pretxnchangegroup.lfs', checkrequireslfs, b'lfs' |
| 290 |
) |
| 291 |
else: |
| 292 |
repo.prepushoutgoinghooks.add(b'lfs', wrapper.prepush) |
| 293 |
|
| 294 |
|
| 295 |
def _trackedmatcher(repo): |
| 296 |
"""Return a function (path, size) -> bool indicating whether or not to |
| 297 |
track a given file with lfs.""" |
| 298 |
if not repo.wvfs.exists(b'.hglfs'): |
| 299 |
# No '.hglfs' in wdir. Fallback to config for now. |
| 300 |
trackspec = repo.ui.config(b'lfs', b'track') |
| 301 |
|
| 302 |
# deprecated config: lfs.threshold |
| 303 |
threshold = repo.ui.configbytes(b'lfs', b'threshold') |
| 304 |
if threshold: |
| 305 |
filesetlang.parse(trackspec) # make sure syntax errors are confined |
| 306 |
trackspec = b"(%s) | size('>%d')" % (trackspec, threshold) |
| 307 |
|
| 308 |
return minifileset.compile(trackspec) |
| 309 |
|
| 310 |
data = repo.wvfs.tryread(b'.hglfs') |
| 311 |
if not data: |
| 312 |
return lambda p, s: False |
| 313 |
|
| 314 |
# Parse errors here will abort with a message that points to the .hglfs file |
| 315 |
# and line number. |
| 316 |
cfg = config.config() |
| 317 |
cfg.parse(b'.hglfs', data) |
| 318 |
|
| 319 |
try: |
| 320 |
rules = [ |
| 321 |
(minifileset.compile(pattern), minifileset.compile(rule)) |
| 322 |
for pattern, rule in cfg.items(b'track') |
| 323 |
] |
| 324 |
except error.ParseError as e: |
| 325 |
# The original exception gives no indicator that the error is in the |
| 326 |
# .hglfs file, so add that. |
| 327 |
|
| 328 |
# TODO: See if the line number of the file can be made available. |
| 329 |
raise error.Abort(_(b'parse error in .hglfs: %s') % e) |
| 330 |
|
| 331 |
def _match(path, size): |
| 332 |
for pat, rule in rules: |
| 333 |
if pat(path, size): |
| 334 |
return rule(path, size) |
| 335 |
|
| 336 |
return False |
| 337 |
|
| 338 |
return _match |
| 339 |
|
| 340 |
|
| 341 |
# Called by remotefilelog |
| 342 |
def wrapfilelog(filelog): |
| 343 |
wrapfunction = extensions.wrapfunction |
| 344 |
|
| 345 |
wrapfunction(filelog, 'addrevision', wrapper.filelogaddrevision) |
| 346 |
wrapfunction(filelog, 'renamed', wrapper.filelogrenamed) |
| 347 |
wrapfunction(filelog, 'has_meta', wrapper.filelog_has_meta) |
| 348 |
wrapfunction(filelog, 'size', wrapper.filelogsize) |
| 349 |
|
| 350 |
|
| 351 |
@eh.wrapfunction(repo_vfs_opts, 'resolve_revlog_store_vfs_options') |
| 352 |
def _resolverevlogstorevfsoptions(orig, ui, requirements, features): |
| 353 |
opts = orig(ui, requirements, features) |
| 354 |
for name, module in extensions.extensions(ui): |
| 355 |
if module is sys.modules[__name__]: |
| 356 |
if revlog.REVIDX_EXTSTORED in opts[b'flagprocessors']: |
| 357 |
msg = ( |
| 358 |
_(b"cannot register multiple processors on flag '%#x'.") |
| 359 |
% revlog.REVIDX_EXTSTORED |
| 360 |
) |
| 361 |
raise error.Abort(msg) |
| 362 |
|
| 363 |
opts[b'flagprocessors'][revlog.REVIDX_EXTSTORED] = lfsprocessor |
| 364 |
break |
| 365 |
|
| 366 |
return opts |
| 367 |
|
| 368 |
|
| 369 |
@eh.extsetup |
| 370 |
def _extsetup(ui): |
| 371 |
wrapfilelog(filelog.filelog) |
| 372 |
|
| 373 |
context.basefilectx.islfs = wrapper.filectxislfs |
| 374 |
|
| 375 |
scmutil.fileprefetchhooks.add(b'lfs', wrapper._prefetchfiles) |
| 376 |
|
| 377 |
# Make bundle choose changegroup3 instead of changegroup2. This affects |
| 378 |
# "hg bundle" command. Note: it does not cover all bundle formats like |
| 379 |
# "packed1". Using "packed1" with lfs will likely cause trouble. |
| 380 |
bundlecaches._bundlespeccontentopts[b"v2"][b"cg.version"] = b"03" |
| 381 |
|
| 382 |
|
| 383 |
@eh.filesetpredicate(b'lfs()') |
| 384 |
def lfsfileset(mctx, x): |
| 385 |
"""File that uses LFS storage.""" |
| 386 |
# i18n: "lfs" is a keyword |
| 387 |
filesetlang.getargs(x, 0, 0, _(b"lfs takes no arguments")) |
| 388 |
ctx = mctx.ctx |
| 389 |
|
| 390 |
def lfsfilep(f): |
| 391 |
return wrapper.pointerfromctx(ctx, f, removed=True) is not None |
| 392 |
|
| 393 |
return mctx.predicate(lfsfilep, predrepr=b'<lfs>') |
| 394 |
|
| 395 |
|
| 396 |
@eh.templatekeyword(b'lfs_files', requires={b'ctx'}) |
| 397 |
def lfsfiles(context, mapping): |
| 398 |
"""List of strings. All files modified, added, or removed by this |
| 399 |
changeset.""" |
| 400 |
ctx = context.resource(mapping, b'ctx') |
| 401 |
|
| 402 |
pointers = wrapper.pointersfromctx(ctx, removed=True) # {path: pointer} |
| 403 |
files = sorted(pointers.keys()) |
| 404 |
|
| 405 |
def pointer(v): |
| 406 |
# In the file spec, version is first and the other keys are sorted. |
| 407 |
sortkeyfunc = lambda x: (x[0] != b'version', x) |
| 408 |
items = sorted(pointers[v].items(), key=sortkeyfunc) |
| 409 |
return util.sortdict(items) |
| 410 |
|
| 411 |
makemap = lambda v: { |
| 412 |
b'file': v, |
| 413 |
b'lfsoid': pointers[v].oid() if pointers[v] else None, |
| 414 |
b'lfspointer': templateutil.hybriddict(pointer(v)), |
| 415 |
} |
| 416 |
|
| 417 |
# TODO: make the separator ', '? |
| 418 |
f = templateutil._showcompatlist(context, mapping, b'lfs_file', files) |
| 419 |
return templateutil.hybrid(f, files, makemap, pycompat.identity) |
| 420 |
|
| 421 |
|
| 422 |
@eh.command( |
| 423 |
b'debug::lfs-local-cache', |
| 424 |
cmd_impls.formatter_opts, |
| 425 |
) |
| 426 |
def debugcache(ui, repo, **opts): |
| 427 |
"""print information about the local blob cache""" |
| 428 |
path = b"" |
| 429 |
enabled = b"no" |
| 430 |
|
| 431 |
if (store := getattr(repo.svfs, "lfslocalblobstore", None)) is not None: |
| 432 |
# The nullvfs doesn't call the superclass constructor, so it doesn't |
| 433 |
# have a ``base`` attribute. |
| 434 |
if not isinstance(store.cachevfs, blobstore.nullvfs): |
| 435 |
path = store.cachevfs.base |
| 436 |
enabled = b"yes" |
| 437 |
|
| 438 |
with ui.formatter(b'lfs-local-cache', pycompat.byteskwargs(opts)) as fm: |
| 439 |
fm.startitem() |
| 440 |
fm.data(path=path, enabled=enabled) |
| 441 |
fm.plain(_(b"path: %s\n") % (path if path else b"(unknown)")) |
| 442 |
fm.plain(_(b"enabled: %s\n") % enabled) |
| 443 |
|
| 444 |
return 0 |
| 445 |
|
| 446 |
|
| 447 |
@eh.command( |
| 448 |
b'debuglfsupload', |
| 449 |
[(b'r', b'rev', [], _(b'upload large files introduced by REV'))], |
| 450 |
) |
| 451 |
def debuglfsupload(ui, repo, **opts): |
| 452 |
"""upload lfs blobs added by the working copy parent or given revisions""" |
| 453 |
revs = opts.get('rev', []) |
| 454 |
pointers = wrapper.extractpointers(repo, logcmdutil.revrange(repo, revs)) |
| 455 |
wrapper.uploadblobs(repo, pointers) |
| 456 |
|
| 457 |
|
| 458 |
@eh.wrapcommand( |
| 459 |
b'verify', |
| 460 |
opts=[(b'', b'no-lfs', None, _(b'skip missing lfs blob content'))], |
| 461 |
) |
| 462 |
def verify(orig, ui, repo, **opts): |
| 463 |
skipflags = repo.ui.configint(b'verify', b'skipflags') |
| 464 |
no_lfs = opts.pop('no_lfs') |
| 465 |
|
| 466 |
if skipflags: |
| 467 |
# --lfs overrides the config bit, if set. |
| 468 |
if no_lfs is False: |
| 469 |
skipflags &= ~repository.REVISION_FLAG_EXTSTORED |
| 470 |
else: |
| 471 |
skipflags = 0 |
| 472 |
|
| 473 |
if no_lfs is True: |
| 474 |
skipflags |= repository.REVISION_FLAG_EXTSTORED |
| 475 |
|
| 476 |
with ui.configoverride({(b'verify', b'skipflags'): skipflags}): |
| 477 |
return orig(ui, repo, **opts) |