##// END OF EJS Templates
compression: introduce a `storage.revlog.zstd.level` configuration...
compression: introduce a `storage.revlog.zstd.level` configuration This option control the zstd compression level used when compressing revlog chunk. The usage of zstd for revlog compression has not graduated from experimental yet, but we intend to fix that soon. The option name for the compression level is more straight forward to pick, so this changesets comes first. Having a dedicated option for each compression engine is useful because they don't support the same range of values. I ran the same measurement as for the zlib compression level (in the parent changesets). The variation in repository size is stay mostly in the same (small) range. The "read/write" performance see smallish variation, but are overall much better than zlib. Write performance show the same tend of having better write performance for when reaching high-end compression. Again, we don't intend to change the default zstd compression level (currently: 3) in this series. However this is worth investigating in the future. The Performance comparison of zlib vs zstd is quite impressive. The repository size stay in the same range, but the performance are much better in all situations. Comparison summary ================== We are looking at: - performance range for zlib - performance range for zstd - comparison of default zstd (level-3) to default zlib (level 6) - comparison of the slowest zstd time to the fastest zlib time Read performance: ----------------- | zlib | zstd | cmp | f2s mercurial | 0.170159 - 0.189219 | 0.144127 - 0.149624 | 80% | 88% pypy | 2.679217 - 2.768691 | 1.532317 - 1.705044 | 60% | 63% netbeans | 122.477027 - 141.620281 | 72.996346 - 89.731560 | 58% | 73% mozilla | 147.867662 - 170.572118 | 91.700995 - 105.853099 | 56% | 71% Write performance: ------------------ | zlib | zstd | cmp | f2s mercurial | 53.250304 - 56.2936129 | 40.877025 - 45.677286 | 75% | 86% pypy | 460.721984 - 476.589918 | 270.545409 - 301.002219 | 63% | 65% netbeans | 520.560316 - 715.930400 | 370.356311 - 428.329652 | 55% | 82% mozilla | 739.803002 - 987.056093 | 505.152906 - 591.930683 | 57% | 80% Raw data -------- repo alg lvl .hg/store size 00manifest.d read write mercurial zlib 1 49,402,813 5,963,475 0.170159 53.250304 mercurial zlib 6 47,197,397 5,875,730 0.182820 56.264320 mercurial zlib 9 47,121,596 5,849,781 0.189219 56.293612 mercurial zstd 1 49,737,084 5,966,355 0.144127 40.877025 mercurial zstd 3 48,961,867 5,895,208 0.146376 42.268142 mercurial zstd 5 48,200,592 5,938,676 0.149624 43.162875 mercurial zstd 10 47,833,520 5,913,353 0.145185 44.012489 mercurial zstd 15 47,314,604 5,728,679 0.147686 45.677286 mercurial zstd 20 47,330,502 5,830,539 0.145789 45.025407 mercurial zstd 22 47,330,076 5,830,539 0.143996 44.690460 pypy zlib 1 370,830,572 28,462,425 2.679217 460.721984 pypy zlib 6 340,112,317 27,648,747 2.768691 467.537158 pypy zlib 9 338,360,736 27,639,003 2.763495 476.589918 pypy zstd 1 362,377,479 27,916,214 1.532317 270.545409 pypy zstd 3 354,137,693 27,905,988 1.686718 294.951509 pypy zstd 5 342,640,043 27,655,774 1.705044 301.002219 pypy zstd 10 334,224,327 27,164,493 1.567287 285.186239 pypy zstd 15 329,000,363 26,645,965 1.637729 299.561332 pypy zstd 20 324,534,039 26,199,547 1.526813 302.149827 pypy zstd 22 324,530,595 26,198,932 1.525718 307.821218 netbeans zlib 1 1,281,847,810 165,495,457 122.477027 520.560316 netbeans zlib 6 1,205,284,353 159,161,207 139.876147 715.930400 netbeans zlib 9 1,197,135,671 155,034,586 141.620281 678.297064 netbeans zstd 1 1,259,581,737 160,840,613 72.996346 370.356311 netbeans zstd 3 1,232,978,122 157,691,551 81.622317 396.733087 netbeans zstd 5 1,208,034,075 160,246,880 83.080549 364.342626 netbeans zstd 10 1,188,624,176 156,083,417 79.323935 403.594602 netbeans zstd 15 1,176,973,589 153,859,477 89.731560 428.329652 netbeans zstd 20 1,162,958,258 151,147,535 82.842667 392.335349 netbeans zstd 22 1,162,707,029 151,150,220 82.565695 402.840655 mozilla zlib 1 2,775,497,186 298,527,987 147.867662 751.263721 mozilla zlib 6 2,596,856,420 286,597,671 170.572118 987.056093 mozilla zlib 9 2,587,542,494 287,018,264 163.622338 739.803002 mozilla zstd 1 2,723,159,348 286,617,532 91.700995 570.042751 mozilla zstd 3 2,665,055,001 286,152,013 95.240155 561.412805 mozilla zstd 5 2,607,819,817 288,060,030 101.978048 505.152906 mozilla zstd 10 2,558,761,085 283,967,648 104.113481 497.771202 mozilla zstd 15 2,526,216,060 275,581,300 105.853099 591.930683 mozilla zstd 20 2,485,114,806 266,478,859 95.268795 576.515389 mozilla zstd 22 2,484,869,080 266,456,505 94.429282 572.785537

File last commit:

r41756:698667eb default
r42211:bb271ec2 default
Show More
blobstore.py
678 lines | 25.6 KiB | text/x-python | PythonLexer
# blobstore.py - local and remote (speaking Git-LFS protocol) blob storages
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import contextlib
import errno
import hashlib
import json
import os
import re
import socket
from mercurial.i18n import _
from mercurial import (
encoding,
error,
node,
pathutil,
pycompat,
url as urlmod,
util,
vfs as vfsmod,
worker,
)
from mercurial.utils import (
stringutil,
)
from ..largefiles import lfutil
# 64 bytes for SHA256
_lfsre = re.compile(br'\A[a-f0-9]{64}\Z')
class lfsvfs(vfsmod.vfs):
def join(self, path):
"""split the path at first two characters, like: XX/XXXXX..."""
if not _lfsre.match(path):
raise error.ProgrammingError(b'unexpected lfs path: %s' % path)
return super(lfsvfs, self).join(path[0:2], path[2:])
def walk(self, path=None, onerror=None):
"""Yield (dirpath, [], oids) tuple for blobs under path
Oids only exist in the root of this vfs, so dirpath is always ''.
"""
root = os.path.normpath(self.base)
# when dirpath == root, dirpath[prefixlen:] becomes empty
# because len(dirpath) < prefixlen.
prefixlen = len(pathutil.normasprefix(root))
oids = []
for dirpath, dirs, files in os.walk(self.reljoin(self.base, path
or b''),
onerror=onerror):
dirpath = dirpath[prefixlen:]
# Silently skip unexpected files and directories
if len(dirpath) == 2:
oids.extend([dirpath + f for f in files
if _lfsre.match(dirpath + f)])
yield ('', [], oids)
class nullvfs(lfsvfs):
def __init__(self):
pass
def exists(self, oid):
return False
def read(self, oid):
# store.read() calls into here if the blob doesn't exist in its
# self.vfs. Raise the same error as a normal vfs when asked to read a
# file that doesn't exist. The only difference is the full file path
# isn't available in the error.
raise IOError(errno.ENOENT,
pycompat.sysstr(b'%s: No such file or directory' % oid))
def walk(self, path=None, onerror=None):
return (b'', [], [])
def write(self, oid, data):
pass
class filewithprogress(object):
"""a file-like object that supports __len__ and read.
Useful to provide progress information for how many bytes are read.
"""
def __init__(self, fp, callback):
self._fp = fp
self._callback = callback # func(readsize)
fp.seek(0, os.SEEK_END)
self._len = fp.tell()
fp.seek(0)
def __len__(self):
return self._len
def read(self, size):
if self._fp is None:
return b''
data = self._fp.read(size)
if data:
if self._callback:
self._callback(len(data))
else:
self._fp.close()
self._fp = None
return data
class local(object):
"""Local blobstore for large file contents.
This blobstore is used both as a cache and as a staging area for large blobs
to be uploaded to the remote blobstore.
"""
def __init__(self, repo):
fullpath = repo.svfs.join(b'lfs/objects')
self.vfs = lfsvfs(fullpath)
if repo.ui.configbool(b'experimental', b'lfs.disableusercache'):
self.cachevfs = nullvfs()
else:
usercache = lfutil._usercachedir(repo.ui, b'lfs')
self.cachevfs = lfsvfs(usercache)
self.ui = repo.ui
def open(self, oid):
"""Open a read-only file descriptor to the named blob, in either the
usercache or the local store."""
# The usercache is the most likely place to hold the file. Commit will
# write to both it and the local store, as will anything that downloads
# the blobs. However, things like clone without an update won't
# populate the local store. For an init + push of a local clone,
# the usercache is the only place it _could_ be. If not present, the
# missing file msg here will indicate the local repo, not the usercache.
if self.cachevfs.exists(oid):
return self.cachevfs(oid, b'rb')
return self.vfs(oid, b'rb')
def download(self, oid, src):
"""Read the blob from the remote source in chunks, verify the content,
and write to this local blobstore."""
sha256 = hashlib.sha256()
with self.vfs(oid, b'wb', atomictemp=True) as fp:
for chunk in util.filechunkiter(src, size=1048576):
fp.write(chunk)
sha256.update(chunk)
realoid = node.hex(sha256.digest())
if realoid != oid:
raise LfsCorruptionError(_(b'corrupt remote lfs object: %s')
% oid)
self._linktousercache(oid)
def write(self, oid, data):
"""Write blob to local blobstore.
This should only be called from the filelog during a commit or similar.
As such, there is no need to verify the data. Imports from a remote
store must use ``download()`` instead."""
with self.vfs(oid, b'wb', atomictemp=True) as fp:
fp.write(data)
self._linktousercache(oid)
def linkfromusercache(self, oid):
"""Link blobs found in the user cache into this store.
The server module needs to do this when it lets the client know not to
upload the blob, to ensure it is always available in this store.
Normally this is done implicitly when the client reads or writes the
blob, but that doesn't happen when the server tells the client that it
already has the blob.
"""
if (not isinstance(self.cachevfs, nullvfs)
and not self.vfs.exists(oid)):
self.ui.note(_(b'lfs: found %s in the usercache\n') % oid)
lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid))
def _linktousercache(self, oid):
# XXX: should we verify the content of the cache, and hardlink back to
# the local store on success, but truncate, write and link on failure?
if (not self.cachevfs.exists(oid)
and not isinstance(self.cachevfs, nullvfs)):
self.ui.note(_(b'lfs: adding %s to the usercache\n') % oid)
lfutil.link(self.vfs.join(oid), self.cachevfs.join(oid))
def read(self, oid, verify=True):
"""Read blob from local blobstore."""
if not self.vfs.exists(oid):
blob = self._read(self.cachevfs, oid, verify)
# Even if revlog will verify the content, it needs to be verified
# now before making the hardlink to avoid propagating corrupt blobs.
# Don't abort if corruption is detected, because `hg verify` will
# give more useful info about the corruption- simply don't add the
# hardlink.
if verify or node.hex(hashlib.sha256(blob).digest()) == oid:
self.ui.note(_(b'lfs: found %s in the usercache\n') % oid)
lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid))
else:
self.ui.note(_(b'lfs: found %s in the local lfs store\n') % oid)
blob = self._read(self.vfs, oid, verify)
return blob
def _read(self, vfs, oid, verify):
"""Read blob (after verifying) from the given store"""
blob = vfs.read(oid)
if verify:
_verify(oid, blob)
return blob
def verify(self, oid):
"""Indicate whether or not the hash of the underlying file matches its
name."""
sha256 = hashlib.sha256()
with self.open(oid) as fp:
for chunk in util.filechunkiter(fp, size=1048576):
sha256.update(chunk)
return oid == node.hex(sha256.digest())
def has(self, oid):
"""Returns True if the local blobstore contains the requested blob,
False otherwise."""
return self.cachevfs.exists(oid) or self.vfs.exists(oid)
def _urlerrorreason(urlerror):
'''Create a friendly message for the given URLError to be used in an
LfsRemoteError message.
'''
inst = urlerror
if isinstance(urlerror.reason, Exception):
inst = urlerror.reason
if util.safehasattr(inst, 'reason'):
try: # usually it is in the form (errno, strerror)
reason = inst.reason.args[1]
except (AttributeError, IndexError):
# it might be anything, for example a string
reason = inst.reason
if isinstance(reason, pycompat.unicode):
# SSLError of Python 2.7.9 contains a unicode
reason = encoding.unitolocal(reason)
return reason
elif getattr(inst, "strerror", None):
return encoding.strtolocal(inst.strerror)
else:
return stringutil.forcebytestr(urlerror)
class lfsauthhandler(util.urlreq.basehandler):
handler_order = 480 # Before HTTPDigestAuthHandler (== 490)
def http_error_401(self, req, fp, code, msg, headers):
"""Enforces that any authentication performed is HTTP Basic
Authentication. No authentication is also acceptable.
"""
authreq = headers.get(r'www-authenticate', None)
if authreq:
scheme = authreq.split()[0]
if scheme.lower() != r'basic':
msg = _(b'the server must support Basic Authentication')
raise util.urlerr.httperror(req.get_full_url(), code,
encoding.strfromlocal(msg), headers,
fp)
return None
class _gitlfsremote(object):
def __init__(self, repo, url):
ui = repo.ui
self.ui = ui
baseurl, authinfo = url.authinfo()
self.baseurl = baseurl.rstrip(b'/')
useragent = repo.ui.config(b'experimental', b'lfs.user-agent')
if not useragent:
useragent = b'git-lfs/2.3.4 (Mercurial %s)' % util.version()
self.urlopener = urlmod.opener(ui, authinfo, useragent)
self.urlopener.add_handler(lfsauthhandler())
self.retry = ui.configint(b'lfs', b'retry')
def writebatch(self, pointers, fromstore):
"""Batch upload from local to remote blobstore."""
self._batch(_deduplicate(pointers), fromstore, b'upload')
def readbatch(self, pointers, tostore):
"""Batch download from remote to local blostore."""
self._batch(_deduplicate(pointers), tostore, b'download')
def _batchrequest(self, pointers, action):
"""Get metadata about objects pointed by pointers for given action
Return decoded JSON object like {'objects': [{'oid': '', 'size': 1}]}
See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
"""
objects = [{r'oid': pycompat.strurl(p.oid()),
r'size': p.size()} for p in pointers]
requestdata = pycompat.bytesurl(json.dumps({
r'objects': objects,
r'operation': pycompat.strurl(action),
}))
url = b'%s/objects/batch' % self.baseurl
batchreq = util.urlreq.request(pycompat.strurl(url), data=requestdata)
batchreq.add_header(r'Accept', r'application/vnd.git-lfs+json')
batchreq.add_header(r'Content-Type', r'application/vnd.git-lfs+json')
try:
with contextlib.closing(self.urlopener.open(batchreq)) as rsp:
rawjson = rsp.read()
except util.urlerr.httperror as ex:
hints = {
400: _(b'check that lfs serving is enabled on %s and "%s" is '
b'supported') % (self.baseurl, action),
404: _(b'the "lfs.url" config may be used to override %s')
% self.baseurl,
}
hint = hints.get(ex.code, _(b'api=%s, action=%s') % (url, action))
raise LfsRemoteError(
_(b'LFS HTTP error: %s') % stringutil.forcebytestr(ex),
hint=hint)
except util.urlerr.urlerror as ex:
hint = (_(b'the "lfs.url" config may be used to override %s')
% self.baseurl)
raise LfsRemoteError(_(b'LFS error: %s') % _urlerrorreason(ex),
hint=hint)
try:
response = json.loads(rawjson)
except ValueError:
raise LfsRemoteError(_(b'LFS server returns invalid JSON: %s')
% rawjson.encode("utf-8"))
if self.ui.debugflag:
self.ui.debug(b'Status: %d\n' % rsp.status)
# lfs-test-server and hg serve return headers in different order
headers = pycompat.bytestr(rsp.info()).strip()
self.ui.debug(b'%s\n'
% b'\n'.join(sorted(headers.splitlines())))
if r'objects' in response:
response[r'objects'] = sorted(response[r'objects'],
key=lambda p: p[r'oid'])
self.ui.debug(b'%s\n'
% pycompat.bytesurl(
json.dumps(response, indent=2,
separators=(r'', r': '),
sort_keys=True)))
def encodestr(x):
if isinstance(x, pycompat.unicode):
return x.encode(u'utf-8')
return x
return pycompat.rapply(encodestr, response)
def _checkforservererror(self, pointers, responses, action):
"""Scans errors from objects
Raises LfsRemoteError if any objects have an error"""
for response in responses:
# The server should return 404 when objects cannot be found. Some
# server implementation (ex. lfs-test-server) does not set "error"
# but just removes "download" from "actions". Treat that case
# as the same as 404 error.
if b'error' not in response:
if (action == b'download'
and action not in response.get(b'actions', [])):
code = 404
else:
continue
else:
# An error dict without a code doesn't make much sense, so
# treat as a server error.
code = response.get(b'error').get(b'code', 500)
ptrmap = {p.oid(): p for p in pointers}
p = ptrmap.get(response[b'oid'], None)
if p:
filename = getattr(p, 'filename', b'unknown')
errors = {
404: b'The object does not exist',
410: b'The object was removed by the owner',
422: b'Validation error',
500: b'Internal server error',
}
msg = errors.get(code, b'status code %d' % code)
raise LfsRemoteError(_(b'LFS server error for "%s": %s')
% (filename, msg))
else:
raise LfsRemoteError(
_(b'LFS server error. Unsolicited response for oid %s')
% response[b'oid'])
def _extractobjects(self, response, pointers, action):
"""extract objects from response of the batch API
response: parsed JSON object returned by batch API
return response['objects'] filtered by action
raise if any object has an error
"""
# Scan errors from objects - fail early
objects = response.get(b'objects', [])
self._checkforservererror(pointers, objects, action)
# Filter objects with given action. Practically, this skips uploading
# objects which exist in the server.
filteredobjects = [o for o in objects
if action in o.get(b'actions', [])]
return filteredobjects
def _basictransfer(self, obj, action, localstore):
"""Download or upload a single object using basic transfer protocol
obj: dict, an object description returned by batch API
action: string, one of ['upload', 'download']
localstore: blobstore.local
See https://github.com/git-lfs/git-lfs/blob/master/docs/api/\
basic-transfers.md
"""
oid = obj[b'oid']
href = obj[b'actions'][action].get(b'href')
headers = obj[b'actions'][action].get(b'header', {}).items()
request = util.urlreq.request(pycompat.strurl(href))
if action == b'upload':
# If uploading blobs, read data from local blobstore.
if not localstore.verify(oid):
raise error.Abort(_(b'detected corrupt lfs object: %s') % oid,
hint=_(b'run hg verify'))
request.data = filewithprogress(localstore.open(oid), None)
request.get_method = lambda: r'PUT'
request.add_header(r'Content-Type', r'application/octet-stream')
request.add_header(r'Content-Length', len(request.data))
for k, v in headers:
request.add_header(pycompat.strurl(k), pycompat.strurl(v))
response = b''
try:
with contextlib.closing(self.urlopener.open(request)) as req:
ui = self.ui # Shorten debug lines
if self.ui.debugflag:
ui.debug(b'Status: %d\n' % req.status)
# lfs-test-server and hg serve return headers in different
# order
headers = pycompat.bytestr(req.info()).strip()
ui.debug(b'%s\n'
% b'\n'.join(sorted(headers.splitlines())))
if action == b'download':
# If downloading blobs, store downloaded data to local
# blobstore
localstore.download(oid, req)
else:
while True:
data = req.read(1048576)
if not data:
break
response += data
if response:
ui.debug(b'lfs %s response: %s' % (action, response))
except util.urlerr.httperror as ex:
if self.ui.debugflag:
self.ui.debug(b'%s: %s\n' % (oid, ex.read())) # XXX: also bytes?
raise LfsRemoteError(_(b'LFS HTTP error: %s (oid=%s, action=%s)')
% (stringutil.forcebytestr(ex), oid, action))
except util.urlerr.urlerror as ex:
hint = (_(b'attempted connection to %s')
% pycompat.bytesurl(util.urllibcompat.getfullurl(request)))
raise LfsRemoteError(_(b'LFS error: %s') % _urlerrorreason(ex),
hint=hint)
def _batch(self, pointers, localstore, action):
if action not in [b'upload', b'download']:
raise error.ProgrammingError(b'invalid Git-LFS action: %s' % action)
response = self._batchrequest(pointers, action)
objects = self._extractobjects(response, pointers, action)
total = sum(x.get(b'size', 0) for x in objects)
sizes = {}
for obj in objects:
sizes[obj.get(b'oid')] = obj.get(b'size', 0)
topic = {b'upload': _(b'lfs uploading'),
b'download': _(b'lfs downloading')}[action]
if len(objects) > 1:
self.ui.note(_(b'lfs: need to transfer %d objects (%s)\n')
% (len(objects), util.bytecount(total)))
def transfer(chunk):
for obj in chunk:
objsize = obj.get(b'size', 0)
if self.ui.verbose:
if action == b'download':
msg = _(b'lfs: downloading %s (%s)\n')
elif action == b'upload':
msg = _(b'lfs: uploading %s (%s)\n')
self.ui.note(msg % (obj.get(b'oid'),
util.bytecount(objsize)))
retry = self.retry
while True:
try:
self._basictransfer(obj, action, localstore)
yield 1, obj.get(b'oid')
break
except socket.error as ex:
if retry > 0:
self.ui.note(
_(b'lfs: failed: %r (remaining retry %d)\n')
% (stringutil.forcebytestr(ex), retry))
retry -= 1
continue
raise
# Until https multiplexing gets sorted out
if self.ui.configbool(b'experimental', b'lfs.worker-enable'):
oids = worker.worker(self.ui, 0.1, transfer, (),
sorted(objects, key=lambda o: o.get(b'oid')))
else:
oids = transfer(sorted(objects, key=lambda o: o.get(b'oid')))
with self.ui.makeprogress(topic, total=total) as progress:
progress.update(0)
processed = 0
blobs = 0
for _one, oid in oids:
processed += sizes[oid]
blobs += 1
progress.update(processed)
self.ui.note(_(b'lfs: processed: %s\n') % oid)
if blobs > 0:
if action == b'upload':
self.ui.status(_(b'lfs: uploaded %d files (%s)\n')
% (blobs, util.bytecount(processed)))
elif action == b'download':
self.ui.status(_(b'lfs: downloaded %d files (%s)\n')
% (blobs, util.bytecount(processed)))
def __del__(self):
# copied from mercurial/httppeer.py
urlopener = getattr(self, 'urlopener', None)
if urlopener:
for h in urlopener.handlers:
h.close()
getattr(h, "close_all", lambda : None)()
class _dummyremote(object):
"""Dummy store storing blobs to temp directory."""
def __init__(self, repo, url):
fullpath = repo.vfs.join(b'lfs', url.path)
self.vfs = lfsvfs(fullpath)
def writebatch(self, pointers, fromstore):
for p in _deduplicate(pointers):
content = fromstore.read(p.oid(), verify=True)
with self.vfs(p.oid(), b'wb', atomictemp=True) as fp:
fp.write(content)
def readbatch(self, pointers, tostore):
for p in _deduplicate(pointers):
with self.vfs(p.oid(), b'rb') as fp:
tostore.download(p.oid(), fp)
class _nullremote(object):
"""Null store storing blobs to /dev/null."""
def __init__(self, repo, url):
pass
def writebatch(self, pointers, fromstore):
pass
def readbatch(self, pointers, tostore):
pass
class _promptremote(object):
"""Prompt user to set lfs.url when accessed."""
def __init__(self, repo, url):
pass
def writebatch(self, pointers, fromstore, ui=None):
self._prompt()
def readbatch(self, pointers, tostore, ui=None):
self._prompt()
def _prompt(self):
raise error.Abort(_(b'lfs.url needs to be configured'))
_storemap = {
b'https': _gitlfsremote,
b'http': _gitlfsremote,
b'file': _dummyremote,
b'null': _nullremote,
None: _promptremote,
}
def _deduplicate(pointers):
"""Remove any duplicate oids that exist in the list"""
reduced = util.sortdict()
for p in pointers:
reduced[p.oid()] = p
return reduced.values()
def _verify(oid, content):
realoid = node.hex(hashlib.sha256(content).digest())
if realoid != oid:
raise LfsCorruptionError(_(b'detected corrupt lfs object: %s') % oid,
hint=_(b'run hg verify'))
def remote(repo, remote=None):
"""remotestore factory. return a store in _storemap depending on config
If ``lfs.url`` is specified, use that remote endpoint. Otherwise, try to
infer the endpoint, based on the remote repository using the same path
adjustments as git. As an extension, 'http' is supported as well so that
``hg serve`` works out of the box.
https://github.com/git-lfs/git-lfs/blob/master/docs/api/server-discovery.md
"""
lfsurl = repo.ui.config(b'lfs', b'url')
url = util.url(lfsurl or '')
if lfsurl is None:
if remote:
path = remote
elif util.safehasattr(repo, '_subtoppath'):
# The pull command sets this during the optional update phase, which
# tells exactly where the pull originated, whether 'paths.default'
# or explicit.
path = repo._subtoppath
else:
# TODO: investigate 'paths.remote:lfsurl' style path customization,
# and fall back to inferring from 'paths.remote' if unspecified.
path = repo.ui.config(b'paths', b'default') or b''
defaulturl = util.url(path)
# TODO: support local paths as well.
# TODO: consider the ssh -> https transformation that git applies
if defaulturl.scheme in (b'http', b'https'):
if defaulturl.path and defaulturl.path[:-1] != b'/':
defaulturl.path += b'/'
defaulturl.path = (defaulturl.path or b'') + b'.git/info/lfs'
url = util.url(bytes(defaulturl))
repo.ui.note(_(b'lfs: assuming remote store: %s\n') % url)
scheme = url.scheme
if scheme not in _storemap:
raise error.Abort(_(b'lfs: unknown url scheme: %s') % scheme)
return _storemap[scheme](repo, url)
class LfsRemoteError(error.StorageError):
pass
class LfsCorruptionError(error.Abort):
"""Raised when a corrupt blob is detected, aborting an operation
It exists to allow specialized handling on the server side."""