diff_tree.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. from cStringIO import StringIO
  20. import itertools
  21. import stat
  22. from dulwich.misc import (
  23. defaultdict,
  24. TreeChangeTuple,
  25. )
  26. from dulwich.objects import (
  27. S_ISGITLINK,
  28. TreeEntry,
  29. )
  30. # TreeChange type constants.
  31. CHANGE_ADD = 'add'
  32. CHANGE_MODIFY = 'modify'
  33. CHANGE_DELETE = 'delete'
  34. CHANGE_RENAME = 'rename'
  35. CHANGE_COPY = 'copy'
  36. CHANGE_UNCHANGED = 'unchanged'
  37. _NULL_ENTRY = TreeEntry(None, None, None)
  38. _MAX_SCORE = 100
  39. _RENAME_THRESHOLD = 60
  40. class TreeChange(TreeChangeTuple):
  41. """Class encapsulating a single change between two trees."""
  42. @classmethod
  43. def add(cls, new):
  44. return cls(CHANGE_ADD, _NULL_ENTRY, new)
  45. @classmethod
  46. def delete(cls, old):
  47. return cls(CHANGE_DELETE, old, _NULL_ENTRY)
  48. def _tree_entries(path, tree):
  49. result = []
  50. if not tree:
  51. return result
  52. for entry in tree.iteritems(name_order=True):
  53. result.append(entry.in_path(path))
  54. return result
  55. def _merge_entries(path, tree1, tree2):
  56. """Merge the entries of two trees.
  57. :param path: A path to prepend to all tree entry names.
  58. :param tree1: The first Tree object to iterate, or None.
  59. :param tree2: The second Tree object to iterate, or None.
  60. :return: A list of pairs of TreeEntry objects for each pair of entries in
  61. the trees. If an entry exists in one tree but not the other, the other
  62. entry will have all attributes set to None. If neither entry's path is
  63. None, they are guaranteed to match.
  64. """
  65. entries1 = _tree_entries(path, tree1)
  66. entries2 = _tree_entries(path, tree2)
  67. i1 = i2 = 0
  68. len1 = len(entries1)
  69. len2 = len(entries2)
  70. result = []
  71. while i1 < len1 and i2 < len2:
  72. entry1 = entries1[i1]
  73. entry2 = entries2[i2]
  74. if entry1.path < entry2.path:
  75. result.append((entry1, _NULL_ENTRY))
  76. i1 += 1
  77. elif entry1.path > entry2.path:
  78. result.append((_NULL_ENTRY, entry2))
  79. i2 += 1
  80. else:
  81. result.append((entry1, entry2))
  82. i1 += 1
  83. i2 += 1
  84. for i in xrange(i1, len1):
  85. result.append((entries1[i], _NULL_ENTRY))
  86. for i in xrange(i2, len2):
  87. result.append((_NULL_ENTRY, entries2[i]))
  88. return result
  89. def walk_trees(store, tree1_id, tree2_id, prune_identical=False):
  90. """Recursively walk all the entries of two trees.
  91. Iteration is depth-first pre-order, as in e.g. os.walk.
  92. :param store: An ObjectStore for looking up objects.
  93. :param tree1_id: The SHA of the first Tree object to iterate, or None.
  94. :param tree2_id: The SHA of the second Tree object to iterate, or None.
  95. :param prune_identical: If True, identical subtrees will not be walked.
  96. :yield: Pairs of TreeEntry objects for each pair of entries in the trees and
  97. their subtrees recursively. If an entry exists in one tree but not the
  98. other, the other entry will have all attributes set to None. If neither
  99. entry's path is None, they are guaranteed to match.
  100. """
  101. # This could be fairly easily generalized to >2 trees if we find a use case.
  102. mode1 = tree1_id and stat.S_IFDIR or None
  103. mode2 = tree2_id and stat.S_IFDIR or None
  104. todo = [(TreeEntry('', mode1, tree1_id), TreeEntry('', mode2, tree2_id))]
  105. while todo:
  106. entry1, entry2 = todo.pop()
  107. is_tree1 = entry1.mode and stat.S_ISDIR(entry1.mode)
  108. is_tree2 = entry2.mode and stat.S_ISDIR(entry2.mode)
  109. if prune_identical and is_tree1 and is_tree2 and entry1 == entry2:
  110. continue
  111. tree1 = is_tree1 and store[entry1.sha] or None
  112. tree2 = is_tree2 and store[entry2.sha] or None
  113. path = entry1.path or entry2.path
  114. todo.extend(reversed(_merge_entries(path, tree1, tree2)))
  115. yield entry1, entry2
  116. def _skip_tree(entry):
  117. if entry.mode is None or stat.S_ISDIR(entry.mode):
  118. return _NULL_ENTRY
  119. return entry
  120. def tree_changes(store, tree1_id, tree2_id, want_unchanged=False):
  121. """Find the differences between the contents of two trees.
  122. :param store: An ObjectStore for looking up objects.
  123. :param tree1_id: The SHA of the source tree.
  124. :param tree2_id: The SHA of the target tree.
  125. :param want_unchanged: If True, include TreeChanges for unmodified entries
  126. as well.
  127. :yield: TreeChange instances for each change between the source and target
  128. tree.
  129. """
  130. entries = walk_trees(store, tree1_id, tree2_id,
  131. prune_identical=(not want_unchanged))
  132. for entry1, entry2 in entries:
  133. if entry1 == entry2 and not want_unchanged:
  134. continue
  135. # Treat entries for trees as missing.
  136. entry1 = _skip_tree(entry1)
  137. entry2 = _skip_tree(entry2)
  138. if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY:
  139. if stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode):
  140. # File type changed: report as delete/add.
  141. yield TreeChange.delete(entry1)
  142. entry1 = _NULL_ENTRY
  143. change_type = CHANGE_ADD
  144. elif entry1 == entry2:
  145. change_type = CHANGE_UNCHANGED
  146. else:
  147. change_type = CHANGE_MODIFY
  148. elif entry1 != _NULL_ENTRY:
  149. change_type = CHANGE_DELETE
  150. elif entry2 != _NULL_ENTRY:
  151. change_type = CHANGE_ADD
  152. else:
  153. # Both were None because at least one was a tree.
  154. continue
  155. yield TreeChange(change_type, entry1, entry2)
  156. _BLOCK_SIZE = 64
  157. def _count_blocks(obj):
  158. """Count the blocks in an object.
  159. Splits the data into blocks either on lines or <=64-byte chunks of lines.
  160. :param obj: The object to count blocks for.
  161. :return: A dict of block -> number of occurrences.
  162. """
  163. block_counts = defaultdict(int)
  164. block = StringIO()
  165. for c in itertools.chain(*obj.as_raw_chunks()):
  166. block.write(c)
  167. if c == '\n' or block.tell() == _BLOCK_SIZE:
  168. block_counts[block.getvalue()] += 1
  169. block.seek(0)
  170. block.truncate()
  171. last_block = block.getvalue()
  172. if last_block:
  173. block_counts[last_block] += 1
  174. return block_counts
  175. def _common_bytes(blocks1, blocks2):
  176. """Count the number of common bytes in two block count dicts."""
  177. # Iterate over the smaller of the two dicts, since this is symmetrical.
  178. if len(blocks1) > len(blocks2):
  179. blocks1, blocks2 = blocks2, blocks1
  180. score = 0
  181. for block, count1 in blocks1.iteritems():
  182. count2 = blocks2.get(block)
  183. if count2:
  184. score += min(count1, count2) * len(block)
  185. return score
  186. def _similarity_score(obj1, obj2, block_cache=None):
  187. """Compute a similarity score for two objects.
  188. :param obj1: The first object to score.
  189. :param obj2: The second object to score.
  190. :param block_cache: An optional dict of SHA to block counts to cache results
  191. between calls.
  192. :return: The similarity score between the two objects, defined as the number
  193. of bytes in common between the two objects divided by the maximum size,
  194. scaled to the range 0-100.
  195. """
  196. if block_cache is None:
  197. block_cache = {}
  198. if obj1.id not in block_cache:
  199. block_cache[obj1.id] = _count_blocks(obj1)
  200. if obj2.id not in block_cache:
  201. block_cache[obj2.id] = _count_blocks(obj2)
  202. common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id])
  203. max_size = max(obj1.raw_length(), obj2.raw_length())
  204. if not max_size:
  205. return _MAX_SCORE
  206. return int(float(common_bytes) * _MAX_SCORE / max_size)
  207. def _tree_change_key(entry):
  208. # Sort by old path then new path. If only one exists, use it for both keys.
  209. path1 = entry.old.path
  210. path2 = entry.new.path
  211. if path1 is None:
  212. path1 = path2
  213. if path2 is None:
  214. path2 = path1
  215. return (path1, path2)
  216. class RenameDetector(object):
  217. """Object for handling rename detection between two trees."""
  218. def __init__(self, store, tree1_id, tree2_id,
  219. rename_threshold=_RENAME_THRESHOLD):
  220. """Initialize the rename detector.
  221. :param store: An ObjectStore for looking up objects.
  222. :param tree1_id: The SHA of the first Tree.
  223. :param tree2_id: The SHA of the second Tree.
  224. :param rename_threshold: The threshold similarity score for considering
  225. an add/delete pair to be a rename/copy; see _similarity_score.
  226. """
  227. self._tree1_id = tree1_id
  228. self._tree2_id = tree2_id
  229. self._store = store
  230. self._rename_threshold = rename_threshold
  231. self._adds = []
  232. self._deletes = []
  233. self._changes = []
  234. def _collect_changes(self):
  235. for change in tree_changes(self._store, self._tree1_id, self._tree2_id):
  236. if change.type == CHANGE_ADD:
  237. self._adds.append(change)
  238. elif change.type == CHANGE_DELETE:
  239. self._deletes.append(change)
  240. else:
  241. self._changes.append(change)
  242. def _prune(self, add_paths, delete_paths):
  243. self._adds = [a for a in self._adds if a.new.path not in add_paths]
  244. self._deletes = [d for d in self._deletes
  245. if d.old.path not in delete_paths]
  246. def _find_exact_renames(self):
  247. add_map = defaultdict(list)
  248. for add in self._adds:
  249. add_map[add.new.sha].append(add.new)
  250. delete_map = defaultdict(list)
  251. for delete in self._deletes:
  252. delete_map[delete.old.sha].append(delete.old)
  253. add_paths = set()
  254. delete_paths = set()
  255. for sha, sha_deletes in delete_map.iteritems():
  256. sha_adds = add_map[sha]
  257. for old, new in itertools.izip(sha_deletes, sha_adds):
  258. if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode):
  259. continue
  260. delete_paths.add(old.path)
  261. add_paths.add(new.path)
  262. self._changes.append(TreeChange(CHANGE_RENAME, old, new))
  263. num_extra_adds = len(sha_adds) - len(sha_deletes)
  264. # TODO(dborowitz): Less arbitrary way of dealing with extra copies.
  265. old = sha_deletes[0]
  266. if num_extra_adds:
  267. for new in sha_adds[-num_extra_adds:]:
  268. add_paths.add(new.path)
  269. self._changes.append(TreeChange(CHANGE_COPY, old, new))
  270. self._prune(add_paths, delete_paths)
  271. def _find_content_renames(self):
  272. # TODO: Optimizations:
  273. # - Compare object sizes before counting blocks.
  274. # - Skip if delete's S_IFMT differs from all adds.
  275. # - Skip if adds or deletes is empty.
  276. candidates = []
  277. for delete in self._deletes:
  278. if S_ISGITLINK(delete.old.mode):
  279. continue # Git links don't exist in this repo.
  280. old_sha = delete.old.sha
  281. old_obj = self._store[old_sha]
  282. old_blocks = _count_blocks(old_obj)
  283. for add in self._adds:
  284. if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode):
  285. continue
  286. new_obj = self._store[add.new.sha]
  287. score = _similarity_score(old_obj, new_obj,
  288. block_cache={old_sha: old_blocks})
  289. if score > self._rename_threshold:
  290. rename = TreeChange(CHANGE_RENAME, delete.old, add.new)
  291. candidates.append((-score, rename))
  292. # Sort scores from highest to lowest, but keep names in ascending order.
  293. candidates.sort()
  294. delete_paths = set()
  295. add_paths = set()
  296. for _, change in candidates:
  297. new_path = change.new.path
  298. if new_path in add_paths:
  299. continue
  300. old_path = change.old.path
  301. if old_path in delete_paths:
  302. change = TreeChange(CHANGE_COPY, change.old, change.new)
  303. delete_paths.add(old_path)
  304. add_paths.add(new_path)
  305. self._changes.append(change)
  306. self._prune(add_paths, delete_paths)
  307. def _sorted_changes(self):
  308. result = []
  309. result.extend(self._adds)
  310. result.extend(self._deletes)
  311. result.extend(self._changes)
  312. result.sort(key=_tree_change_key)
  313. return result
  314. def changes_with_renames(self):
  315. """Iterate TreeChanges between the two trees, with rename detection."""
  316. self._collect_changes()
  317. self._find_exact_renames()
  318. self._find_content_renames()
  319. return self._sorted_changes()