diff_tree.py 18 KB

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