diff_tree.py 22 KB

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