diff_tree.py 22 KB

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