diff_tree.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. _MAX_FILES = 200
  41. _REWRITE_THRESHOLD = None
  42. class TreeChange(TreeChangeTuple):
  43. """Class encapsulating a single change between two trees."""
  44. @classmethod
  45. def add(cls, new):
  46. return cls(CHANGE_ADD, _NULL_ENTRY, new)
  47. @classmethod
  48. def delete(cls, old):
  49. return cls(CHANGE_DELETE, old, _NULL_ENTRY)
  50. def _tree_entries(path, tree):
  51. result = []
  52. if not tree:
  53. return result
  54. for entry in tree.iteritems(name_order=True):
  55. result.append(entry.in_path(path))
  56. return result
  57. def _merge_entries(path, tree1, tree2):
  58. """Merge the entries of two trees.
  59. :param path: A path to prepend to all tree entry names.
  60. :param tree1: The first Tree object to iterate, or None.
  61. :param tree2: The second Tree object to iterate, or None.
  62. :return: A list of pairs of TreeEntry objects for each pair of entries in
  63. the trees. If an entry exists in one tree but not the other, the other
  64. entry will have all attributes set to None. If neither entry's path is
  65. None, they are guaranteed to match.
  66. """
  67. entries1 = _tree_entries(path, tree1)
  68. entries2 = _tree_entries(path, tree2)
  69. i1 = i2 = 0
  70. len1 = len(entries1)
  71. len2 = len(entries2)
  72. result = []
  73. while i1 < len1 and i2 < len2:
  74. entry1 = entries1[i1]
  75. entry2 = entries2[i2]
  76. if entry1.path < entry2.path:
  77. result.append((entry1, _NULL_ENTRY))
  78. i1 += 1
  79. elif entry1.path > entry2.path:
  80. result.append((_NULL_ENTRY, entry2))
  81. i2 += 1
  82. else:
  83. result.append((entry1, entry2))
  84. i1 += 1
  85. i2 += 1
  86. for i in xrange(i1, len1):
  87. result.append((entries1[i], _NULL_ENTRY))
  88. for i in xrange(i2, len2):
  89. result.append((_NULL_ENTRY, entries2[i]))
  90. return result
  91. def _is_tree(entry):
  92. mode = entry.mode
  93. if mode is None:
  94. return False
  95. return stat.S_ISDIR(mode)
  96. def walk_trees(store, tree1_id, tree2_id, prune_identical=False):
  97. """Recursively walk all the entries of two trees.
  98. Iteration is depth-first pre-order, as in e.g. os.walk.
  99. :param store: An ObjectStore for looking up objects.
  100. :param tree1_id: The SHA of the first Tree object to iterate, or None.
  101. :param tree2_id: The SHA of the second Tree object to iterate, or None.
  102. :param prune_identical: If True, identical subtrees will not be walked.
  103. :yield: Pairs of TreeEntry objects for each pair of entries in the trees and
  104. their subtrees recursively. If an entry exists in one tree but not the
  105. other, the other entry will have all attributes set to None. If neither
  106. entry's path is None, they are guaranteed to match.
  107. """
  108. # This could be fairly easily generalized to >2 trees if we find a use case.
  109. mode1 = tree1_id and stat.S_IFDIR or None
  110. mode2 = tree2_id and stat.S_IFDIR or None
  111. todo = [(TreeEntry('', mode1, tree1_id), TreeEntry('', mode2, tree2_id))]
  112. while todo:
  113. entry1, entry2 = todo.pop()
  114. is_tree1 = _is_tree(entry1)
  115. is_tree2 = _is_tree(entry2)
  116. if prune_identical and is_tree1 and is_tree2 and entry1 == entry2:
  117. continue
  118. tree1 = is_tree1 and store[entry1.sha] or None
  119. tree2 = is_tree2 and store[entry2.sha] or None
  120. path = entry1.path or entry2.path
  121. todo.extend(reversed(_merge_entries(path, tree1, tree2)))
  122. yield entry1, entry2
  123. def _skip_tree(entry):
  124. if entry.mode is None or stat.S_ISDIR(entry.mode):
  125. return _NULL_ENTRY
  126. return entry
  127. def tree_changes(store, tree1_id, tree2_id, want_unchanged=False):
  128. """Find the differences between the contents of two trees.
  129. :param store: An ObjectStore for looking up objects.
  130. :param tree1_id: The SHA of the source tree.
  131. :param tree2_id: The SHA of the target tree.
  132. :param want_unchanged: If True, include TreeChanges for unmodified entries
  133. as well.
  134. :yield: TreeChange instances for each change between the source and target
  135. tree.
  136. """
  137. entries = walk_trees(store, tree1_id, tree2_id,
  138. prune_identical=(not want_unchanged))
  139. for entry1, entry2 in entries:
  140. if entry1 == entry2 and not want_unchanged:
  141. continue
  142. # Treat entries for trees as missing.
  143. entry1 = _skip_tree(entry1)
  144. entry2 = _skip_tree(entry2)
  145. if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY:
  146. if stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode):
  147. # File type changed: report as delete/add.
  148. yield TreeChange.delete(entry1)
  149. entry1 = _NULL_ENTRY
  150. change_type = CHANGE_ADD
  151. elif entry1 == entry2:
  152. change_type = CHANGE_UNCHANGED
  153. else:
  154. change_type = CHANGE_MODIFY
  155. elif entry1 != _NULL_ENTRY:
  156. change_type = CHANGE_DELETE
  157. elif entry2 != _NULL_ENTRY:
  158. change_type = CHANGE_ADD
  159. else:
  160. # Both were None because at least one was a tree.
  161. continue
  162. yield TreeChange(change_type, entry1, entry2)
  163. _BLOCK_SIZE = 64
  164. def _count_blocks(obj):
  165. """Count the blocks in an object.
  166. Splits the data into blocks either on lines or <=64-byte chunks of lines.
  167. :param obj: The object to count blocks for.
  168. :return: A dict of block hashcode -> total bytes occurring.
  169. """
  170. block_counts = defaultdict(int)
  171. block = StringIO()
  172. n = 0
  173. # Cache attrs as locals to avoid expensive lookups in the inner loop.
  174. block_write = block.write
  175. block_seek = block.seek
  176. block_truncate = block.truncate
  177. block_getvalue = block.getvalue
  178. for c in itertools.chain(*obj.as_raw_chunks()):
  179. block_write(c)
  180. n += 1
  181. if c == '\n' or n == _BLOCK_SIZE:
  182. value = block_getvalue()
  183. block_counts[hash(value)] += len(value)
  184. block_seek(0)
  185. block_truncate()
  186. n = 0
  187. if n > 0:
  188. last_block = block_getvalue()
  189. block_counts[hash(last_block)] += len(last_block)
  190. return block_counts
  191. def _common_bytes(blocks1, blocks2):
  192. """Count the number of common bytes in two block count dicts.
  193. :param block1: The first dict of block hashcode -> total bytes.
  194. :param block2: The second dict of block hashcode -> total bytes.
  195. :return: The number of bytes in common between blocks1 and blocks2. This is
  196. only approximate due to possible hash collisions.
  197. """
  198. # Iterate over the smaller of the two dicts, since this is symmetrical.
  199. if len(blocks1) > len(blocks2):
  200. blocks1, blocks2 = blocks2, blocks1
  201. score = 0
  202. for block, count1 in blocks1.iteritems():
  203. count2 = blocks2.get(block)
  204. if count2:
  205. score += min(count1, count2)
  206. return score
  207. def _similarity_score(obj1, obj2, block_cache=None):
  208. """Compute a similarity score for two objects.
  209. :param obj1: The first object to score.
  210. :param obj2: The second object to score.
  211. :param block_cache: An optional dict of SHA to block counts to cache results
  212. between calls.
  213. :return: The similarity score between the two objects, defined as the number
  214. of bytes in common between the two objects divided by the maximum size,
  215. scaled to the range 0-100.
  216. """
  217. if block_cache is None:
  218. block_cache = {}
  219. if obj1.id not in block_cache:
  220. block_cache[obj1.id] = _count_blocks(obj1)
  221. if obj2.id not in block_cache:
  222. block_cache[obj2.id] = _count_blocks(obj2)
  223. common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id])
  224. max_size = max(obj1.raw_length(), obj2.raw_length())
  225. if not max_size:
  226. return _MAX_SCORE
  227. return int(float(common_bytes) * _MAX_SCORE / max_size)
  228. def _tree_change_key(entry):
  229. # Sort by old path then new path. If only one exists, use it for both keys.
  230. path1 = entry.old.path
  231. path2 = entry.new.path
  232. if path1 is None:
  233. path1 = path2
  234. if path2 is None:
  235. path2 = path1
  236. return (path1, path2)
  237. class RenameDetector(object):
  238. """Object for handling rename detection between two trees."""
  239. def __init__(self, store, tree1_id, tree2_id,
  240. rename_threshold=_RENAME_THRESHOLD, max_files=_MAX_FILES,
  241. rewrite_threshold=_REWRITE_THRESHOLD,
  242. find_copies_harder=False):
  243. """Initialize the rename detector.
  244. :param store: An ObjectStore for looking up objects.
  245. :param tree1_id: The SHA of the first Tree.
  246. :param tree2_id: The SHA of the second Tree.
  247. :param rename_threshold: The threshold similarity score for considering
  248. an add/delete pair to be a rename/copy; see _similarity_score.
  249. :param max_files: The maximum number of adds and deletes to consider, or
  250. None for no limit. The detector is guaranteed to compare no more
  251. than max_files ** 2 add/delete pairs. This limit is provided because
  252. rename detection can be quadratic in the project size. If the limit
  253. is exceeded, no content rename detection is attempted.
  254. :param rewrite_threshold: The threshold similarity score below which a
  255. modify should be considered a delete/add, or None to not break
  256. modifies; see _similarity_score.
  257. :param find_copies_harder: If True, consider unmodified files when
  258. detecting copies.
  259. """
  260. self._tree1_id = tree1_id
  261. self._tree2_id = tree2_id
  262. self._store = store
  263. self._rename_threshold = rename_threshold
  264. self._rewrite_threshold = rewrite_threshold
  265. self._max_files = max_files
  266. self._find_copies_harder = find_copies_harder
  267. self._adds = []
  268. self._deletes = []
  269. self._changes = []
  270. def _should_split(self, change):
  271. if (self._rewrite_threshold is None or change.type != CHANGE_MODIFY or
  272. change.old.sha == change.new.sha):
  273. return False
  274. old_obj = self._store[change.old.sha]
  275. new_obj = self._store[change.new.sha]
  276. return _similarity_score(old_obj, new_obj) < self._rewrite_threshold
  277. def _collect_changes(self):
  278. for change in tree_changes(self._store, self._tree1_id, self._tree2_id,
  279. want_unchanged=self._find_copies_harder):
  280. if change.type == CHANGE_ADD:
  281. self._adds.append(change)
  282. elif change.type == CHANGE_DELETE:
  283. self._deletes.append(change)
  284. elif self._should_split(change):
  285. self._deletes.append(TreeChange.delete(change.old))
  286. self._adds.append(TreeChange.add(change.new))
  287. elif (self._find_copies_harder and (
  288. change.type == CHANGE_MODIFY or change.type == CHANGE_UNCHANGED)):
  289. # Treat modified/unchanged as deleted rather than splitting it,
  290. # to avoid spurious renames.
  291. self._deletes.append(change)
  292. else:
  293. self._changes.append(change)
  294. def _prune(self, add_paths, delete_paths):
  295. self._adds = [a for a in self._adds if a.new.path not in add_paths]
  296. self._deletes = [d for d in self._deletes
  297. if d.old.path not in delete_paths]
  298. def _find_exact_renames(self):
  299. add_map = defaultdict(list)
  300. for add in self._adds:
  301. add_map[add.new.sha].append(add.new)
  302. delete_map = defaultdict(list)
  303. for delete in self._deletes:
  304. # Keep track of whether the delete was actually marked as a delete.
  305. # If not, it must have been added due to find_copies_harder, and
  306. # needs to be marked as a copy.
  307. is_delete = delete.type == CHANGE_DELETE
  308. delete_map[delete.old.sha].append((delete.old, is_delete))
  309. add_paths = set()
  310. delete_paths = set()
  311. for sha, sha_deletes in delete_map.iteritems():
  312. sha_adds = add_map[sha]
  313. for (old, is_delete), new in itertools.izip(sha_deletes, sha_adds):
  314. if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode):
  315. continue
  316. delete_paths.add(old.path)
  317. add_paths.add(new.path)
  318. new_type = is_delete and CHANGE_RENAME or CHANGE_COPY
  319. self._changes.append(TreeChange(new_type, old, new))
  320. num_extra_adds = len(sha_adds) - len(sha_deletes)
  321. # TODO(dborowitz): Less arbitrary way of dealing with extra copies.
  322. old = sha_deletes[0][0]
  323. if num_extra_adds:
  324. for new in sha_adds[-num_extra_adds:]:
  325. add_paths.add(new.path)
  326. self._changes.append(TreeChange(CHANGE_COPY, old, new))
  327. self._prune(add_paths, delete_paths)
  328. def _find_content_renames(self):
  329. # TODO: Optimizations:
  330. # - Compare object sizes before counting blocks.
  331. # - Skip if delete's S_IFMT differs from all adds.
  332. # - Skip if adds or deletes is empty.
  333. # Match C git's behavior of not attempting to find content renames if
  334. # the matrix size exceeds the threshold.
  335. if len(self._adds) * len(self._deletes) > self._max_files ** 2:
  336. return
  337. check_paths = self._rename_threshold is not None
  338. candidates = []
  339. for delete in self._deletes:
  340. if S_ISGITLINK(delete.old.mode):
  341. continue # Git links don't exist in this repo.
  342. old_sha = delete.old.sha
  343. old_obj = self._store[old_sha]
  344. old_blocks = _count_blocks(old_obj)
  345. for add in self._adds:
  346. if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode):
  347. continue
  348. new_obj = self._store[add.new.sha]
  349. score = _similarity_score(old_obj, new_obj,
  350. block_cache={old_sha: old_blocks})
  351. if score > self._rename_threshold:
  352. if check_paths and delete.old.path == add.new.path:
  353. # If the paths match, this must be a split modify, so
  354. # make sure it comes out as a modify.
  355. new_type = CHANGE_MODIFY
  356. elif delete.type != CHANGE_DELETE:
  357. # If it's in deletes but not marked as a delete, it must
  358. # have been added due to find_copies_harder, and needs
  359. # to be marked as a copy.
  360. new_type = CHANGE_COPY
  361. else:
  362. new_type = CHANGE_RENAME
  363. rename = TreeChange(new_type, delete.old, add.new)
  364. candidates.append((-score, rename))
  365. # Sort scores from highest to lowest, but keep names in ascending order.
  366. candidates.sort()
  367. delete_paths = set()
  368. add_paths = set()
  369. for _, change in candidates:
  370. new_path = change.new.path
  371. if new_path in add_paths:
  372. continue
  373. old_path = change.old.path
  374. orig_type = change.type
  375. if old_path in delete_paths:
  376. change = TreeChange(CHANGE_COPY, change.old, change.new)
  377. # If the candidate was originally a copy, that means it came from a
  378. # modified or unchanged path, so we don't want to prune it.
  379. if orig_type != CHANGE_COPY:
  380. delete_paths.add(old_path)
  381. add_paths.add(new_path)
  382. self._changes.append(change)
  383. self._prune(add_paths, delete_paths)
  384. def _join_modifies(self):
  385. if self._rewrite_threshold is None:
  386. return
  387. modifies = {}
  388. delete_map = dict((d.old.path, d) for d in self._deletes)
  389. for add in self._adds:
  390. path = add.new.path
  391. delete = delete_map.get(path)
  392. if (delete is not None and
  393. stat.S_IFMT(delete.old.mode) == stat.S_IFMT(add.new.mode)):
  394. modifies[path] = TreeChange(CHANGE_MODIFY, delete.old, add.new)
  395. self._adds = [a for a in self._adds if a.new.path not in modifies]
  396. self._deletes = [a for a in self._deletes if a.new.path not in modifies]
  397. self._changes += modifies.values()
  398. def _sorted_changes(self):
  399. result = []
  400. result.extend(self._adds)
  401. result.extend(self._deletes)
  402. result.extend(self._changes)
  403. result.sort(key=_tree_change_key)
  404. return result
  405. def _prune_unchanged(self):
  406. self._deletes = [d for d in self._deletes if d.type != CHANGE_UNCHANGED]
  407. def changes_with_renames(self):
  408. """Iterate TreeChanges between the two trees, with rename detection."""
  409. self._collect_changes()
  410. self._find_exact_renames()
  411. self._find_content_renames()
  412. self._join_modifies()
  413. self._prune_unchanged()
  414. return self._sorted_changes()
  415. # Hold on to the pure-python implementations for testing.
  416. _is_tree_py = _is_tree
  417. _merge_entries_py = _merge_entries
  418. _count_blocks_py = _count_blocks
  419. try:
  420. # Try to import C versions
  421. from dulwich._diff_tree import _is_tree, _merge_entries, _count_blocks
  422. except ImportError:
  423. pass