Debian Codegraph @

hgext/lfs/blobstore.py

raw
1 # blobstore.py - local and remote (speaking Git-LFS protocol) blob storages
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 from __future__ import annotations
9
10 import contextlib
11 import errno
12 import hashlib
13 import json
14 import os
15 import re
16
17 from mercurial.i18n import _
18 from mercurial.node import hex
19
20 from mercurial import (
21 encoding,
22 error,
23 httpconnection as httpconnectionmod,
24 pathutil,
25 pycompat,
26 url as urlmod,
27 util,
28 vfs as vfsmod,
29 worker,
30 )
31
32 from mercurial.utils import (
33 stringutil,
34 urlutil,
35 )
36
37 from ..largefiles import lfutil
38
39 # 64 bytes for SHA256
40 _lfsre = re.compile(br'\A[a-f0-9]{64}\Z')
41
42
43 class lfsvfs(vfsmod.vfs):
44 def __init__(self, base: bytes) -> None:
45 super().__init__(base, expandpath=True, realpath=True)
46
47 def join(self, path: bytes | None, *insidef: bytes) -> bytes:
48 """split the path at first two characters, like: XX/XXXXX..."""
49 if not _lfsre.match(path):
50 raise error.ProgrammingError(b'unexpected lfs path: %s' % path)
51 return super().join(path[0:2], path[2:], *insidef)
52
53 def walk(self, path=None, onerror=None):
54 """Yield (dirpath, [], oids) tuple for blobs under path
55
56 Oids only exist in the root of this vfs, so dirpath is always ''.
57 """
58 root = os.path.normpath(self.base)
59 # when dirpath == root, dirpath[prefixlen:] becomes empty
60 # because len(dirpath) < prefixlen.
61 prefixlen = len(pathutil.normasprefix(root))
62 oids = []
63
64 for dirpath, dirs, files in os.walk(
65 self.reljoin(self.base, path or b''), onerror=onerror
66 ):
67 dirpath = dirpath[prefixlen:]
68
69 # Silently skip unexpected files and directories
70 if len(dirpath) == 2:
71 oids.extend(
72 [dirpath + f for f in files if _lfsre.match(dirpath + f)]
73 )
74
75 yield (b'', [], oids)
76
77
78 class nullvfs(lfsvfs):
79 def __init__(self):
80 pass
81
82 def exists(self, path: bytes | None = None) -> bool:
83 return False
84
85 def read(self, oid):
86 # store.read() calls into here if the blob doesn't exist in its
87 # self.vfs. Raise the same error as a normal vfs when asked to read a
88 # file that doesn't exist. The only difference is the full file path
89 # isn't available in the error.
90 raise OSError(
91 errno.ENOENT,
92 pycompat.sysstr(b'%s: No such file or directory' % oid),
93 )
94
95 def walk(self, path=None, onerror=None):
96 return (b'', [], [])
97
98 def write(self, *args, **kwargs) -> int:
99 return 0
100
101
102 class lfsuploadfile(httpconnectionmod.httpsendfile):
103 """a file-like object that supports keepalive."""
104
105 def __init__(self, ui, filename):
106 super().__init__(ui, filename, b'rb')
107 self.read = self._data.read
108
109 def _makeprogress(self):
110 return None # progress is handled by the worker client
111
112
113 class local:
114 """Local blobstore for large file contents.
115
116 This blobstore is used both as a cache and as a staging area for large blobs
117 to be uploaded to the remote blobstore.
118 """
119
120 def __init__(self, repo):
121 fullpath = repo.svfs.join(b'lfs/objects')
122 self.vfs = lfsvfs(fullpath)
123
124 if repo.ui.configbool(b'experimental', b'lfs.disableusercache'):
125 self.cachevfs = nullvfs()
126 else:
127 usercache = lfutil._usercachedir(repo.ui, b'lfs')
128 self.cachevfs = lfsvfs(usercache)
129 self.ui = repo.ui
130
131 def open(self, oid):
132 """Open a read-only file descriptor to the named blob, in either the
133 usercache or the local store."""
134 return open(self.path(oid), 'rb')
135
136 def path(self, oid):
137 """Build the path for the given blob ``oid``.
138
139 If the blob exists locally, the path may point to either the usercache
140 or the local store. If it doesn't, it will point to the local store.
141 This is meant for situations where existing code that isn't LFS aware
142 needs to open a blob. Generally, prefer the ``open`` method on this
143 class.
144 """
145 # The usercache is the most likely place to hold the file. Commit will
146 # write to both it and the local store, as will anything that downloads
147 # the blobs. However, things like clone without an update won't
148 # populate the local store. For an init + push of a local clone,
149 # the usercache is the only place it _could_ be. If not present, the
150 # missing file msg here will indicate the local repo, not the usercache.
151 if self.cachevfs.exists(oid):
152 return self.cachevfs.join(oid)
153
154 return self.vfs.join(oid)
155
156 def download(self, oid, src, content_length):
157 """Read the blob from the remote source in chunks, verify the content,
158 and write to this local blobstore."""
159 sha256 = hashlib.sha256()
160 size = 0
161
162 with self.vfs(oid, b'wb', atomictemp=True) as fp:
163 for chunk in util.filechunkiter(src, size=1048576):
164 fp.write(chunk)
165 sha256.update(chunk)
166 size += len(chunk)
167
168 # If the server advertised a length longer than what we actually
169 # received, then we should expect that the server crashed while
170 # producing the response (but the server has no way of telling us
171 # that), and we really don't need to try to write the response to
172 # the localstore, because it's not going to match the expected.
173 # The server also uses this method to store data uploaded by the
174 # client, so if this happens on the server side, it's possible
175 # that the client crashed or an antivirus interfered with the
176 # upload.
177 if content_length is not None and int(content_length) != size:
178 msg = (
179 b"Response length (%d) does not match Content-Length "
180 b"header (%d) for %s"
181 )
182 raise LfsRemoteError(_(msg) % (size, int(content_length), oid))
183
184 realoid = hex(sha256.digest())
185 if realoid != oid:
186 raise LfsCorruptionError(
187 _(b'corrupt remote lfs object: %s') % oid
188 )
189
190 self._linktousercache(oid)
191
192 def write(self, oid, data):
193 """Write blob to local blobstore.
194
195 This should only be called from the filelog during a commit or similar.
196 As such, there is no need to verify the data. Imports from a remote
197 store must use ``download()`` instead."""
198 with self.vfs(oid, b'wb', atomictemp=True) as fp:
199 fp.write(data)
200
201 self._linktousercache(oid)
202
203 def linkfromusercache(self, oid):
204 """Link blobs found in the user cache into this store.
205
206 The server module needs to do this when it lets the client know not to
207 upload the blob, to ensure it is always available in this store.
208 Normally this is done implicitly when the client reads or writes the
209 blob, but that doesn't happen when the server tells the client that it
210 already has the blob.
211 """
212 if not isinstance(self.cachevfs, nullvfs) and not self.vfs.exists(oid):
213 self.ui.note(_(b'lfs: found %s in the usercache\n') % oid)
214 lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid))
215
216 def _linktousercache(self, oid):
217 # XXX: should we verify the content of the cache, and hardlink back to
218 # the local store on success, but truncate, write and link on failure?
219 if not self.cachevfs.exists(oid) and not isinstance(
220 self.cachevfs, nullvfs
221 ):
222 self.ui.note(_(b'lfs: adding %s to the usercache\n') % oid)
223 lfutil.link(self.vfs.join(oid), self.cachevfs.join(oid))
224
225 def read(self, oid, verify=True):
226 """Read blob from local blobstore."""
227 if not self.vfs.exists(oid):
228 blob = self._read(self.cachevfs, oid, verify)
229
230 # Even if revlog will verify the content, it needs to be verified
231 # now before making the hardlink to avoid propagating corrupt blobs.
232 # Don't abort if corruption is detected, because `hg verify` will
233 # give more useful info about the corruption- simply don't add the
234 # hardlink.
235 if verify or hex(hashlib.sha256(blob).digest()) == oid:
236 self.ui.note(_(b'lfs: found %s in the usercache\n') % oid)
237 lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid))
238 else:
239 self.ui.note(_(b'lfs: found %s in the local lfs store\n') % oid)
240 blob = self._read(self.vfs, oid, verify)
241 return blob
242
243 def _read(self, vfs, oid, verify):
244 """Read blob (after verifying) from the given store"""
245 blob = vfs.read(oid)
246 if verify:
247 _verify(oid, blob)
248 return blob
249
250 def verify(self, oid):
251 """Indicate whether or not the hash of the underlying file matches its
252 name."""
253 sha256 = hashlib.sha256()
254
255 with self.open(oid) as fp:
256 for chunk in util.filechunkiter(fp, size=1048576):
257 sha256.update(chunk)
258
259 return oid == hex(sha256.digest())
260
261 def has(self, oid):
262 """Returns True if the local blobstore contains the requested blob,
263 False otherwise."""
264 return self.cachevfs.exists(oid) or self.vfs.exists(oid)
265
266
267 def _urlerrorreason(urlerror):
268 """Create a friendly message for the given URLError to be used in an
269 LfsRemoteError message.
270 """
271 inst = urlerror
272
273 if isinstance(urlerror.reason, Exception):
274 inst = urlerror.reason
275
276 if hasattr(inst, 'reason'):
277 try: # usually it is in the form (errno, strerror)
278 reason = inst.reason.args[1]
279 except (AttributeError, IndexError):
280 # it might be anything, for example a string
281 reason = inst.reason
282 if isinstance(reason, str):
283 # SSLError of Python 2.7.9 contains a unicode
284 reason = encoding.unitolocal(reason)
285 return reason
286 elif getattr(inst, "strerror", None):
287 return encoding.strtolocal(inst.strerror)
288 else:
289 return stringutil.forcebytestr(urlerror)
290
291
292 class lfsauthhandler(util.urlreq.basehandler):
293 handler_order = 480 # Before HTTPDigestAuthHandler (== 490)
294
295 def http_error_401(self, req, fp, code, msg, headers):
296 """Enforces that any authentication performed is HTTP Basic
297 Authentication. No authentication is also acceptable.
298 """
299 authreq = headers.get('www-authenticate', None)
300 if authreq:
301 scheme = authreq.split()[0]
302
303 if scheme.lower() != 'basic':
304 msg = _(b'the server must support Basic Authentication')
305 raise util.urlerr.httperror(
306 req.get_full_url(),
307 code,
308 encoding.strfromlocal(msg),
309 headers,
310 fp,
311 )
312 return None
313
314
315 class _gitlfsremote:
316 def __init__(self, repo, url):
317 ui = repo.ui
318 self.ui = ui
319 baseurl, authinfo = url.authinfo()
320 self.baseurl = baseurl.rstrip(b'/')
321 useragent = repo.ui.config(b'experimental', b'lfs.user-agent')
322 if not useragent:
323 useragent = b'git-lfs/2.3.4 (Mercurial %s)' % util.version()
324 self.urlopener = urlmod.opener(ui, authinfo, useragent)
325 self.urlopener.add_handler(lfsauthhandler())
326 self.retry = ui.configint(b'lfs', b'retry')
327
328 def writebatch(self, pointers, fromstore):
329 """Batch upload from local to remote blobstore."""
330 self._batch(_deduplicate(pointers), fromstore, b'upload')
331
332 def readbatch(self, pointers, tostore):
333 """Batch download from remote to local blostore."""
334 self._batch(_deduplicate(pointers), tostore, b'download')
335
336 def _batchrequest(self, pointers, action):
337 """Get metadata about objects pointed by pointers for given action
338
339 Return decoded JSON object like {'objects': [{'oid': '', 'size': 1}]}
340 See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
341 """
342 objects = [
343 {'oid': pycompat.strurl(p.oid()), 'size': p.size()}
344 for p in pointers
345 ]
346 requestdata = pycompat.bytesurl(
347 json.dumps(
348 {
349 'objects': objects,
350 'operation': pycompat.strurl(action),
351 }
352 )
353 )
354 url = b'%s/objects/batch' % self.baseurl
355 batchreq = util.urlreq.request(pycompat.strurl(url), data=requestdata)
356 batchreq.add_header('Accept', 'application/vnd.git-lfs+json')
357 batchreq.add_header('Content-Type', 'application/vnd.git-lfs+json')
358 try:
359 with contextlib.closing(self.urlopener.open(batchreq)) as rsp:
360 rawjson = rsp.read()
361 except util.urlerr.httperror as ex:
362 hints = {
363 400: _(
364 b'check that lfs serving is enabled on %s and "%s" is '
365 b'supported'
366 )
367 % (self.baseurl, action),
368 404: _(b'the "lfs.url" config may be used to override %s')
369 % self.baseurl,
370 }
371 hint = hints.get(ex.code, _(b'api=%s, action=%s') % (url, action))
372 raise LfsRemoteError(
373 _(b'LFS HTTP error: %s') % stringutil.forcebytestr(ex),
374 hint=hint,
375 )
376 except util.urlerr.urlerror as ex:
377 hint = (
378 _(b'the "lfs.url" config may be used to override %s')
379 % self.baseurl
380 )
381 raise LfsRemoteError(
382 _(b'LFS error: %s') % _urlerrorreason(ex), hint=hint
383 )
384 try:
385 response = pycompat.json_loads(rawjson)
386 except ValueError:
387 raise LfsRemoteError(
388 _(b'LFS server returns invalid JSON: %s') % rawjson
389 )
390
391 if self.ui.debugflag:
392 self.ui.debug(b'Status: %d\n' % rsp.status)
393 # lfs-test-server and hg serve return headers in different order
394 headers = pycompat.bytestr(rsp.info()).strip()
395 self.ui.debug(b'%s\n' % b'\n'.join(sorted(headers.splitlines())))
396
397 if 'objects' in response:
398 response['objects'] = sorted(
399 response['objects'], key=lambda p: p['oid']
400 )
401 self.ui.debug(
402 b'%s\n'
403 % pycompat.bytesurl(
404 json.dumps(
405 response,
406 indent=2,
407 separators=('', ': '),
408 sort_keys=True,
409 )
410 )
411 )
412
413 def encodestr(x):
414 if isinstance(x, str):
415 return x.encode('utf-8')
416 return x
417
418 return pycompat.rapply(encodestr, response)
419
420 def _checkforservererror(self, pointers, responses, action):
421 """Scans errors from objects
422
423 Raises LfsRemoteError if any objects have an error"""
424 for response in responses:
425 # The server should return 404 when objects cannot be found. Some
426 # server implementation (ex. lfs-test-server) does not set "error"
427 # but just removes "download" from "actions". Treat that case
428 # as the same as 404 error.
429 if b'error' not in response:
430 if action == b'download' and action not in response.get(
431 b'actions', []
432 ):
433 code = 404
434 else:
435 continue
436 else:
437 # An error dict without a code doesn't make much sense, so
438 # treat as a server error.
439 code = response.get(b'error').get(b'code', 500)
440
441 ptrmap = {p.oid(): p for p in pointers}
442 p = ptrmap.get(response[b'oid'], None)
443 if p:
444 filename = getattr(p, 'filename', b'unknown')
445 errors = {
446 404: b'The object does not exist',
447 410: b'The object was removed by the owner',
448 422: b'Validation error',
449 500: b'Internal server error',
450 }
451 msg = errors.get(code, b'status code %d' % code)
452 raise LfsRemoteError(
453 _(b'LFS server error for "%s": %s') % (filename, msg)
454 )
455 else:
456 raise LfsRemoteError(
457 _(b'LFS server error. Unsolicited response for oid %s')
458 % response[b'oid']
459 )
460
461 def _extractobjects(self, response, pointers, action):
462 """extract objects from response of the batch API
463
464 response: parsed JSON object returned by batch API
465 return response['objects'] filtered by action
466 raise if any object has an error
467 """
468 # Scan errors from objects - fail early
469 objects = response.get(b'objects', [])
470 self._checkforservererror(pointers, objects, action)
471
472 # Filter objects with given action. Practically, this skips uploading
473 # objects which exist in the server.
474 filteredobjects = [
475 o for o in objects if action in o.get(b'actions', [])
476 ]
477
478 return filteredobjects
479
480 def _basictransfer(self, obj, action, localstore):
481 """Download or upload a single object using basic transfer protocol
482
483 obj: dict, an object description returned by batch API
484 action: string, one of ['upload', 'download']
485 localstore: blobstore.local
486
487 See https://github.com/git-lfs/git-lfs/blob/master/docs/api/\
488 basic-transfers.md
489 """
490 oid = obj[b'oid']
491 href = obj[b'actions'][action].get(b'href')
492 headers = obj[b'actions'][action].get(b'header', {}).items()
493
494 request = util.urlreq.request(pycompat.strurl(href))
495 if action == b'upload':
496 # If uploading blobs, read data from local blobstore.
497 if not localstore.verify(oid):
498 raise error.Abort(
499 _(b'detected corrupt lfs object: %s') % oid,
500 hint=_(b'run hg verify'),
501 )
502
503 for k, v in headers:
504 request.add_header(pycompat.strurl(k), pycompat.strurl(v))
505
506 try:
507 if action == b'upload':
508 request.data = lfsuploadfile(self.ui, localstore.path(oid))
509 request.get_method = lambda: 'PUT'
510 request.add_header('Content-Type', 'application/octet-stream')
511 request.add_header('Content-Length', request.data.length)
512
513 with contextlib.closing(self.urlopener.open(request)) as res:
514 contentlength = res.info().get("content-length")
515 ui = self.ui # Shorten debug lines
516 if self.ui.debugflag:
517 ui.debug(b'Status: %d\n' % res.status)
518 # lfs-test-server and hg serve return headers in different
519 # order
520 headers = pycompat.bytestr(res.info()).strip()
521 ui.debug(b'%s\n' % b'\n'.join(sorted(headers.splitlines())))
522
523 if action == b'download':
524 # If downloading blobs, store downloaded data to local
525 # blobstore
526 localstore.download(oid, res, contentlength)
527 else:
528 blocks = []
529 while True:
530 data = res.read(1048576)
531 if not data:
532 break
533 blocks.append(data)
534
535 response = b"".join(blocks)
536 if response:
537 ui.debug(b'lfs %s response: %s' % (action, response))
538 except util.urlerr.httperror as ex:
539 if self.ui.debugflag:
540 self.ui.debug(
541 b'%s: %s\n' % (oid, ex.read())
542 ) # XXX: also bytes?
543 raise LfsRemoteError(
544 _(b'LFS HTTP error: %s (oid=%s, action=%s)')
545 % (stringutil.forcebytestr(ex), oid, action)
546 )
547 except util.urlerr.urlerror as ex:
548 hint = _(b'attempted connection to %s') % pycompat.bytesurl(
549 util.urllibcompat.getfullurl(request)
550 )
551 raise LfsRemoteError(
552 _(b'LFS error: %s') % _urlerrorreason(ex), hint=hint
553 )
554 finally:
555 if request.data:
556 request.data.close()
557
558 def _batch(self, pointers, localstore, action):
559 if action not in [b'upload', b'download']:
560 raise error.ProgrammingError(b'invalid Git-LFS action: %s' % action)
561
562 response = self._batchrequest(pointers, action)
563 objects = self._extractobjects(response, pointers, action)
564 total = sum(x.get(b'size', 0) for x in objects)
565 sizes = {}
566 for obj in objects:
567 sizes[obj.get(b'oid')] = obj.get(b'size', 0)
568 topic = {
569 b'upload': _(b'lfs uploading'),
570 b'download': _(b'lfs downloading'),
571 }[action]
572 if len(objects) > 1:
573 self.ui.note(
574 _(b'lfs: need to transfer %d objects (%s)\n')
575 % (len(objects), util.bytecount(total))
576 )
577
578 def transfer(chunk):
579 for obj in chunk:
580 objsize = obj.get(b'size', 0)
581 if self.ui.verbose:
582 if action == b'download':
583 msg = _(b'lfs: downloading %s (%s)\n')
584 elif action == b'upload':
585 msg = _(b'lfs: uploading %s (%s)\n')
586 self.ui.note(
587 msg % (obj.get(b'oid'), util.bytecount(objsize))
588 )
589 retry = self.retry
590 while True:
591 try:
592 self._basictransfer(obj, action, localstore)
593 yield 1, obj.get(b'oid')
594 break
595 except OSError as ex:
596 if retry > 0:
597 self.ui.note(
598 _(b'lfs: failed: %r (remaining retry %d)\n')
599 % (stringutil.forcebytestr(ex), retry)
600 )
601 retry -= 1
602 continue
603 raise
604
605 # Until https multiplexing gets sorted out. It's not clear if
606 # ConnectionManager.set_ready() is externally synchronized for thread
607 # safety with Windows workers.
608 if self.ui.configbool(b'experimental', b'lfs.worker-enable'):
609 # The POSIX workers are forks of this process, so before spinning
610 # them up, close all pooled connections. Otherwise, there's no way
611 # to coordinate between them about who is using what, and the
612 # transfers will get corrupted.
613 #
614 # TODO: add a function to keepalive.ConnectionManager to mark all
615 # ready connections as in use, and roll that back after the fork?
616 # That would allow the existing pool of connections in this process
617 # to be preserved.
618 def prefork():
619 for h in self.urlopener.handlers:
620 getattr(h, "close_all", lambda: None)()
621
622 oids = worker.worker(
623 self.ui,
624 0.1,
625 transfer,
626 (),
627 sorted(objects, key=lambda o: o.get(b'oid')),
628 prefork=prefork,
629 )
630 else:
631 oids = transfer(sorted(objects, key=lambda o: o.get(b'oid')))
632
633 with self.ui.makeprogress(
634 topic, unit=_(b"bytes"), total=total
635 ) as progress:
636 progress.update(0)
637 processed = 0
638 blobs = 0
639 for _one, oid in oids:
640 processed += sizes[oid]
641 blobs += 1
642 progress.update(processed)
643 self.ui.note(_(b'lfs: processed: %s\n') % oid)
644
645 if blobs > 0:
646 if action == b'upload':
647 self.ui.status(
648 _(b'lfs: uploaded %d files (%s)\n')
649 % (blobs, util.bytecount(processed))
650 )
651 elif action == b'download':
652 self.ui.status(
653 _(b'lfs: downloaded %d files (%s)\n')
654 % (blobs, util.bytecount(processed))
655 )
656
657 def __del__(self):
658 # copied from mercurial/httppeer.py
659 urlopener = getattr(self, 'urlopener', None)
660 if urlopener:
661 for h in urlopener.handlers:
662 h.close()
663 getattr(h, "close_all", lambda: None)()
664
665
666 class _dummyremote:
667 """Dummy store storing blobs to temp directory."""
668
669 def __init__(self, repo, url):
670 fullpath = repo.vfs.join(b'lfs', url.path)
671 self.vfs = lfsvfs(fullpath)
672
673 def writebatch(self, pointers, fromstore):
674 for p in _deduplicate(pointers):
675 content = fromstore.read(p.oid(), verify=True)
676 with self.vfs(p.oid(), b'wb', atomictemp=True) as fp:
677 fp.write(content)
678
679 def readbatch(self, pointers, tostore):
680 for p in _deduplicate(pointers):
681 with self.vfs(p.oid(), b'rb') as fp:
682 tostore.download(p.oid(), fp, None)
683
684
685 class _nullremote:
686 """Null store storing blobs to /dev/null."""
687
688 def __init__(self, repo, url):
689 pass
690
691 def writebatch(self, pointers, fromstore):
692 pass
693
694 def readbatch(self, pointers, tostore):
695 pass
696
697
698 class _promptremote:
699 """Prompt user to set lfs.url when accessed."""
700
701 def __init__(self, repo, url):
702 pass
703
704 def writebatch(self, pointers, fromstore, ui=None):
705 self._prompt()
706
707 def readbatch(self, pointers, tostore, ui=None):
708 self._prompt()
709
710 def _prompt(self):
711 raise error.Abort(_(b'lfs.url needs to be configured'))
712
713
714 _storemap = {
715 b'https': _gitlfsremote,
716 b'http': _gitlfsremote,
717 b'file': _dummyremote,
718 b'null': _nullremote,
719 None: _promptremote,
720 }
721
722
723 def _deduplicate(pointers):
724 """Remove any duplicate oids that exist in the list"""
725 reduced = util.sortdict()
726 for p in pointers:
727 reduced[p.oid()] = p
728 return reduced.values()
729
730
731 def _verify(oid, content):
732 realoid = hex(hashlib.sha256(content).digest())
733 if realoid != oid:
734 raise LfsCorruptionError(
735 _(b'detected corrupt lfs object: %s') % oid,
736 hint=_(b'run hg verify'),
737 )
738
739
740 def remote(repo, remote=None):
741 """remotestore factory. return a store in _storemap depending on config
742
743 If ``lfs.url`` is specified, use that remote endpoint. Otherwise, try to
744 infer the endpoint, based on the remote repository using the same path
745 adjustments as git. As an extension, 'http' is supported as well so that
746 ``hg serve`` works out of the box.
747
748 https://github.com/git-lfs/git-lfs/blob/master/docs/api/server-discovery.md
749 """
750 lfsurl = repo.ui.config(b'lfs', b'url')
751 url = urlutil.url(lfsurl or b'')
752 if lfsurl is None:
753 if remote:
754 path = remote
755 elif hasattr(repo, '_subtoppath'):
756 # The pull command sets this during the optional update phase, which
757 # tells exactly where the pull originated, whether 'paths.default'
758 # or explicit.
759 path = repo._subtoppath
760 else:
761 # TODO: investigate 'paths.remote:lfsurl' style path customization,
762 # and fall back to inferring from 'paths.remote' if unspecified.
763 path = repo.ui.config(b'paths', b'default') or b''
764
765 defaulturl = urlutil.url(path)
766
767 # TODO: support local paths as well.
768 # TODO: consider the ssh -> https transformation that git applies
769 if defaulturl.scheme in (b'http', b'https'):
770 if defaulturl.path and defaulturl.path[:-1] != b'/':
771 defaulturl.path += b'/'
772 defaulturl.path = (defaulturl.path or b'') + b'.git/info/lfs'
773
774 url = urlutil.url(bytes(defaulturl))
775 repo.ui.note(_(b'lfs: assuming remote store: %s\n') % url)
776
777 scheme = url.scheme
778 if scheme not in _storemap:
779 raise error.Abort(_(b'lfs: unknown url scheme: %s') % scheme)
780 return _storemap[scheme](repo, url)
781
782
783 class LfsRemoteError(error.StorageError):
784 pass
785
786
787 class LfsCorruptionError(error.Abort):
788 """Raised when a corrupt blob is detected, aborting an operation
789
790 It exists to allow specialized handling on the server side."""