util.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. """Utility functions for working with git objects."""
  6. __all__ = [
  7. "get_object_type_by_name",
  8. "parse_date",
  9. "parse_actor_and_date",
  10. "ProcessStreamAdapter",
  11. "Traversable",
  12. "altz_to_utctz_str",
  13. "utctz_to_altz",
  14. "verify_utctz",
  15. "Actor",
  16. "tzoffset",
  17. "utc",
  18. ]
  19. from abc import ABC, abstractmethod
  20. import calendar
  21. from collections import deque
  22. from datetime import datetime, timedelta, tzinfo
  23. import re
  24. from string import digits
  25. import time
  26. import warnings
  27. from git.util import Actor, IterableList, IterableObj
  28. # typing ------------------------------------------------------------
  29. from typing import (
  30. Any,
  31. Callable,
  32. Deque,
  33. Iterator,
  34. NamedTuple,
  35. Sequence,
  36. TYPE_CHECKING,
  37. Tuple,
  38. Type,
  39. TypeVar,
  40. Union,
  41. cast,
  42. overload,
  43. )
  44. from git.types import Has_id_attribute, Literal
  45. if TYPE_CHECKING:
  46. from io import BytesIO, StringIO
  47. from subprocess import Popen
  48. from git.types import Protocol, runtime_checkable
  49. from .blob import Blob
  50. from .commit import Commit
  51. from .submodule.base import Submodule
  52. from .tag import TagObject
  53. from .tree import TraversedTreeTup, Tree
  54. else:
  55. Protocol = ABC
  56. def runtime_checkable(f):
  57. return f
  58. class TraverseNT(NamedTuple):
  59. depth: int
  60. item: Union["Traversable", "Blob"]
  61. src: Union["Traversable", None]
  62. T_TIobj = TypeVar("T_TIobj", bound="TraversableIterableObj") # For TraversableIterableObj.traverse()
  63. TraversedTup = Union[
  64. Tuple[Union["Traversable", None], "Traversable"], # For Commit, Submodule.
  65. "TraversedTreeTup", # For Tree.traverse().
  66. ]
  67. # --------------------------------------------------------------------
  68. ZERO = timedelta(0)
  69. # { Functions
  70. def mode_str_to_int(modestr: Union[bytes, str]) -> int:
  71. """Convert mode bits from an octal mode string to an integer mode for git.
  72. :param modestr:
  73. String like ``755`` or ``644`` or ``100644`` - only the last 6 chars will be
  74. used.
  75. :return:
  76. String identifying a mode compatible to the mode methods ids of the :mod:`stat`
  77. module regarding the rwx permissions for user, group and other, special flags
  78. and file system flags, such as whether it is a symlink.
  79. """
  80. mode = 0
  81. for iteration, char in enumerate(reversed(modestr[-6:])):
  82. char = cast(Union[str, int], char)
  83. mode += int(char) << iteration * 3
  84. # END for each char
  85. return mode
  86. def get_object_type_by_name(
  87. object_type_name: bytes,
  88. ) -> Union[Type["Commit"], Type["TagObject"], Type["Tree"], Type["Blob"]]:
  89. """Retrieve the Python class GitPython uses to represent a kind of Git object.
  90. :return:
  91. A type suitable to handle the given as `object_type_name`.
  92. This type can be called create new instances.
  93. :param object_type_name:
  94. Member of :attr:`Object.TYPES <git.objects.base.Object.TYPES>`.
  95. :raise ValueError:
  96. If `object_type_name` is unknown.
  97. """
  98. if object_type_name == b"commit":
  99. from . import commit
  100. return commit.Commit
  101. elif object_type_name == b"tag":
  102. from . import tag
  103. return tag.TagObject
  104. elif object_type_name == b"blob":
  105. from . import blob
  106. return blob.Blob
  107. elif object_type_name == b"tree":
  108. from . import tree
  109. return tree.Tree
  110. else:
  111. raise ValueError("Cannot handle unknown object type: %s" % object_type_name.decode())
  112. def utctz_to_altz(utctz: str) -> int:
  113. """Convert a git timezone offset into a timezone offset west of UTC in seconds
  114. (compatible with :attr:`time.altzone`).
  115. :param utctz:
  116. git utc timezone string, e.g. +0200
  117. """
  118. int_utctz = int(utctz)
  119. seconds = (abs(int_utctz) // 100) * 3600 + (abs(int_utctz) % 100) * 60
  120. return seconds if int_utctz < 0 else -seconds
  121. def altz_to_utctz_str(altz: float) -> str:
  122. """Convert a timezone offset west of UTC in seconds into a Git timezone offset
  123. string.
  124. :param altz:
  125. Timezone offset in seconds west of UTC.
  126. """
  127. hours = abs(altz) // 3600
  128. minutes = (abs(altz) % 3600) // 60
  129. sign = "-" if altz >= 60 else "+"
  130. return "{}{:02}{:02}".format(sign, hours, minutes)
  131. def verify_utctz(offset: str) -> str:
  132. """
  133. :raise ValueError:
  134. If `offset` is incorrect.
  135. :return:
  136. `offset`
  137. """
  138. fmt_exc = ValueError("Invalid timezone offset format: %s" % offset)
  139. if len(offset) != 5:
  140. raise fmt_exc
  141. if offset[0] not in "+-":
  142. raise fmt_exc
  143. if offset[1] not in digits or offset[2] not in digits or offset[3] not in digits or offset[4] not in digits:
  144. raise fmt_exc
  145. # END for each char
  146. return offset
  147. class tzoffset(tzinfo):
  148. def __init__(self, secs_west_of_utc: float, name: Union[None, str] = None) -> None:
  149. self._offset = timedelta(seconds=-secs_west_of_utc)
  150. self._name = name or "fixed"
  151. def __reduce__(self) -> Tuple[Type["tzoffset"], Tuple[float, str]]:
  152. return tzoffset, (-self._offset.total_seconds(), self._name)
  153. def utcoffset(self, dt: Union[datetime, None]) -> timedelta:
  154. return self._offset
  155. def tzname(self, dt: Union[datetime, None]) -> str:
  156. return self._name
  157. def dst(self, dt: Union[datetime, None]) -> timedelta:
  158. return ZERO
  159. utc = tzoffset(0, "UTC")
  160. def from_timestamp(timestamp: float, tz_offset: float) -> datetime:
  161. """Convert a `timestamp` + `tz_offset` into an aware :class:`~datetime.datetime`
  162. instance."""
  163. utc_dt = datetime.fromtimestamp(timestamp, utc)
  164. try:
  165. local_dt = utc_dt.astimezone(tzoffset(tz_offset))
  166. return local_dt
  167. except ValueError:
  168. return utc_dt
  169. def parse_date(string_date: Union[str, datetime]) -> Tuple[int, int]:
  170. """Parse the given date as one of the following:
  171. * Aware datetime instance
  172. * Git internal format: timestamp offset
  173. * :rfc:`2822`: ``Thu, 07 Apr 2005 22:13:13 +0200``
  174. * ISO 8601: ``2005-04-07T22:13:13`` - The ``T`` can be a space as well.
  175. :return:
  176. Tuple(int(timestamp_UTC), int(offset)), both in seconds since epoch
  177. :raise ValueError:
  178. If the format could not be understood.
  179. :note:
  180. Date can also be ``YYYY.MM.DD``, ``MM/DD/YYYY`` and ``DD.MM.YYYY``.
  181. """
  182. if isinstance(string_date, datetime):
  183. if string_date.tzinfo:
  184. utcoffset = cast(timedelta, string_date.utcoffset()) # typeguard, if tzinfoand is not None
  185. offset = -int(utcoffset.total_seconds())
  186. return int(string_date.astimezone(utc).timestamp()), offset
  187. else:
  188. raise ValueError(f"string_date datetime object without tzinfo, {string_date}")
  189. # Git time
  190. try:
  191. if string_date.count(" ") == 1 and string_date.rfind(":") == -1:
  192. timestamp, offset_str = string_date.split()
  193. if timestamp.startswith("@"):
  194. timestamp = timestamp[1:]
  195. timestamp_int = int(timestamp)
  196. return timestamp_int, utctz_to_altz(verify_utctz(offset_str))
  197. else:
  198. offset_str = "+0000" # Local time by default.
  199. if string_date[-5] in "-+":
  200. offset_str = verify_utctz(string_date[-5:])
  201. string_date = string_date[:-6] # skip space as well
  202. # END split timezone info
  203. offset = utctz_to_altz(offset_str)
  204. # Now figure out the date and time portion - split time.
  205. date_formats = []
  206. splitter = -1
  207. if "," in string_date:
  208. date_formats.append("%a, %d %b %Y")
  209. splitter = string_date.rfind(" ")
  210. else:
  211. # ISO plus additional
  212. date_formats.append("%Y-%m-%d")
  213. date_formats.append("%Y.%m.%d")
  214. date_formats.append("%m/%d/%Y")
  215. date_formats.append("%d.%m.%Y")
  216. splitter = string_date.rfind("T")
  217. if splitter == -1:
  218. splitter = string_date.rfind(" ")
  219. # END handle 'T' and ' '
  220. # END handle RFC or ISO
  221. assert splitter > -1
  222. # Split date and time.
  223. time_part = string_date[splitter + 1 :] # Skip space.
  224. date_part = string_date[:splitter]
  225. # Parse time.
  226. tstruct = time.strptime(time_part, "%H:%M:%S")
  227. for fmt in date_formats:
  228. try:
  229. dtstruct = time.strptime(date_part, fmt)
  230. utctime = calendar.timegm(
  231. (
  232. dtstruct.tm_year,
  233. dtstruct.tm_mon,
  234. dtstruct.tm_mday,
  235. tstruct.tm_hour,
  236. tstruct.tm_min,
  237. tstruct.tm_sec,
  238. dtstruct.tm_wday,
  239. dtstruct.tm_yday,
  240. tstruct.tm_isdst,
  241. )
  242. )
  243. return int(utctime), offset
  244. except ValueError:
  245. continue
  246. # END exception handling
  247. # END for each fmt
  248. # Still here ? fail.
  249. raise ValueError("no format matched")
  250. # END handle format
  251. except Exception as e:
  252. raise ValueError(f"Unsupported date format or type: {string_date}, type={type(string_date)}") from e
  253. # END handle exceptions
  254. # Precompiled regexes
  255. _re_actor_epoch = re.compile(r"^.+? (.*) (\d+) ([+-]\d+).*$")
  256. _re_only_actor = re.compile(r"^.+? (.*)$")
  257. def parse_actor_and_date(line: str) -> Tuple[Actor, int, int]:
  258. """Parse out the actor (author or committer) info from a line like::
  259. author Tom Preston-Werner <tom@mojombo.com> 1191999972 -0700
  260. :return:
  261. [Actor, int_seconds_since_epoch, int_timezone_offset]
  262. """
  263. actor, epoch, offset = "", "0", "0"
  264. m = _re_actor_epoch.search(line)
  265. if m:
  266. actor, epoch, offset = m.groups()
  267. else:
  268. m = _re_only_actor.search(line)
  269. actor = m.group(1) if m else line or ""
  270. return (Actor._from_string(actor), int(epoch), utctz_to_altz(offset))
  271. # } END functions
  272. # { Classes
  273. class ProcessStreamAdapter:
  274. """Class wiring all calls to the contained Process instance.
  275. Use this type to hide the underlying process to provide access only to a specified
  276. stream. The process is usually wrapped into an :class:`~git.cmd.Git.AutoInterrupt`
  277. class to kill it if the instance goes out of scope.
  278. """
  279. __slots__ = ("_proc", "_stream")
  280. def __init__(self, process: "Popen", stream_name: str) -> None:
  281. self._proc = process
  282. self._stream: StringIO = getattr(process, stream_name) # guessed type
  283. def __getattr__(self, attr: str) -> Any:
  284. return getattr(self._stream, attr)
  285. @runtime_checkable
  286. class Traversable(Protocol):
  287. """Simple interface to perform depth-first or breadth-first traversals in one
  288. direction.
  289. Subclasses only need to implement one function.
  290. Instances of the subclass must be hashable.
  291. Defined subclasses:
  292. * :class:`Commit <git.objects.Commit>`
  293. * :class:`Tree <git.objects.tree.Tree>`
  294. * :class:`Submodule <git.objects.submodule.base.Submodule>`
  295. """
  296. __slots__ = ()
  297. @classmethod
  298. @abstractmethod
  299. def _get_intermediate_items(cls, item: Any) -> Sequence["Traversable"]:
  300. """
  301. :return:
  302. Tuple of items connected to the given item.
  303. Must be implemented in subclass.
  304. class Commit:: (cls, Commit) -> Tuple[Commit, ...]
  305. class Submodule:: (cls, Submodule) -> Iterablelist[Submodule]
  306. class Tree:: (cls, Tree) -> Tuple[Tree, ...]
  307. """
  308. raise NotImplementedError("To be implemented in subclass")
  309. @abstractmethod
  310. def list_traverse(self, *args: Any, **kwargs: Any) -> Any:
  311. """Traverse self and collect all items found.
  312. Calling this directly on the abstract base class, including via a ``super()``
  313. proxy, is deprecated. Only overridden implementations should be called.
  314. """
  315. warnings.warn(
  316. "list_traverse() method should only be called from subclasses."
  317. " Calling from Traversable abstract class will raise NotImplementedError in 4.0.0."
  318. " The concrete subclasses in GitPython itself are 'Commit', 'RootModule', 'Submodule', and 'Tree'.",
  319. DeprecationWarning,
  320. stacklevel=2,
  321. )
  322. return self._list_traverse(*args, **kwargs)
  323. def _list_traverse(
  324. self, as_edge: bool = False, *args: Any, **kwargs: Any
  325. ) -> IterableList[Union["Commit", "Submodule", "Tree", "Blob"]]:
  326. """Traverse self and collect all items found.
  327. :return:
  328. :class:`~git.util.IterableList` with the results of the traversal as
  329. produced by :meth:`traverse`::
  330. Commit -> IterableList[Commit]
  331. Submodule -> IterableList[Submodule]
  332. Tree -> IterableList[Union[Submodule, Tree, Blob]]
  333. """
  334. # Commit and Submodule have id.__attribute__ as IterableObj.
  335. # Tree has id.__attribute__ inherited from IndexObject.
  336. if isinstance(self, Has_id_attribute):
  337. id = self._id_attribute_
  338. else:
  339. # Shouldn't reach here, unless Traversable subclass created with no
  340. # _id_attribute_.
  341. id = ""
  342. # Could add _id_attribute_ to Traversable, or make all Traversable also
  343. # Iterable?
  344. if not as_edge:
  345. out: IterableList[Union["Commit", "Submodule", "Tree", "Blob"]] = IterableList(id)
  346. out.extend(self.traverse(as_edge=as_edge, *args, **kwargs)) # noqa: B026
  347. return out
  348. # Overloads in subclasses (mypy doesn't allow typing self: subclass).
  349. # Union[IterableList['Commit'], IterableList['Submodule'], IterableList[Union['Submodule', 'Tree', 'Blob']]]
  350. else:
  351. # Raise DeprecationWarning, it doesn't make sense to use this.
  352. out_list: IterableList = IterableList(self.traverse(*args, **kwargs))
  353. return out_list
  354. @abstractmethod
  355. def traverse(self, *args: Any, **kwargs: Any) -> Any:
  356. """Iterator yielding items found when traversing self.
  357. Calling this directly on the abstract base class, including via a ``super()``
  358. proxy, is deprecated. Only overridden implementations should be called.
  359. """
  360. warnings.warn(
  361. "traverse() method should only be called from subclasses."
  362. " Calling from Traversable abstract class will raise NotImplementedError in 4.0.0."
  363. " The concrete subclasses in GitPython itself are 'Commit', 'RootModule', 'Submodule', and 'Tree'.",
  364. DeprecationWarning,
  365. stacklevel=2,
  366. )
  367. return self._traverse(*args, **kwargs)
  368. def _traverse(
  369. self,
  370. predicate: Callable[[Union["Traversable", "Blob", TraversedTup], int], bool] = lambda i, d: True,
  371. prune: Callable[[Union["Traversable", "Blob", TraversedTup], int], bool] = lambda i, d: False,
  372. depth: int = -1,
  373. branch_first: bool = True,
  374. visit_once: bool = True,
  375. ignore_self: int = 1,
  376. as_edge: bool = False,
  377. ) -> Union[Iterator[Union["Traversable", "Blob"]], Iterator[TraversedTup]]:
  378. """Iterator yielding items found when traversing `self`.
  379. :param predicate:
  380. A function ``f(i,d)`` that returns ``False`` if item i at depth ``d`` should
  381. not be included in the result.
  382. :param prune:
  383. A function ``f(i,d)`` that returns ``True`` if the search should stop at
  384. item ``i`` at depth ``d``. Item ``i`` will not be returned.
  385. :param depth:
  386. Defines at which level the iteration should not go deeper if -1. There is no
  387. limit if 0, you would effectively only get `self`, the root of the
  388. iteration. If 1, you would only get the first level of
  389. predecessors/successors.
  390. :param branch_first:
  391. If ``True``, items will be returned branch first, otherwise depth first.
  392. :param visit_once:
  393. If ``True``, items will only be returned once, although they might be
  394. encountered several times. Loops are prevented that way.
  395. :param ignore_self:
  396. If ``True``, `self` will be ignored and automatically pruned from the
  397. result. Otherwise it will be the first item to be returned. If `as_edge` is
  398. ``True``, the source of the first edge is ``None``.
  399. :param as_edge:
  400. If ``True``, return a pair of items, first being the source, second the
  401. destination, i.e. tuple(src, dest) with the edge spanning from source to
  402. destination.
  403. :return:
  404. Iterator yielding items found when traversing `self`::
  405. Commit -> Iterator[Union[Commit, Tuple[Commit, Commit]] Submodule ->
  406. Iterator[Submodule, Tuple[Submodule, Submodule]] Tree ->
  407. Iterator[Union[Blob, Tree, Submodule,
  408. Tuple[Union[Submodule, Tree], Union[Blob, Tree,
  409. Submodule]]]
  410. ignore_self=True is_edge=True -> Iterator[item] ignore_self=True
  411. is_edge=False --> Iterator[item] ignore_self=False is_edge=True ->
  412. Iterator[item] | Iterator[Tuple[src, item]] ignore_self=False
  413. is_edge=False -> Iterator[Tuple[src, item]]
  414. """
  415. visited = set()
  416. stack: Deque[TraverseNT] = deque()
  417. stack.append(TraverseNT(0, self, None)) # self is always depth level 0.
  418. def addToStack(
  419. stack: Deque[TraverseNT],
  420. src_item: "Traversable",
  421. branch_first: bool,
  422. depth: int,
  423. ) -> None:
  424. lst = self._get_intermediate_items(item)
  425. if not lst: # Empty list
  426. return
  427. if branch_first:
  428. stack.extendleft(TraverseNT(depth, i, src_item) for i in lst)
  429. else:
  430. reviter = (TraverseNT(depth, lst[i], src_item) for i in range(len(lst) - 1, -1, -1))
  431. stack.extend(reviter)
  432. # END addToStack local method
  433. while stack:
  434. d, item, src = stack.pop() # Depth of item, item, item_source
  435. if visit_once and item in visited:
  436. continue
  437. if visit_once:
  438. visited.add(item)
  439. rval: Union[TraversedTup, "Traversable", "Blob"]
  440. if as_edge:
  441. # If as_edge return (src, item) unless rrc is None
  442. # (e.g. for first item).
  443. rval = (src, item)
  444. else:
  445. rval = item
  446. if prune(rval, d):
  447. continue
  448. skipStartItem = ignore_self and (item is self)
  449. if not skipStartItem and predicate(rval, d):
  450. yield rval
  451. # Only continue to next level if this is appropriate!
  452. next_d = d + 1
  453. if depth > -1 and next_d > depth:
  454. continue
  455. addToStack(stack, item, branch_first, next_d)
  456. # END for each item on work stack
  457. @runtime_checkable
  458. class Serializable(Protocol):
  459. """Defines methods to serialize and deserialize objects from and into a data
  460. stream."""
  461. __slots__ = ()
  462. # @abstractmethod
  463. def _serialize(self, stream: "BytesIO") -> "Serializable":
  464. """Serialize the data of this object into the given data stream.
  465. :note:
  466. A serialized object would :meth:`_deserialize` into the same object.
  467. :param stream:
  468. A file-like object.
  469. :return:
  470. self
  471. """
  472. raise NotImplementedError("To be implemented in subclass")
  473. # @abstractmethod
  474. def _deserialize(self, stream: "BytesIO") -> "Serializable":
  475. """Deserialize all information regarding this object from the stream.
  476. :param stream:
  477. A file-like object.
  478. :return:
  479. self
  480. """
  481. raise NotImplementedError("To be implemented in subclass")
  482. class TraversableIterableObj(IterableObj, Traversable):
  483. __slots__ = ()
  484. TIobj_tuple = Tuple[Union[T_TIobj, None], T_TIobj]
  485. def list_traverse(self: T_TIobj, *args: Any, **kwargs: Any) -> IterableList[T_TIobj]:
  486. return super()._list_traverse(*args, **kwargs)
  487. @overload
  488. def traverse(self: T_TIobj) -> Iterator[T_TIobj]: ...
  489. @overload
  490. def traverse(
  491. self: T_TIobj,
  492. predicate: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool],
  493. prune: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool],
  494. depth: int,
  495. branch_first: bool,
  496. visit_once: bool,
  497. ignore_self: Literal[True],
  498. as_edge: Literal[False],
  499. ) -> Iterator[T_TIobj]: ...
  500. @overload
  501. def traverse(
  502. self: T_TIobj,
  503. predicate: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool],
  504. prune: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool],
  505. depth: int,
  506. branch_first: bool,
  507. visit_once: bool,
  508. ignore_self: Literal[False],
  509. as_edge: Literal[True],
  510. ) -> Iterator[Tuple[Union[T_TIobj, None], T_TIobj]]: ...
  511. @overload
  512. def traverse(
  513. self: T_TIobj,
  514. predicate: Callable[[Union[T_TIobj, TIobj_tuple], int], bool],
  515. prune: Callable[[Union[T_TIobj, TIobj_tuple], int], bool],
  516. depth: int,
  517. branch_first: bool,
  518. visit_once: bool,
  519. ignore_self: Literal[True],
  520. as_edge: Literal[True],
  521. ) -> Iterator[Tuple[T_TIobj, T_TIobj]]: ...
  522. def traverse(
  523. self: T_TIobj,
  524. predicate: Callable[[Union[T_TIobj, TIobj_tuple], int], bool] = lambda i, d: True,
  525. prune: Callable[[Union[T_TIobj, TIobj_tuple], int], bool] = lambda i, d: False,
  526. depth: int = -1,
  527. branch_first: bool = True,
  528. visit_once: bool = True,
  529. ignore_self: int = 1,
  530. as_edge: bool = False,
  531. ) -> Union[Iterator[T_TIobj], Iterator[Tuple[T_TIobj, T_TIobj]], Iterator[TIobj_tuple]]:
  532. """For documentation, see :meth:`Traversable._traverse`."""
  533. ## To typecheck instead of using cast:
  534. #
  535. # import itertools
  536. # from git.types import TypeGuard
  537. # def is_commit_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Tuple['Commit', 'Commit']]]]:
  538. # for x in inp[1]:
  539. # if not isinstance(x, tuple) and len(x) != 2:
  540. # if all(isinstance(inner, Commit) for inner in x):
  541. # continue
  542. # return True
  543. #
  544. # ret = super(Commit, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self, as_edge)
  545. # ret_tup = itertools.tee(ret, 2)
  546. # assert is_commit_traversed(ret_tup), f"{[type(x) for x in list(ret_tup[0])]}"
  547. # return ret_tup[0]
  548. return cast(
  549. Union[Iterator[T_TIobj], Iterator[Tuple[Union[None, T_TIobj], T_TIobj]]],
  550. super()._traverse(
  551. predicate, # type: ignore[arg-type]
  552. prune, # type: ignore[arg-type]
  553. depth,
  554. branch_first,
  555. visit_once,
  556. ignore_self,
  557. as_edge,
  558. ),
  559. )