graph.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
  2. # Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. """Implementation of merge-base following the approach of git."""
  21. from collections.abc import Iterator
  22. from heapq import heappop, heappush
  23. from typing import TYPE_CHECKING, Any, Callable, Generic, Optional, TypeVar
  24. if TYPE_CHECKING:
  25. from .repo import BaseRepo
  26. from .lru_cache import LRUCache
  27. from .objects import ObjectID
  28. T = TypeVar("T")
  29. # priority queue using builtin python minheap tools
  30. # why they do not have a builtin maxheap is simply ridiculous but
  31. # liveable with integer time stamps using negation
  32. class WorkList(Generic[T]):
  33. def __init__(self) -> None:
  34. self.pq: list[tuple[int, T]] = []
  35. def add(self, item: tuple[int, T]) -> None:
  36. dt, cmt = item
  37. heappush(self.pq, (-dt, cmt))
  38. def get(self) -> Optional[tuple[int, T]]:
  39. item = heappop(self.pq)
  40. if item:
  41. pr, cmt = item
  42. return -pr, cmt
  43. return None
  44. def iter(self) -> Iterator[tuple[int, T]]:
  45. for pr, cmt in self.pq:
  46. yield (-pr, cmt)
  47. def _find_lcas(
  48. lookup_parents: Callable[[ObjectID], list[ObjectID]],
  49. c1: ObjectID,
  50. c2s: list[ObjectID],
  51. lookup_stamp: Callable[[ObjectID], int],
  52. min_stamp: int = 0,
  53. ) -> list[ObjectID]:
  54. cands = []
  55. cstates = {}
  56. # Flags to Record State
  57. _ANC_OF_1 = 1 # ancestor of commit 1
  58. _ANC_OF_2 = 2 # ancestor of commit 2
  59. _DNC = 4 # Do Not Consider
  60. _LCA = 8 # potential LCA (Lowest Common Ancestor)
  61. def _has_candidates(wlst: WorkList[ObjectID], cstates: dict[ObjectID, int]) -> bool:
  62. for dt, cmt in wlst.iter():
  63. if cmt in cstates:
  64. if not ((cstates[cmt] & _DNC) == _DNC):
  65. return True
  66. return False
  67. # initialize the working list states with ancestry info
  68. # note possibility of c1 being one of c2s should be handled
  69. wlst: WorkList[bytes] = WorkList()
  70. cstates[c1] = _ANC_OF_1
  71. wlst.add((lookup_stamp(c1), c1))
  72. for c2 in c2s:
  73. cflags = cstates.get(c2, 0)
  74. cstates[c2] = cflags | _ANC_OF_2
  75. wlst.add((lookup_stamp(c2), c2))
  76. # loop while at least one working list commit is still viable (not marked as _DNC)
  77. # adding any parents to the list in a breadth first manner
  78. while _has_candidates(wlst, cstates):
  79. result = wlst.get()
  80. if result is None:
  81. break
  82. dt, cmt = result
  83. # Look only at ANCESTRY and _DNC flags so that already
  84. # found _LCAs can still be marked _DNC by lower _LCAS
  85. cflags = cstates[cmt] & (_ANC_OF_1 | _ANC_OF_2 | _DNC)
  86. if cflags == (_ANC_OF_1 | _ANC_OF_2):
  87. # potential common ancestor if not already in candidates add it
  88. if not (cstates[cmt] & _LCA) == _LCA:
  89. cstates[cmt] = cstates[cmt] | _LCA
  90. cands.append((dt, cmt))
  91. # mark any parents of this node _DNC as all parents
  92. # would be one generation further removed common ancestors
  93. cflags = cflags | _DNC
  94. parents = lookup_parents(cmt)
  95. if parents:
  96. for pcmt in parents:
  97. pflags = cstates.get(pcmt, 0)
  98. # if this parent was already visited with no new ancestry/flag information
  99. # do not add it to the working list again
  100. if (pflags & cflags) == cflags:
  101. continue
  102. pdt = lookup_stamp(pcmt)
  103. if pdt < min_stamp:
  104. continue
  105. cstates[pcmt] = pflags | cflags
  106. wlst.add((pdt, pcmt))
  107. # walk final candidates removing any superseded by _DNC by later lower _LCAs
  108. # remove any duplicates and sort it so that earliest is first
  109. results = []
  110. for dt, cmt in cands:
  111. if not ((cstates[cmt] & _DNC) == _DNC) and (dt, cmt) not in results:
  112. results.append((dt, cmt))
  113. results.sort(key=lambda x: x[0])
  114. lcas = [cmt for dt, cmt in results]
  115. return lcas
  116. # actual git sorts these based on commit times
  117. def find_merge_base(repo: "BaseRepo", commit_ids: list[ObjectID]) -> list[ObjectID]:
  118. """Find lowest common ancestors of commit_ids[0] and *any* of commits_ids[1:].
  119. Args:
  120. repo: Repository object
  121. commit_ids: list of commit ids
  122. Returns:
  123. list of lowest common ancestor commit_ids
  124. """
  125. cmtcache: LRUCache[ObjectID, Any] = LRUCache(max_cache=128)
  126. parents_provider = repo.parents_provider()
  127. def lookup_stamp(cmtid: ObjectID) -> int:
  128. if cmtid not in cmtcache:
  129. cmtcache[cmtid] = repo.object_store[cmtid]
  130. return cmtcache[cmtid].commit_time
  131. def lookup_parents(cmtid: ObjectID) -> list[ObjectID]:
  132. commit = None
  133. if cmtid in cmtcache:
  134. commit = cmtcache[cmtid]
  135. # must use parents provider to handle grafts and shallow
  136. return parents_provider.get_parents(cmtid, commit=commit)
  137. if not commit_ids:
  138. return []
  139. c1 = commit_ids[0]
  140. if not len(commit_ids) > 1:
  141. return [c1]
  142. c2s = commit_ids[1:]
  143. if c1 in c2s:
  144. return [c1]
  145. lcas = _find_lcas(lookup_parents, c1, c2s, lookup_stamp)
  146. return lcas
  147. def find_octopus_base(repo: "BaseRepo", commit_ids: list[ObjectID]) -> list[ObjectID]:
  148. """Find lowest common ancestors of *all* provided commit_ids.
  149. Args:
  150. repo: Repository
  151. commit_ids: list of commit ids
  152. Returns:
  153. list of lowest common ancestor commit_ids
  154. """
  155. cmtcache: LRUCache[ObjectID, Any] = LRUCache(max_cache=128)
  156. parents_provider = repo.parents_provider()
  157. def lookup_stamp(cmtid: ObjectID) -> int:
  158. if cmtid not in cmtcache:
  159. cmtcache[cmtid] = repo.object_store[cmtid]
  160. return cmtcache[cmtid].commit_time
  161. def lookup_parents(cmtid: ObjectID) -> list[ObjectID]:
  162. commit = None
  163. if cmtid in cmtcache:
  164. commit = cmtcache[cmtid]
  165. # must use parents provider to handle grafts and shallow
  166. return parents_provider.get_parents(cmtid, commit=commit)
  167. if not commit_ids:
  168. return []
  169. if len(commit_ids) <= 2:
  170. return find_merge_base(repo, commit_ids)
  171. lcas = [commit_ids[0]]
  172. others = commit_ids[1:]
  173. for cmt in others:
  174. next_lcas = []
  175. for ca in lcas:
  176. res = _find_lcas(lookup_parents, cmt, [ca], lookup_stamp)
  177. next_lcas.extend(res)
  178. lcas = next_lcas[:]
  179. return lcas
  180. def can_fast_forward(repo: "BaseRepo", c1: bytes, c2: bytes) -> bool:
  181. """Is it possible to fast-forward from c1 to c2?
  182. Args:
  183. repo: Repository to retrieve objects from
  184. c1: Commit id for first commit
  185. c2: Commit id for second commit
  186. """
  187. cmtcache: LRUCache[ObjectID, Any] = LRUCache(max_cache=128)
  188. parents_provider = repo.parents_provider()
  189. def lookup_stamp(cmtid: ObjectID) -> int:
  190. if cmtid not in cmtcache:
  191. cmtcache[cmtid] = repo.object_store[cmtid]
  192. return cmtcache[cmtid].commit_time
  193. def lookup_parents(cmtid: ObjectID) -> list[ObjectID]:
  194. commit = None
  195. if cmtid in cmtcache:
  196. commit = cmtcache[cmtid]
  197. # must use parents provider to handle grafts and shallow
  198. return parents_provider.get_parents(cmtid, commit=commit)
  199. if c1 == c2:
  200. return True
  201. # Algorithm: Find the common ancestor
  202. min_stamp = lookup_stamp(c1)
  203. lcas = _find_lcas(lookup_parents, c1, [c2], lookup_stamp, min_stamp=min_stamp)
  204. return lcas == [c1]