tree.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. __all__ = ["TreeModifier", "Tree"]
  6. import os
  7. import sys
  8. import git.diff as git_diff
  9. from git.util import IterableList, join_path, to_bin_sha
  10. from . import util
  11. from .base import IndexObjUnion, IndexObject
  12. from .blob import Blob
  13. from .fun import tree_entries_from_data, tree_to_stream
  14. from .submodule.base import Submodule
  15. # typing -------------------------------------------------
  16. from typing import (
  17. Any,
  18. Callable,
  19. Dict,
  20. Iterable,
  21. Iterator,
  22. List,
  23. Tuple,
  24. TYPE_CHECKING,
  25. Type,
  26. Union,
  27. cast,
  28. )
  29. if sys.version_info >= (3, 8):
  30. from typing import Literal
  31. else:
  32. from typing_extensions import Literal
  33. from git.types import PathLike
  34. if TYPE_CHECKING:
  35. from io import BytesIO
  36. from git.repo import Repo
  37. TreeCacheTup = Tuple[bytes, int, str]
  38. TraversedTreeTup = Union[Tuple[Union["Tree", None], IndexObjUnion, Tuple["Submodule", "Submodule"]]]
  39. # --------------------------------------------------------
  40. def cmp(a: str, b: str) -> int:
  41. return (a > b) - (a < b)
  42. class TreeModifier:
  43. """A utility class providing methods to alter the underlying cache in a list-like
  44. fashion.
  45. Once all adjustments are complete, the :attr:`_cache`, which really is a reference
  46. to the cache of a tree, will be sorted. This ensures it will be in a serializable
  47. state.
  48. """
  49. __slots__ = ("_cache",)
  50. def __init__(self, cache: List[TreeCacheTup]) -> None:
  51. self._cache = cache
  52. def _index_by_name(self, name: str) -> int:
  53. """:return: index of an item with name, or -1 if not found"""
  54. for i, t in enumerate(self._cache):
  55. if t[2] == name:
  56. return i
  57. # END found item
  58. # END for each item in cache
  59. return -1
  60. # { Interface
  61. def set_done(self) -> "TreeModifier":
  62. """Call this method once you are done modifying the tree information.
  63. This may be called several times, but be aware that each call will cause a sort
  64. operation.
  65. :return:
  66. self
  67. """
  68. self._cache.sort(key=lambda x: (x[2] + "/") if x[1] == Tree.tree_id << 12 else x[2])
  69. return self
  70. # } END interface
  71. # { Mutators
  72. def add(self, sha: bytes, mode: int, name: str, force: bool = False) -> "TreeModifier":
  73. """Add the given item to the tree.
  74. If an item with the given name already exists, nothing will be done, but a
  75. :exc:`ValueError` will be raised if the sha and mode of the existing item do not
  76. match the one you add, unless `force` is ``True``.
  77. :param sha:
  78. The 20 or 40 byte sha of the item to add.
  79. :param mode:
  80. :class:`int` representing the stat-compatible mode of the item.
  81. :param force:
  82. If ``True``, an item with your name and information will overwrite any
  83. existing item with the same name, no matter which information it has.
  84. :return:
  85. self
  86. """
  87. if "/" in name:
  88. raise ValueError("Name must not contain '/' characters")
  89. if (mode >> 12) not in Tree._map_id_to_type:
  90. raise ValueError("Invalid object type according to mode %o" % mode)
  91. sha = to_bin_sha(sha)
  92. index = self._index_by_name(name)
  93. item = (sha, mode, name)
  94. if index == -1:
  95. self._cache.append(item)
  96. else:
  97. if force:
  98. self._cache[index] = item
  99. else:
  100. ex_item = self._cache[index]
  101. if ex_item[0] != sha or ex_item[1] != mode:
  102. raise ValueError("Item %r existed with different properties" % name)
  103. # END handle mismatch
  104. # END handle force
  105. # END handle name exists
  106. return self
  107. def add_unchecked(self, binsha: bytes, mode: int, name: str) -> None:
  108. """Add the given item to the tree. Its correctness is assumed, so it is the
  109. caller's responsibility to ensure that the input is correct.
  110. For more information on the parameters, see :meth:`add`.
  111. :param binsha:
  112. 20 byte binary sha.
  113. """
  114. assert isinstance(binsha, bytes) and isinstance(mode, int) and isinstance(name, str)
  115. tree_cache = (binsha, mode, name)
  116. self._cache.append(tree_cache)
  117. def __delitem__(self, name: str) -> None:
  118. """Delete an item with the given name if it exists."""
  119. index = self._index_by_name(name)
  120. if index > -1:
  121. del self._cache[index]
  122. # } END mutators
  123. class Tree(IndexObject, git_diff.Diffable, util.Traversable, util.Serializable):
  124. R"""Tree objects represent an ordered list of :class:`~git.objects.blob.Blob`\s and
  125. other :class:`Tree`\s.
  126. See :manpage:`gitglossary(7)` on "tree object":
  127. https://git-scm.com/docs/gitglossary#def_tree_object
  128. Subscripting is supported, as with a list or dict:
  129. * Access a specific blob using the ``tree["filename"]`` notation.
  130. * You may likewise access by index, like ``blob = tree[0]``.
  131. """
  132. type: Literal["tree"] = "tree"
  133. __slots__ = ("_cache",)
  134. # Actual integer IDs for comparison.
  135. commit_id = 0o16 # Equals stat.S_IFDIR | stat.S_IFLNK - a directory link.
  136. blob_id = 0o10
  137. symlink_id = 0o12
  138. tree_id = 0o04
  139. _map_id_to_type: Dict[int, Type[IndexObjUnion]] = {
  140. commit_id: Submodule,
  141. blob_id: Blob,
  142. symlink_id: Blob,
  143. # Tree ID added once Tree is defined.
  144. }
  145. def __init__(
  146. self,
  147. repo: "Repo",
  148. binsha: bytes,
  149. mode: int = tree_id << 12,
  150. path: Union[PathLike, None] = None,
  151. ):
  152. super().__init__(repo, binsha, mode, path)
  153. @classmethod
  154. def _get_intermediate_items(
  155. cls,
  156. index_object: IndexObjUnion,
  157. ) -> Union[Tuple["Tree", ...], Tuple[()]]:
  158. if index_object.type == "tree":
  159. return tuple(index_object._iter_convert_to_object(index_object._cache))
  160. return ()
  161. def _set_cache_(self, attr: str) -> None:
  162. if attr == "_cache":
  163. # Set the data when we need it.
  164. ostream = self.repo.odb.stream(self.binsha)
  165. self._cache: List[TreeCacheTup] = tree_entries_from_data(ostream.read())
  166. else:
  167. super()._set_cache_(attr)
  168. # END handle attribute
  169. def _iter_convert_to_object(self, iterable: Iterable[TreeCacheTup]) -> Iterator[IndexObjUnion]:
  170. """Iterable yields tuples of (binsha, mode, name), which will be converted to
  171. the respective object representation.
  172. """
  173. for binsha, mode, name in iterable:
  174. path = join_path(self.path, name)
  175. try:
  176. yield self._map_id_to_type[mode >> 12](self.repo, binsha, mode, path)
  177. except KeyError as e:
  178. raise TypeError("Unknown mode %o found in tree data for path '%s'" % (mode, path)) from e
  179. # END for each item
  180. def join(self, file: PathLike) -> IndexObjUnion:
  181. """Find the named object in this tree's contents.
  182. :return:
  183. :class:`~git.objects.blob.Blob`, :class:`Tree`, or
  184. :class:`~git.objects.submodule.base.Submodule`
  185. :raise KeyError:
  186. If the given file or tree does not exist in this tree.
  187. """
  188. msg = "Blob or Tree named %r not found"
  189. file = os.fspath(file)
  190. if "/" in file:
  191. tree = self
  192. item = self
  193. tokens = file.split("/")
  194. for i, token in enumerate(tokens):
  195. item = tree[token]
  196. if item.type == "tree":
  197. tree = item
  198. else:
  199. # Safety assertion - blobs are at the end of the path.
  200. if i != len(tokens) - 1:
  201. raise KeyError(msg % file)
  202. return item
  203. # END handle item type
  204. # END for each token of split path
  205. if item == self:
  206. raise KeyError(msg % file)
  207. return item
  208. else:
  209. for info in self._cache:
  210. if info[2] == file: # [2] == name
  211. return self._map_id_to_type[info[1] >> 12](
  212. self.repo, info[0], info[1], join_path(self.path, info[2])
  213. )
  214. # END for each obj
  215. raise KeyError(msg % file)
  216. # END handle long paths
  217. def __truediv__(self, file: PathLike) -> IndexObjUnion:
  218. """The ``/`` operator is another syntax for joining.
  219. See :meth:`join` for details.
  220. """
  221. return self.join(file)
  222. @property
  223. def trees(self) -> List["Tree"]:
  224. """:return: list(Tree, ...) List of trees directly below this tree"""
  225. return [i for i in self if i.type == "tree"]
  226. @property
  227. def blobs(self) -> List[Blob]:
  228. """:return: list(Blob, ...) List of blobs directly below this tree"""
  229. return [i for i in self if i.type == "blob"]
  230. @property
  231. def cache(self) -> TreeModifier:
  232. """
  233. :return:
  234. An object allowing modification of the internal cache. This can be used to
  235. change the tree's contents. When done, make sure you call
  236. :meth:`~TreeModifier.set_done` on the tree modifier, or serialization
  237. behaviour will be incorrect.
  238. :note:
  239. See :class:`TreeModifier` for more information on how to alter the cache.
  240. """
  241. return TreeModifier(self._cache)
  242. def traverse(
  243. self,
  244. predicate: Callable[[Union[IndexObjUnion, TraversedTreeTup], int], bool] = lambda i, d: True,
  245. prune: Callable[[Union[IndexObjUnion, TraversedTreeTup], int], bool] = lambda i, d: False,
  246. depth: int = -1,
  247. branch_first: bool = True,
  248. visit_once: bool = False,
  249. ignore_self: int = 1,
  250. as_edge: bool = False,
  251. ) -> Union[Iterator[IndexObjUnion], Iterator[TraversedTreeTup]]:
  252. """For documentation, see
  253. `Traversable._traverse() <git.objects.util.Traversable._traverse>`.
  254. Trees are set to ``visit_once = False`` to gain more performance in the
  255. traversal.
  256. """
  257. # # To typecheck instead of using cast.
  258. # import itertools
  259. # def is_tree_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Union['Tree', 'Blob', 'Submodule']]]]:
  260. # return all(isinstance(x, (Blob, Tree, Submodule)) for x in inp[1])
  261. # ret = super().traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)
  262. # ret_tup = itertools.tee(ret, 2)
  263. # assert is_tree_traversed(ret_tup), f"Type is {[type(x) for x in list(ret_tup[0])]}"
  264. # return ret_tup[0]
  265. return cast(
  266. Union[Iterator[IndexObjUnion], Iterator[TraversedTreeTup]],
  267. super()._traverse(
  268. predicate, # type: ignore[arg-type]
  269. prune, # type: ignore[arg-type]
  270. depth,
  271. branch_first,
  272. visit_once,
  273. ignore_self,
  274. ),
  275. )
  276. def list_traverse(self, *args: Any, **kwargs: Any) -> IterableList[IndexObjUnion]:
  277. """
  278. :return:
  279. :class:`~git.util.IterableList` with the results of the traversal as
  280. produced by :meth:`traverse`
  281. Tree -> IterableList[Union[Submodule, Tree, Blob]]
  282. """
  283. return super()._list_traverse(*args, **kwargs)
  284. # List protocol
  285. def __getslice__(self, i: int, j: int) -> List[IndexObjUnion]:
  286. return list(self._iter_convert_to_object(self._cache[i:j]))
  287. def __iter__(self) -> Iterator[IndexObjUnion]:
  288. return self._iter_convert_to_object(self._cache)
  289. def __len__(self) -> int:
  290. return len(self._cache)
  291. def __getitem__(self, item: Union[str, int, slice]) -> IndexObjUnion:
  292. if isinstance(item, int):
  293. info = self._cache[item]
  294. return self._map_id_to_type[info[1] >> 12](self.repo, info[0], info[1], join_path(self.path, info[2]))
  295. if isinstance(item, str):
  296. # compatibility
  297. return self.join(item)
  298. # END index is basestring
  299. raise TypeError("Invalid index type: %r" % item)
  300. def __contains__(self, item: Union[IndexObjUnion, PathLike]) -> bool:
  301. if isinstance(item, IndexObject):
  302. for info in self._cache:
  303. if item.binsha == info[0]:
  304. return True
  305. # END compare sha
  306. # END for each entry
  307. # END handle item is index object
  308. # compatibility
  309. # Treat item as repo-relative path.
  310. else:
  311. path = self.path
  312. for info in self._cache:
  313. if item == join_path(path, info[2]):
  314. return True
  315. # END for each item
  316. return False
  317. def __reversed__(self) -> Iterator[IndexObjUnion]:
  318. return reversed(self._iter_convert_to_object(self._cache)) # type: ignore[call-overload]
  319. def _serialize(self, stream: "BytesIO") -> "Tree":
  320. """Serialize this tree into the stream. Assumes sorted tree data.
  321. :note:
  322. We will assume our tree data to be in a sorted state. If this is not the
  323. case, serialization will not generate a correct tree representation as these
  324. are assumed to be sorted by algorithms.
  325. """
  326. tree_to_stream(self._cache, stream.write)
  327. return self
  328. def _deserialize(self, stream: "BytesIO") -> "Tree":
  329. self._cache = tree_entries_from_data(stream.read())
  330. return self
  331. # END tree
  332. # Finalize map definition.
  333. Tree._map_id_to_type[Tree.tree_id] = Tree