diff_tree.py 23 KB

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