util.py 22 KB

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