lfs.py 2.4 KB

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