2
0

diff_tree.py 22 KB

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