2
0

lfs.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # lfs.py -- Implementation of the LFS
  2. # Copyright (C) 2020 Jelmer Vernooij
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. import hashlib
  22. import os
  23. import tempfile
  24. class LFSStore:
  25. """Stores objects on disk, indexed by SHA256."""
  26. def __init__(self, path) -> None:
  27. self.path = path
  28. @classmethod
  29. def create(cls, lfs_dir):
  30. if not os.path.isdir(lfs_dir):
  31. os.mkdir(lfs_dir)
  32. os.mkdir(os.path.join(lfs_dir, "tmp"))
  33. os.mkdir(os.path.join(lfs_dir, "objects"))
  34. return cls(lfs_dir)
  35. @classmethod
  36. def from_repo(cls, repo, create=False):
  37. lfs_dir = os.path.join(repo.controldir, "lfs")
  38. if create:
  39. return cls.create(lfs_dir)
  40. return cls(lfs_dir)
  41. def _sha_path(self, sha):
  42. return os.path.join(self.path, "objects", sha[0:2], sha[2:4], sha)
  43. def open_object(self, sha):
  44. """Open an object by sha."""
  45. try:
  46. return open(self._sha_path(sha), "rb")
  47. except FileNotFoundError as exc:
  48. raise KeyError(sha) from exc
  49. def write_object(self, chunks):
  50. """Write an object.
  51. Returns: object SHA
  52. """
  53. sha = hashlib.sha256()
  54. tmpdir = os.path.join(self.path, "tmp")
  55. with tempfile.NamedTemporaryFile(dir=tmpdir, mode="wb", delete=False) as f:
  56. for chunk in chunks:
  57. sha.update(chunk)
  58. f.write(chunk)
  59. f.flush()
  60. tmppath = f.name
  61. path = self._sha_path(sha.hexdigest())
  62. if not os.path.exists(os.path.dirname(path)):
  63. os.makedirs(os.path.dirname(path))
  64. os.rename(tmppath, path)
  65. return sha.hexdigest()