diff_tree.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 (rename_detector is not None and tree1_id is not None and
  156. tree2_id is not None):
  157. for change in rename_detector.changes_with_renames(
  158. tree1_id, tree2_id, want_unchanged=want_unchanged,
  159. include_trees=include_trees):
  160. yield change
  161. return
  162. entries = walk_trees(store, tree1_id, tree2_id,
  163. prune_identical=(not want_unchanged))
  164. for entry1, entry2 in entries:
  165. if entry1 == entry2 and not want_unchanged:
  166. continue
  167. # Treat entries for trees as missing.
  168. entry1 = _skip_tree(entry1, include_trees)
  169. entry2 = _skip_tree(entry2, include_trees)
  170. if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY:
  171. if (stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode)
  172. and not change_type_same):
  173. # File type changed: report as delete/add.
  174. yield TreeChange.delete(entry1)
  175. entry1 = _NULL_ENTRY
  176. change_type = CHANGE_ADD
  177. elif entry1 == entry2:
  178. change_type = CHANGE_UNCHANGED
  179. else:
  180. change_type = CHANGE_MODIFY
  181. elif entry1 != _NULL_ENTRY:
  182. change_type = CHANGE_DELETE
  183. elif entry2 != _NULL_ENTRY:
  184. change_type = CHANGE_ADD
  185. else:
  186. # Both were None because at least one was a tree.
  187. continue
  188. yield TreeChange(change_type, entry1, entry2)
  189. def _all_eq(seq, key, value):
  190. for e in seq:
  191. if key(e) != value:
  192. return False
  193. return True
  194. def _all_same(seq, key):
  195. return _all_eq(seq[1:], key, key(seq[0]))
  196. def tree_changes_for_merge(store, parent_tree_ids, tree_id,
  197. rename_detector=None):
  198. """Get the tree changes for a merge tree relative to all its parents.
  199. Args:
  200. store: An ObjectStore for looking up objects.
  201. parent_tree_ids: An iterable of the SHAs of the parent trees.
  202. tree_id: The SHA of the merge tree.
  203. rename_detector: RenameDetector object for detecting renames.
  204. Returns:
  205. Iterator over lists of TreeChange objects, one per conflicted path
  206. in the merge.
  207. Each list contains one element per parent, with the TreeChange for that
  208. path relative to that parent. An element may be None if it never
  209. existed in one parent and was deleted in two others.
  210. A path is only included in the output if it is a conflict, i.e. its SHA
  211. in the merge tree is not found in any of the parents, or in the case of
  212. deletes, if not all of the old SHAs match.
  213. """
  214. all_parent_changes = [tree_changes(store, t, tree_id,
  215. rename_detector=rename_detector)
  216. for t in parent_tree_ids]
  217. num_parents = len(parent_tree_ids)
  218. changes_by_path = defaultdict(lambda: [None] * num_parents)
  219. # Organize by path.
  220. for i, parent_changes in enumerate(all_parent_changes):
  221. for change in parent_changes:
  222. if change.type == CHANGE_DELETE:
  223. path = change.old.path
  224. else:
  225. path = change.new.path
  226. changes_by_path[path][i] = change
  227. def old_sha(c):
  228. return c.old.sha
  229. def change_type(c):
  230. return c.type
  231. # Yield only conflicting changes.
  232. for _, changes in sorted(changes_by_path.items()):
  233. assert len(changes) == num_parents
  234. have = [c for c in changes if c is not None]
  235. if _all_eq(have, change_type, CHANGE_DELETE):
  236. if not _all_same(have, old_sha):
  237. yield changes
  238. elif not _all_same(have, change_type):
  239. yield changes
  240. elif None not in changes:
  241. # If no change was found relative to one parent, that means the SHA
  242. # must have matched the SHA in that parent, so it is not a
  243. # conflict.
  244. yield changes
  245. _BLOCK_SIZE = 64
  246. def _count_blocks(obj):
  247. """Count the blocks in an object.
  248. Splits the data into blocks either on lines or <=64-byte chunks of lines.
  249. Args:
  250. obj: The object to count blocks for.
  251. Returns:
  252. A dict of block hashcode -> total bytes occurring.
  253. """
  254. block_counts = defaultdict(int)
  255. block = BytesIO()
  256. n = 0
  257. # Cache attrs as locals to avoid expensive lookups in the inner loop.
  258. block_write = block.write
  259. block_seek = block.seek
  260. block_truncate = block.truncate
  261. block_getvalue = block.getvalue
  262. for c in chain(*obj.as_raw_chunks()):
  263. if sys.version_info[0] == 3:
  264. c = c.to_bytes(1, 'big')
  265. block_write(c)
  266. n += 1
  267. if c == b'\n' or n == _BLOCK_SIZE:
  268. value = block_getvalue()
  269. block_counts[hash(value)] += len(value)
  270. block_seek(0)
  271. block_truncate()
  272. n = 0
  273. if n > 0:
  274. last_block = block_getvalue()
  275. block_counts[hash(last_block)] += len(last_block)
  276. return block_counts
  277. def _common_bytes(blocks1, blocks2):
  278. """Count the number of common bytes in two block count dicts.
  279. Args:
  280. block1: The first dict of block hashcode -> total bytes.
  281. block2: The second dict of block hashcode -> total bytes.
  282. Returns:
  283. The number of bytes in common between blocks1 and blocks2. This is
  284. only approximate due to possible hash collisions.
  285. """
  286. # Iterate over the smaller of the two dicts, since this is symmetrical.
  287. if len(blocks1) > len(blocks2):
  288. blocks1, blocks2 = blocks2, blocks1
  289. score = 0
  290. for block, count1 in blocks1.items():
  291. count2 = blocks2.get(block)
  292. if count2:
  293. score += min(count1, count2)
  294. return score
  295. def _similarity_score(obj1, obj2, block_cache=None):
  296. """Compute a similarity score for two objects.
  297. Args:
  298. obj1: The first object to score.
  299. obj2: The second object to score.
  300. block_cache: An optional dict of SHA to block counts to cache
  301. results between calls.
  302. Returns:
  303. The similarity score between the two objects, defined as the
  304. number of bytes in common between the two objects divided by the
  305. maximum size, scaled to the range 0-100.
  306. """
  307. if block_cache is None:
  308. block_cache = {}
  309. if obj1.id not in block_cache:
  310. block_cache[obj1.id] = _count_blocks(obj1)
  311. if obj2.id not in block_cache:
  312. block_cache[obj2.id] = _count_blocks(obj2)
  313. common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id])
  314. max_size = max(obj1.raw_length(), obj2.raw_length())
  315. if not max_size:
  316. return _MAX_SCORE
  317. return int(float(common_bytes) * _MAX_SCORE / max_size)
  318. def _tree_change_key(entry):
  319. # Sort by old path then new path. If only one exists, use it for both keys.
  320. path1 = entry.old.path
  321. path2 = entry.new.path
  322. if path1 is None:
  323. path1 = path2
  324. if path2 is None:
  325. path2 = path1
  326. return (path1, path2)
  327. class RenameDetector(object):
  328. """Object for handling rename detection between two trees."""
  329. def __init__(self, store, rename_threshold=RENAME_THRESHOLD,
  330. max_files=MAX_FILES,
  331. rewrite_threshold=REWRITE_THRESHOLD,
  332. find_copies_harder=False):
  333. """Initialize the rename detector.
  334. Args:
  335. store: An ObjectStore for looking up objects.
  336. rename_threshold: The threshold similarity score for considering
  337. an add/delete pair to be a rename/copy; see _similarity_score.
  338. max_files: The maximum number of adds and deletes to consider,
  339. or None for no limit. The detector is guaranteed to compare no more
  340. than max_files ** 2 add/delete pairs. This limit is provided
  341. because rename detection can be quadratic in the project size. If
  342. the limit is exceeded, no content rename detection is attempted.
  343. rewrite_threshold: The threshold similarity score below which a
  344. modify should be considered a delete/add, or None to not break
  345. modifies; see _similarity_score.
  346. find_copies_harder: If True, consider unmodified files when
  347. detecting copies.
  348. """
  349. self._store = store
  350. self._rename_threshold = rename_threshold
  351. self._rewrite_threshold = rewrite_threshold
  352. self._max_files = max_files
  353. self._find_copies_harder = find_copies_harder
  354. self._want_unchanged = False
  355. def _reset(self):
  356. self._adds = []
  357. self._deletes = []
  358. self._changes = []
  359. def _should_split(self, change):
  360. if (self._rewrite_threshold is None or change.type != CHANGE_MODIFY or
  361. change.old.sha == change.new.sha):
  362. return False
  363. old_obj = self._store[change.old.sha]
  364. new_obj = self._store[change.new.sha]
  365. return _similarity_score(old_obj, new_obj) < self._rewrite_threshold
  366. def _add_change(self, change):
  367. if change.type == CHANGE_ADD:
  368. self._adds.append(change)
  369. elif change.type == CHANGE_DELETE:
  370. self._deletes.append(change)
  371. elif self._should_split(change):
  372. self._deletes.append(TreeChange.delete(change.old))
  373. self._adds.append(TreeChange.add(change.new))
  374. elif ((self._find_copies_harder and change.type == CHANGE_UNCHANGED)
  375. or change.type == CHANGE_MODIFY):
  376. # Treat all modifies as potential deletes for rename detection,
  377. # but don't split them (to avoid spurious renames). Setting
  378. # find_copies_harder means we treat unchanged the same as
  379. # modified.
  380. self._deletes.append(change)
  381. else:
  382. self._changes.append(change)
  383. def _collect_changes(self, tree1_id, tree2_id):
  384. want_unchanged = self._find_copies_harder or self._want_unchanged
  385. for change in tree_changes(self._store, tree1_id, tree2_id,
  386. want_unchanged=want_unchanged,
  387. include_trees=self._include_trees):
  388. self._add_change(change)
  389. def _prune(self, add_paths, delete_paths):
  390. self._adds = [a for a in self._adds if a.new.path not in add_paths]
  391. self._deletes = [d for d in self._deletes
  392. if d.old.path not in delete_paths]
  393. def _find_exact_renames(self):
  394. add_map = defaultdict(list)
  395. for add in self._adds:
  396. add_map[add.new.sha].append(add.new)
  397. delete_map = defaultdict(list)
  398. for delete in self._deletes:
  399. # Keep track of whether the delete was actually marked as a delete.
  400. # If not, it needs to be marked as a copy.
  401. is_delete = delete.type == CHANGE_DELETE
  402. delete_map[delete.old.sha].append((delete.old, is_delete))
  403. add_paths = set()
  404. delete_paths = set()
  405. for sha, sha_deletes in delete_map.items():
  406. sha_adds = add_map[sha]
  407. for (old, is_delete), new in zip(sha_deletes, sha_adds):
  408. if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode):
  409. continue
  410. if is_delete:
  411. delete_paths.add(old.path)
  412. add_paths.add(new.path)
  413. new_type = is_delete and CHANGE_RENAME or CHANGE_COPY
  414. self._changes.append(TreeChange(new_type, old, new))
  415. num_extra_adds = len(sha_adds) - len(sha_deletes)
  416. # TODO(dborowitz): Less arbitrary way of dealing with extra copies.
  417. old = sha_deletes[0][0]
  418. if num_extra_adds > 0:
  419. for new in sha_adds[-num_extra_adds:]:
  420. add_paths.add(new.path)
  421. self._changes.append(TreeChange(CHANGE_COPY, old, new))
  422. self._prune(add_paths, delete_paths)
  423. def _should_find_content_renames(self):
  424. return len(self._adds) * len(self._deletes) <= self._max_files ** 2
  425. def _rename_type(self, check_paths, delete, add):
  426. if check_paths and delete.old.path == add.new.path:
  427. # If the paths match, this must be a split modify, so make sure it
  428. # comes out as a modify.
  429. return CHANGE_MODIFY
  430. elif delete.type != CHANGE_DELETE:
  431. # If it's in deletes but not marked as a delete, it must have been
  432. # added due to find_copies_harder, and needs to be marked as a
  433. # copy.
  434. return CHANGE_COPY
  435. return CHANGE_RENAME
  436. def _find_content_rename_candidates(self):
  437. candidates = self._candidates = []
  438. # TODO: Optimizations:
  439. # - Compare object sizes before counting blocks.
  440. # - Skip if delete's S_IFMT differs from all adds.
  441. # - Skip if adds or deletes is empty.
  442. # Match C git's behavior of not attempting to find content renames if
  443. # the matrix size exceeds the threshold.
  444. if not self._should_find_content_renames():
  445. return
  446. block_cache = {}
  447. check_paths = self._rename_threshold is not None
  448. for delete in self._deletes:
  449. if S_ISGITLINK(delete.old.mode):
  450. continue # Git links don't exist in this repo.
  451. old_sha = delete.old.sha
  452. old_obj = self._store[old_sha]
  453. block_cache[old_sha] = _count_blocks(old_obj)
  454. for add in self._adds:
  455. if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode):
  456. continue
  457. new_obj = self._store[add.new.sha]
  458. score = _similarity_score(old_obj, new_obj,
  459. block_cache=block_cache)
  460. if score > self._rename_threshold:
  461. new_type = self._rename_type(check_paths, delete, add)
  462. rename = TreeChange(new_type, delete.old, add.new)
  463. candidates.append((-score, rename))
  464. def _choose_content_renames(self):
  465. # Sort scores from highest to lowest, but keep names in ascending
  466. # order.
  467. self._candidates.sort()
  468. delete_paths = set()
  469. add_paths = set()
  470. for _, change in self._candidates:
  471. new_path = change.new.path
  472. if new_path in add_paths:
  473. continue
  474. old_path = change.old.path
  475. orig_type = change.type
  476. if old_path in delete_paths:
  477. change = TreeChange(CHANGE_COPY, change.old, change.new)
  478. # If the candidate was originally a copy, that means it came from a
  479. # modified or unchanged path, so we don't want to prune it.
  480. if orig_type != CHANGE_COPY:
  481. delete_paths.add(old_path)
  482. add_paths.add(new_path)
  483. self._changes.append(change)
  484. self._prune(add_paths, delete_paths)
  485. def _join_modifies(self):
  486. if self._rewrite_threshold is None:
  487. return
  488. modifies = {}
  489. delete_map = dict((d.old.path, d) for d in self._deletes)
  490. for add in self._adds:
  491. path = add.new.path
  492. delete = delete_map.get(path)
  493. if (delete is not None and
  494. stat.S_IFMT(delete.old.mode) == stat.S_IFMT(add.new.mode)):
  495. modifies[path] = TreeChange(CHANGE_MODIFY, delete.old, add.new)
  496. self._adds = [a for a in self._adds if a.new.path not in modifies]
  497. self._deletes = [a for a in self._deletes if a.new.path not in
  498. modifies]
  499. self._changes += modifies.values()
  500. def _sorted_changes(self):
  501. result = []
  502. result.extend(self._adds)
  503. result.extend(self._deletes)
  504. result.extend(self._changes)
  505. result.sort(key=_tree_change_key)
  506. return result
  507. def _prune_unchanged(self):
  508. if self._want_unchanged:
  509. return
  510. self._deletes = [
  511. d for d in self._deletes if d.type != CHANGE_UNCHANGED]
  512. def changes_with_renames(self, tree1_id, tree2_id, want_unchanged=False,
  513. include_trees=False):
  514. """Iterate TreeChanges between two tree SHAs, with rename detection."""
  515. self._reset()
  516. self._want_unchanged = want_unchanged
  517. self._include_trees = include_trees
  518. self._collect_changes(tree1_id, tree2_id)
  519. self._find_exact_renames()
  520. self._find_content_rename_candidates()
  521. self._choose_content_renames()
  522. self._join_modifies()
  523. self._prune_unchanged()
  524. return self._sorted_changes()
  525. # Hold on to the pure-python implementations for testing.
  526. _is_tree_py = _is_tree
  527. _merge_entries_py = _merge_entries
  528. _count_blocks_py = _count_blocks
  529. try:
  530. # Try to import C versions
  531. from dulwich._diff_tree import _is_tree, _merge_entries, _count_blocks
  532. except ImportError:
  533. pass