diff_tree.py 22 KB

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