diff_tree.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. # diff_tree.py -- Utilities for diffing files and trees.
  2. # Copyright (C) 2010 Google, Inc.
  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. #
  21. """Utilities for diffing files and trees."""
  22. import stat
  23. from collections import defaultdict, namedtuple
  24. from io import BytesIO
  25. from itertools import chain
  26. from typing import Optional
  27. from .object_store import BaseObjectStore
  28. from .objects import S_ISGITLINK, ObjectID, ShaFile, Tree, TreeEntry
  29. # TreeChange type constants.
  30. CHANGE_ADD = "add"
  31. CHANGE_MODIFY = "modify"
  32. CHANGE_DELETE = "delete"
  33. CHANGE_RENAME = "rename"
  34. CHANGE_COPY = "copy"
  35. CHANGE_UNCHANGED = "unchanged"
  36. RENAME_CHANGE_TYPES = (CHANGE_RENAME, CHANGE_COPY)
  37. _NULL_ENTRY = TreeEntry(None, None, None)
  38. _MAX_SCORE = 100
  39. RENAME_THRESHOLD = 60
  40. MAX_FILES = 200
  41. REWRITE_THRESHOLD = None
  42. class TreeChange(namedtuple("TreeChange", ["type", "old", "new"])):
  43. """Named tuple a single change between two trees."""
  44. @classmethod
  45. def add(cls, new):
  46. return cls(CHANGE_ADD, _NULL_ENTRY, new)
  47. @classmethod
  48. def delete(cls, old):
  49. return cls(CHANGE_DELETE, old, _NULL_ENTRY)
  50. def _tree_entries(path: bytes, tree: Tree) -> list[TreeEntry]:
  51. result: list[TreeEntry] = []
  52. if not tree:
  53. return result
  54. for entry in tree.iteritems(name_order=True):
  55. result.append(entry.in_path(path))
  56. return result
  57. def _merge_entries(
  58. path: bytes, tree1: Tree, tree2: Tree
  59. ) -> list[tuple[TreeEntry, TreeEntry]]:
  60. """Merge the entries of two trees.
  61. Args:
  62. path: A path to prepend to all tree entry names.
  63. tree1: The first Tree object to iterate, or None.
  64. tree2: The second Tree object to iterate, or None.
  65. Returns:
  66. A list of pairs of TreeEntry objects for each pair of entries in
  67. the trees. If an entry exists in one tree but not the other, the other
  68. entry will have all attributes set to None. If neither entry's path is
  69. None, they are guaranteed to match.
  70. """
  71. entries1 = _tree_entries(path, tree1)
  72. entries2 = _tree_entries(path, tree2)
  73. i1 = i2 = 0
  74. len1 = len(entries1)
  75. len2 = len(entries2)
  76. result = []
  77. while i1 < len1 and i2 < len2:
  78. entry1 = entries1[i1]
  79. entry2 = entries2[i2]
  80. if entry1.path < entry2.path:
  81. result.append((entry1, _NULL_ENTRY))
  82. i1 += 1
  83. elif entry1.path > entry2.path:
  84. result.append((_NULL_ENTRY, entry2))
  85. i2 += 1
  86. else:
  87. result.append((entry1, entry2))
  88. i1 += 1
  89. i2 += 1
  90. for i in range(i1, len1):
  91. result.append((entries1[i], _NULL_ENTRY))
  92. for i in range(i2, len2):
  93. result.append((_NULL_ENTRY, entries2[i]))
  94. return result
  95. def _is_tree(entry):
  96. mode = entry.mode
  97. if mode is None:
  98. return False
  99. return stat.S_ISDIR(mode)
  100. def walk_trees(store, tree1_id, tree2_id, prune_identical=False):
  101. """Recursively walk all the entries of two trees.
  102. Iteration is depth-first pre-order, as in e.g. os.walk.
  103. Args:
  104. store: An ObjectStore for looking up objects.
  105. tree1_id: The SHA of the first Tree object to iterate, or None.
  106. tree2_id: The SHA of the second Tree object to iterate, or None.
  107. prune_identical: If True, identical subtrees will not be walked.
  108. Returns:
  109. Iterator over Pairs of TreeEntry objects for each pair of entries
  110. in the trees and their subtrees recursively. If an entry exists in one
  111. tree but not the other, the other entry will have all attributes set
  112. to None. If neither entry's path is None, they are guaranteed to
  113. match.
  114. """
  115. # This could be fairly easily generalized to >2 trees if we find a use
  116. # case.
  117. mode1 = (tree1_id and stat.S_IFDIR) or None
  118. mode2 = (tree2_id and stat.S_IFDIR) or None
  119. todo = [(TreeEntry(b"", mode1, tree1_id), TreeEntry(b"", mode2, tree2_id))]
  120. while todo:
  121. entry1, entry2 = todo.pop()
  122. is_tree1 = _is_tree(entry1)
  123. is_tree2 = _is_tree(entry2)
  124. if prune_identical and is_tree1 and is_tree2 and entry1 == entry2:
  125. continue
  126. tree1 = (is_tree1 and store[entry1.sha]) or None
  127. tree2 = (is_tree2 and store[entry2.sha]) or None
  128. path = entry1.path or entry2.path
  129. todo.extend(reversed(_merge_entries(path, tree1, tree2)))
  130. yield entry1, entry2
  131. def _skip_tree(entry, include_trees):
  132. if entry.mode is None or (not include_trees and stat.S_ISDIR(entry.mode)):
  133. return _NULL_ENTRY
  134. return entry
  135. def tree_changes(
  136. store,
  137. tree1_id,
  138. tree2_id,
  139. want_unchanged=False,
  140. rename_detector=None,
  141. include_trees=False,
  142. change_type_same=False,
  143. ):
  144. """Find the differences between the contents of two trees.
  145. Args:
  146. store: An ObjectStore for looking up objects.
  147. tree1_id: The SHA of the source tree.
  148. tree2_id: The SHA of the target tree.
  149. want_unchanged: If True, include TreeChanges for unmodified entries
  150. as well.
  151. include_trees: Whether to include trees
  152. rename_detector: RenameDetector object for detecting renames.
  153. change_type_same: Whether to report change types in the same
  154. entry or as delete+add.
  155. Returns:
  156. Iterator over TreeChange instances for each change between the
  157. source and target tree.
  158. """
  159. if rename_detector is not None and tree1_id is not None and tree2_id is not None:
  160. yield from rename_detector.changes_with_renames(
  161. tree1_id,
  162. tree2_id,
  163. want_unchanged=want_unchanged,
  164. include_trees=include_trees,
  165. )
  166. return
  167. entries = walk_trees(
  168. store, tree1_id, tree2_id, prune_identical=(not want_unchanged)
  169. )
  170. for entry1, entry2 in entries:
  171. if entry1 == entry2 and not want_unchanged:
  172. continue
  173. # Treat entries for trees as missing.
  174. entry1 = _skip_tree(entry1, include_trees)
  175. entry2 = _skip_tree(entry2, include_trees)
  176. if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY:
  177. if (
  178. stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode)
  179. and not change_type_same
  180. ):
  181. # File type changed: report as delete/add.
  182. yield TreeChange.delete(entry1)
  183. entry1 = _NULL_ENTRY
  184. change_type = CHANGE_ADD
  185. elif entry1 == entry2:
  186. change_type = CHANGE_UNCHANGED
  187. else:
  188. change_type = CHANGE_MODIFY
  189. elif entry1 != _NULL_ENTRY:
  190. change_type = CHANGE_DELETE
  191. elif entry2 != _NULL_ENTRY:
  192. change_type = CHANGE_ADD
  193. else:
  194. # Both were None because at least one was a tree.
  195. continue
  196. yield TreeChange(change_type, entry1, entry2)
  197. def _all_eq(seq, key, value) -> bool:
  198. for e in seq:
  199. if key(e) != value:
  200. return False
  201. return True
  202. def _all_same(seq, key):
  203. return _all_eq(seq[1:], key, key(seq[0]))
  204. def tree_changes_for_merge(
  205. store: BaseObjectStore,
  206. parent_tree_ids: list[ObjectID],
  207. tree_id: ObjectID,
  208. rename_detector=None,
  209. ):
  210. """Get the tree changes for a merge tree relative to all its parents.
  211. Args:
  212. store: An ObjectStore for looking up objects.
  213. parent_tree_ids: An iterable of the SHAs of the parent trees.
  214. tree_id: The SHA of the merge tree.
  215. rename_detector: RenameDetector object for detecting renames.
  216. Returns:
  217. Iterator over lists of TreeChange objects, one per conflicted path
  218. in the merge.
  219. Each list contains one element per parent, with the TreeChange for that
  220. path relative to that parent. An element may be None if it never
  221. existed in one parent and was deleted in two others.
  222. A path is only included in the output if it is a conflict, i.e. its SHA
  223. in the merge tree is not found in any of the parents, or in the case of
  224. deletes, if not all of the old SHAs match.
  225. """
  226. all_parent_changes = [
  227. tree_changes(store, t, tree_id, rename_detector=rename_detector)
  228. for t in parent_tree_ids
  229. ]
  230. num_parents = len(parent_tree_ids)
  231. changes_by_path: dict[str, list[Optional[TreeChange]]] = defaultdict(
  232. lambda: [None] * num_parents
  233. )
  234. # Organize by path.
  235. for i, parent_changes in enumerate(all_parent_changes):
  236. for change in parent_changes:
  237. if change.type == CHANGE_DELETE:
  238. path = change.old.path
  239. else:
  240. path = change.new.path
  241. changes_by_path[path][i] = change
  242. def old_sha(c):
  243. return c.old.sha
  244. def change_type(c):
  245. return c.type
  246. # Yield only conflicting changes.
  247. for _, changes in sorted(changes_by_path.items()):
  248. assert len(changes) == num_parents
  249. have = [c for c in changes if c is not None]
  250. if _all_eq(have, change_type, CHANGE_DELETE):
  251. if not _all_same(have, old_sha):
  252. yield changes
  253. elif not _all_same(have, change_type):
  254. yield changes
  255. elif None not in changes:
  256. # If no change was found relative to one parent, that means the SHA
  257. # must have matched the SHA in that parent, so it is not a
  258. # conflict.
  259. yield changes
  260. _BLOCK_SIZE = 64
  261. def _count_blocks(obj: ShaFile) -> dict[int, int]:
  262. """Count the blocks in an object.
  263. Splits the data into blocks either on lines or <=64-byte chunks of lines.
  264. Args:
  265. obj: The object to count blocks for.
  266. Returns:
  267. A dict of block hashcode -> total bytes occurring.
  268. """
  269. block_counts: dict[int, int] = defaultdict(int)
  270. block = BytesIO()
  271. n = 0
  272. # Cache attrs as locals to avoid expensive lookups in the inner loop.
  273. block_write = block.write
  274. block_seek = block.seek
  275. block_truncate = block.truncate
  276. block_getvalue = block.getvalue
  277. for c in chain.from_iterable(obj.as_raw_chunks()):
  278. cb = c.to_bytes(1, "big")
  279. block_write(cb)
  280. n += 1
  281. if cb == b"\n" or n == _BLOCK_SIZE:
  282. value = block_getvalue()
  283. block_counts[hash(value)] += len(value)
  284. block_seek(0)
  285. block_truncate()
  286. n = 0
  287. if n > 0:
  288. last_block = block_getvalue()
  289. block_counts[hash(last_block)] += len(last_block)
  290. return block_counts
  291. def _common_bytes(blocks1, blocks2):
  292. """Count the number of common bytes in two block count dicts.
  293. Args:
  294. blocks1: The first dict of block hashcode -> total bytes.
  295. blocks2: The second dict of block hashcode -> total bytes.
  296. Returns:
  297. The number of bytes in common between blocks1 and blocks2. This is
  298. only approximate due to possible hash collisions.
  299. """
  300. # Iterate over the smaller of the two dicts, since this is symmetrical.
  301. if len(blocks1) > len(blocks2):
  302. blocks1, blocks2 = blocks2, blocks1
  303. score = 0
  304. for block, count1 in blocks1.items():
  305. count2 = blocks2.get(block)
  306. if count2:
  307. score += min(count1, count2)
  308. return score
  309. def _similarity_score(obj1, obj2, block_cache=None):
  310. """Compute a similarity score for two objects.
  311. Args:
  312. obj1: The first object to score.
  313. obj2: The second object to score.
  314. block_cache: An optional dict of SHA to block counts to cache
  315. results between calls.
  316. Returns:
  317. The similarity score between the two objects, defined as the
  318. number of bytes in common between the two objects divided by the
  319. maximum size, scaled to the range 0-100.
  320. """
  321. if block_cache is None:
  322. block_cache = {}
  323. if obj1.id not in block_cache:
  324. block_cache[obj1.id] = _count_blocks(obj1)
  325. if obj2.id not in block_cache:
  326. block_cache[obj2.id] = _count_blocks(obj2)
  327. common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id])
  328. max_size = max(obj1.raw_length(), obj2.raw_length())
  329. if not max_size:
  330. return _MAX_SCORE
  331. return int(float(common_bytes) * _MAX_SCORE / max_size)
  332. def _tree_change_key(entry):
  333. # Sort by old path then new path. If only one exists, use it for both keys.
  334. path1 = entry.old.path
  335. path2 = entry.new.path
  336. if path1 is None:
  337. path1 = path2
  338. if path2 is None:
  339. path2 = path1
  340. return (path1, path2)
  341. class RenameDetector:
  342. """Object for handling rename detection between two trees."""
  343. _adds: list[TreeChange]
  344. _deletes: list[TreeChange]
  345. _changes: list[TreeChange]
  346. _candidates: list[tuple[int, TreeChange]]
  347. def __init__(
  348. self,
  349. store,
  350. rename_threshold=RENAME_THRESHOLD,
  351. max_files=MAX_FILES,
  352. rewrite_threshold=REWRITE_THRESHOLD,
  353. find_copies_harder=False,
  354. ) -> None:
  355. """Initialize the rename detector.
  356. Args:
  357. store: An ObjectStore for looking up objects.
  358. rename_threshold: The threshold similarity score for considering
  359. an add/delete pair to be a rename/copy; see _similarity_score.
  360. max_files: The maximum number of adds and deletes to consider,
  361. or None for no limit. The detector is guaranteed to compare no more
  362. than max_files ** 2 add/delete pairs. This limit is provided
  363. because rename detection can be quadratic in the project size. If
  364. the limit is exceeded, no content rename detection is attempted.
  365. rewrite_threshold: The threshold similarity score below which a
  366. modify should be considered a delete/add, or None to not break
  367. modifies; see _similarity_score.
  368. find_copies_harder: If True, consider unmodified files when
  369. detecting copies.
  370. """
  371. self._store = store
  372. self._rename_threshold = rename_threshold
  373. self._rewrite_threshold = rewrite_threshold
  374. self._max_files = max_files
  375. self._find_copies_harder = find_copies_harder
  376. self._want_unchanged = False
  377. def _reset(self) -> None:
  378. self._adds = []
  379. self._deletes = []
  380. self._changes = []
  381. def _should_split(self, change):
  382. if (
  383. self._rewrite_threshold is None
  384. or change.type != CHANGE_MODIFY
  385. or change.old.sha == change.new.sha
  386. ):
  387. return False
  388. old_obj = self._store[change.old.sha]
  389. new_obj = self._store[change.new.sha]
  390. return _similarity_score(old_obj, new_obj) < self._rewrite_threshold
  391. def _add_change(self, change) -> None:
  392. if change.type == CHANGE_ADD:
  393. self._adds.append(change)
  394. elif change.type == CHANGE_DELETE:
  395. self._deletes.append(change)
  396. elif self._should_split(change):
  397. self._deletes.append(TreeChange.delete(change.old))
  398. self._adds.append(TreeChange.add(change.new))
  399. elif (
  400. self._find_copies_harder and change.type == CHANGE_UNCHANGED
  401. ) or change.type == CHANGE_MODIFY:
  402. # Treat all modifies as potential deletes for rename detection,
  403. # but don't split them (to avoid spurious renames). Setting
  404. # find_copies_harder means we treat unchanged the same as
  405. # modified.
  406. self._deletes.append(change)
  407. else:
  408. self._changes.append(change)
  409. def _collect_changes(self, tree1_id, tree2_id) -> None:
  410. want_unchanged = self._find_copies_harder or self._want_unchanged
  411. for change in tree_changes(
  412. self._store,
  413. tree1_id,
  414. tree2_id,
  415. want_unchanged=want_unchanged,
  416. include_trees=self._include_trees,
  417. ):
  418. self._add_change(change)
  419. def _prune(self, add_paths, delete_paths) -> None:
  420. self._adds = [a for a in self._adds if a.new.path not in add_paths]
  421. self._deletes = [d for d in self._deletes if d.old.path not in delete_paths]
  422. def _find_exact_renames(self) -> None:
  423. add_map = defaultdict(list)
  424. for add in self._adds:
  425. add_map[add.new.sha].append(add.new)
  426. delete_map = defaultdict(list)
  427. for delete in self._deletes:
  428. # Keep track of whether the delete was actually marked as a delete.
  429. # If not, it needs to be marked as a copy.
  430. is_delete = delete.type == CHANGE_DELETE
  431. delete_map[delete.old.sha].append((delete.old, is_delete))
  432. add_paths = set()
  433. delete_paths = set()
  434. for sha, sha_deletes in delete_map.items():
  435. sha_adds = add_map[sha]
  436. for (old, is_delete), new in zip(sha_deletes, sha_adds):
  437. if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode):
  438. continue
  439. if is_delete:
  440. delete_paths.add(old.path)
  441. add_paths.add(new.path)
  442. new_type = (is_delete and CHANGE_RENAME) or CHANGE_COPY
  443. self._changes.append(TreeChange(new_type, old, new))
  444. num_extra_adds = len(sha_adds) - len(sha_deletes)
  445. # TODO(dborowitz): Less arbitrary way of dealing with extra copies.
  446. old = sha_deletes[0][0]
  447. if num_extra_adds > 0:
  448. for new in sha_adds[-num_extra_adds:]:
  449. add_paths.add(new.path)
  450. self._changes.append(TreeChange(CHANGE_COPY, old, new))
  451. self._prune(add_paths, delete_paths)
  452. def _should_find_content_renames(self):
  453. return len(self._adds) * len(self._deletes) <= self._max_files**2
  454. def _rename_type(self, check_paths, delete, add):
  455. if check_paths and delete.old.path == add.new.path:
  456. # If the paths match, this must be a split modify, so make sure it
  457. # comes out as a modify.
  458. return CHANGE_MODIFY
  459. elif delete.type != CHANGE_DELETE:
  460. # If it's in deletes but not marked as a delete, it must have been
  461. # added due to find_copies_harder, and needs to be marked as a
  462. # copy.
  463. return CHANGE_COPY
  464. return CHANGE_RENAME
  465. def _find_content_rename_candidates(self) -> None:
  466. candidates = self._candidates = []
  467. # TODO: Optimizations:
  468. # - Compare object sizes before counting blocks.
  469. # - Skip if delete's S_IFMT differs from all adds.
  470. # - Skip if adds or deletes is empty.
  471. # Match C git's behavior of not attempting to find content renames if
  472. # the matrix size exceeds the threshold.
  473. if not self._should_find_content_renames():
  474. return
  475. block_cache = {}
  476. check_paths = self._rename_threshold is not None
  477. for delete in self._deletes:
  478. if S_ISGITLINK(delete.old.mode):
  479. continue # Git links don't exist in this repo.
  480. old_sha = delete.old.sha
  481. old_obj = self._store[old_sha]
  482. block_cache[old_sha] = _count_blocks(old_obj)
  483. for add in self._adds:
  484. if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode):
  485. continue
  486. new_obj = self._store[add.new.sha]
  487. score = _similarity_score(old_obj, new_obj, block_cache=block_cache)
  488. if score > self._rename_threshold:
  489. new_type = self._rename_type(check_paths, delete, add)
  490. rename = TreeChange(new_type, delete.old, add.new)
  491. candidates.append((-score, rename))
  492. def _choose_content_renames(self) -> None:
  493. # Sort scores from highest to lowest, but keep names in ascending
  494. # order.
  495. self._candidates.sort()
  496. delete_paths = set()
  497. add_paths = set()
  498. for _, change in self._candidates:
  499. new_path = change.new.path
  500. if new_path in add_paths:
  501. continue
  502. old_path = change.old.path
  503. orig_type = change.type
  504. if old_path in delete_paths:
  505. change = TreeChange(CHANGE_COPY, change.old, change.new)
  506. # If the candidate was originally a copy, that means it came from a
  507. # modified or unchanged path, so we don't want to prune it.
  508. if orig_type != CHANGE_COPY:
  509. delete_paths.add(old_path)
  510. add_paths.add(new_path)
  511. self._changes.append(change)
  512. self._prune(add_paths, delete_paths)
  513. def _join_modifies(self) -> None:
  514. if self._rewrite_threshold is None:
  515. return
  516. modifies = {}
  517. delete_map = {d.old.path: d for d in self._deletes}
  518. for add in self._adds:
  519. path = add.new.path
  520. delete = delete_map.get(path)
  521. if delete is not None and stat.S_IFMT(delete.old.mode) == stat.S_IFMT(
  522. add.new.mode
  523. ):
  524. modifies[path] = TreeChange(CHANGE_MODIFY, delete.old, add.new)
  525. self._adds = [a for a in self._adds if a.new.path not in modifies]
  526. self._deletes = [a for a in self._deletes if a.new.path not in modifies]
  527. self._changes += modifies.values()
  528. def _sorted_changes(self):
  529. result = []
  530. result.extend(self._adds)
  531. result.extend(self._deletes)
  532. result.extend(self._changes)
  533. result.sort(key=_tree_change_key)
  534. return result
  535. def _prune_unchanged(self) -> None:
  536. if self._want_unchanged:
  537. return
  538. self._deletes = [d for d in self._deletes if d.type != CHANGE_UNCHANGED]
  539. def changes_with_renames(
  540. self, tree1_id, tree2_id, want_unchanged=False, include_trees=False
  541. ):
  542. """Iterate TreeChanges between two tree SHAs, with rename detection."""
  543. self._reset()
  544. self._want_unchanged = want_unchanged
  545. self._include_trees = include_trees
  546. self._collect_changes(tree1_id, tree2_id)
  547. self._find_exact_renames()
  548. self._find_content_rename_candidates()
  549. self._choose_content_renames()
  550. self._join_modifies()
  551. self._prune_unchanged()
  552. return self._sorted_changes()
  553. # Hold on to the pure-python implementations for testing.
  554. _is_tree_py = _is_tree
  555. _merge_entries_py = _merge_entries
  556. _count_blocks_py = _count_blocks
  557. try:
  558. # Try to import Rust versions
  559. from dulwich._diff_tree import ( # type: ignore
  560. _count_blocks,
  561. _is_tree,
  562. _merge_entries,
  563. )
  564. except ImportError:
  565. pass