diff_tree.py 22 KB

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