diff_tree.py 21 KB

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