db.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # This module is part of GitPython and is released under the
  2. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  3. """Module with our own gitdb implementation - it uses the git command."""
  4. __all__ = ["GitCmdObjectDB", "GitDB"]
  5. from gitdb.base import OInfo, OStream
  6. from gitdb.db import GitDB, LooseObjectDB
  7. from gitdb.exc import BadObject
  8. from git.util import bin_to_hex, hex_to_bin
  9. from git.exc import GitCommandError
  10. # typing-------------------------------------------------
  11. from typing import TYPE_CHECKING
  12. from git.types import PathLike
  13. if TYPE_CHECKING:
  14. from git.cmd import Git
  15. # --------------------------------------------------------
  16. class GitCmdObjectDB(LooseObjectDB):
  17. """A database representing the default git object store, which includes loose
  18. objects, pack files and an alternates file.
  19. It will create objects only in the loose object database.
  20. """
  21. def __init__(self, root_path: PathLike, git: "Git") -> None:
  22. """Initialize this instance with the root and a git command."""
  23. super().__init__(root_path)
  24. self._git = git
  25. def info(self, binsha: bytes) -> OInfo:
  26. """Get a git object header (using git itself)."""
  27. hexsha, typename, size = self._git.get_object_header(bin_to_hex(binsha))
  28. return OInfo(hex_to_bin(hexsha), typename, size)
  29. def stream(self, binsha: bytes) -> OStream:
  30. """Get git object data as a stream supporting ``read()`` (using git itself)."""
  31. hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(binsha))
  32. return OStream(hex_to_bin(hexsha), typename, size, stream)
  33. # { Interface
  34. def partial_to_complete_sha_hex(self, partial_hexsha: str) -> bytes:
  35. """
  36. :return:
  37. Full binary 20 byte sha from the given partial hexsha
  38. :raise gitdb.exc.AmbiguousObjectName:
  39. :raise gitdb.exc.BadObject:
  40. :note:
  41. Currently we only raise :exc:`~gitdb.exc.BadObject` as git does not
  42. communicate ambiguous objects separately.
  43. """
  44. try:
  45. hexsha, _typename, _size = self._git.get_object_header(partial_hexsha)
  46. return hex_to_bin(hexsha)
  47. except (GitCommandError, ValueError) as e:
  48. raise BadObject(partial_hexsha) from e
  49. # END handle exceptions
  50. # } END interface