Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

agriconnect / dulwich   python

Repository URL to install this package:

/ diff_tree.py

# diff_tree.py -- Utilities for diffing files and trees.
# Copyright (C) 2010 Google, Inc.
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these two licenses.
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
# You should have received a copy of the licenses; if not, see
# <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
# and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
# License, Version 2.0.

"""Utilities for diffing files and trees."""
import sys
from collections import (

from io import BytesIO
from itertools import chain
import stat

from dulwich.objects import (

# TreeChange type constants.
CHANGE_ADD = 'add'
CHANGE_MODIFY = 'modify'
CHANGE_DELETE = 'delete'
CHANGE_RENAME = 'rename'
CHANGE_COPY = 'copy'
CHANGE_UNCHANGED = 'unchanged'


_NULL_ENTRY = TreeEntry(None, None, None)

_MAX_SCORE = 100

class TreeChange(namedtuple('TreeChange', ['type', 'old', 'new'])):
    """Named tuple a single change between two trees."""

    def add(cls, new):
        return cls(CHANGE_ADD, _NULL_ENTRY, new)

    def delete(cls, old):
        return cls(CHANGE_DELETE, old, _NULL_ENTRY)

def _tree_entries(path, tree):
    result = []
    if not tree:
        return result
    for entry in tree.iteritems(name_order=True):
    return result

def _merge_entries(path, tree1, tree2):
    """Merge the entries of two trees.

    :param path: A path to prepend to all tree entry names.
    :param tree1: The first Tree object to iterate, or None.
    :param tree2: The second Tree object to iterate, or None.
    :return: A list of pairs of TreeEntry objects for each pair of entries in
        the trees. If an entry exists in one tree but not the other, the other
        entry will have all attributes set to None. If neither entry's path is
        None, they are guaranteed to match.
    entries1 = _tree_entries(path, tree1)
    entries2 = _tree_entries(path, tree2)
    i1 = i2 = 0
    len1 = len(entries1)
    len2 = len(entries2)

    result = []
    while i1 < len1 and i2 < len2:
        entry1 = entries1[i1]
        entry2 = entries2[i2]
        if entry1.path < entry2.path:
            result.append((entry1, _NULL_ENTRY))
            i1 += 1
        elif entry1.path > entry2.path:
            result.append((_NULL_ENTRY, entry2))
            i2 += 1
            result.append((entry1, entry2))
            i1 += 1
            i2 += 1
    for i in range(i1, len1):
        result.append((entries1[i], _NULL_ENTRY))
    for i in range(i2, len2):
        result.append((_NULL_ENTRY, entries2[i]))
    return result

def _is_tree(entry):
    mode = entry.mode
    if mode is None:
        return False
    return stat.S_ISDIR(mode)

def walk_trees(store, tree1_id, tree2_id, prune_identical=False):
    """Recursively walk all the entries of two trees.

    Iteration is depth-first pre-order, as in e.g. os.walk.

    :param store: An ObjectStore for looking up objects.
    :param tree1_id: The SHA of the first Tree object to iterate, or None.
    :param tree2_id: The SHA of the second Tree object to iterate, or None.
    :param prune_identical: If True, identical subtrees will not be walked.
    :return: Iterator over Pairs of TreeEntry objects for each pair of entries
        in the trees and their subtrees recursively. If an entry exists in one
        tree but not the other, the other entry will have all attributes set
        to None. If neither entry's path is None, they are guaranteed to
    # This could be fairly easily generalized to >2 trees if we find a use
    # case.
    mode1 = tree1_id and stat.S_IFDIR or None
    mode2 = tree2_id and stat.S_IFDIR or None
    todo = [(TreeEntry(b'', mode1, tree1_id), TreeEntry(b'', mode2, tree2_id))]
    while todo:
        entry1, entry2 = todo.pop()
        is_tree1 = _is_tree(entry1)
        is_tree2 = _is_tree(entry2)
        if prune_identical and is_tree1 and is_tree2 and entry1 == entry2:

        tree1 = is_tree1 and store[entry1.sha] or None
        tree2 = is_tree2 and store[entry2.sha] or None
        path = entry1.path or entry2.path
        todo.extend(reversed(_merge_entries(path, tree1, tree2)))
        yield entry1, entry2

def _skip_tree(entry, include_trees):
    if entry.mode is None or (not include_trees and stat.S_ISDIR(entry.mode)):
        return _NULL_ENTRY
    return entry

def tree_changes(store, tree1_id, tree2_id, want_unchanged=False,
                 rename_detector=None, include_trees=False,
    """Find the differences between the contents of two trees.

    :param store: An ObjectStore for looking up objects.
    :param tree1_id: The SHA of the source tree.
    :param tree2_id: The SHA of the target tree.
    :param want_unchanged: If True, include TreeChanges for unmodified entries
        as well.
    :param include_trees: Whether to include trees
    :param rename_detector: RenameDetector object for detecting renames.
    :param change_type_same: Whether to report change types in the same
        entry or as delete+add.
    :return: Iterator over TreeChange instances for each change between the
        source and target tree.
    if include_trees and rename_detector is not None:
        raise NotImplementedError(
            'rename_detector and include_trees are mutually exclusive')
    if (rename_detector is not None and tree1_id is not None and
            tree2_id is not None):
        for change in rename_detector.changes_with_renames(
                tree1_id, tree2_id, want_unchanged=want_unchanged):
            yield change

    entries = walk_trees(store, tree1_id, tree2_id,
                         prune_identical=(not want_unchanged))
    for entry1, entry2 in entries:
        if entry1 == entry2 and not want_unchanged:

        # Treat entries for trees as missing.
        entry1 = _skip_tree(entry1, include_trees)
        entry2 = _skip_tree(entry2, include_trees)

        if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY:
            if (stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode)
                    and not change_type_same):
                # File type changed: report as delete/add.
                yield TreeChange.delete(entry1)
                entry1 = _NULL_ENTRY
                change_type = CHANGE_ADD
            elif entry1 == entry2:
                change_type = CHANGE_UNCHANGED
                change_type = CHANGE_MODIFY
        elif entry1 != _NULL_ENTRY:
            change_type = CHANGE_DELETE
        elif entry2 != _NULL_ENTRY:
            change_type = CHANGE_ADD
            # Both were None because at least one was a tree.
        yield TreeChange(change_type, entry1, entry2)

def _all_eq(seq, key, value):
    for e in seq:
        if key(e) != value:
            return False
    return True

def _all_same(seq, key):
    return _all_eq(seq[1:], key, key(seq[0]))

def tree_changes_for_merge(store, parent_tree_ids, tree_id,
    """Get the tree changes for a merge tree relative to all its parents.

    :param store: An ObjectStore for looking up objects.
    :param parent_tree_ids: An iterable of the SHAs of the parent trees.
    :param tree_id: The SHA of the merge tree.
    :param rename_detector: RenameDetector object for detecting renames.

    :return: Iterator over lists of TreeChange objects, one per conflicted path
        in the merge.

        Each list contains one element per parent, with the TreeChange for that
        path relative to that parent. An element may be None if it never
        existed in one parent and was deleted in two others.

        A path is only included in the output if it is a conflict, i.e. its SHA
        in the merge tree is not found in any of the parents, or in the case of
        deletes, if not all of the old SHAs match.
    all_parent_changes = [tree_changes(store, t, tree_id,
                          for t in parent_tree_ids]
    num_parents = len(parent_tree_ids)
    changes_by_path = defaultdict(lambda: [None] * num_parents)

    # Organize by path.
    for i, parent_changes in enumerate(all_parent_changes):
        for change in parent_changes:
            if change.type == CHANGE_DELETE:
                path = change.old.path
                path = change.new.path
            changes_by_path[path][i] = change

    def old_sha(c):
        return c.old.sha

    def change_type(c):
        return c.type

    # Yield only conflicting changes.
    for _, changes in sorted(changes_by_path.items()):
        assert len(changes) == num_parents
        have = [c for c in changes if c is not None]
        if _all_eq(have, change_type, CHANGE_DELETE):
            if not _all_same(have, old_sha):
                yield changes
        elif not _all_same(have, change_type):
            yield changes
        elif None not in changes:
            # If no change was found relative to one parent, that means the SHA
            # must have matched the SHA in that parent, so it is not a
            # conflict.
            yield changes


def _count_blocks(obj):
    """Count the blocks in an object.

    Splits the data into blocks either on lines or <=64-byte chunks of lines.

    :param obj: The object to count blocks for.
    :return: A dict of block hashcode -> total bytes occurring.
    block_counts = defaultdict(int)
    block = BytesIO()
    n = 0

    # Cache attrs as locals to avoid expensive lookups in the inner loop.
    block_write = block.write
    block_seek = block.seek
    block_truncate = block.truncate
    block_getvalue = block.getvalue

    for c in chain(*obj.as_raw_chunks()):
        if sys.version_info[0] == 3:
            c = c.to_bytes(1, 'big')
        n += 1
        if c == b'\n' or n == _BLOCK_SIZE:
            value = block_getvalue()
            block_counts[hash(value)] += len(value)
            n = 0
    if n > 0:
        last_block = block_getvalue()
        block_counts[hash(last_block)] += len(last_block)
    return block_counts

def _common_bytes(blocks1, blocks2):
    """Count the number of common bytes in two block count dicts.

    :param block1: The first dict of block hashcode -> total bytes.
    :param block2: The second dict of block hashcode -> total bytes.
    :return: The number of bytes in common between blocks1 and blocks2. This is
        only approximate due to possible hash collisions.
    # Iterate over the smaller of the two dicts, since this is symmetrical.
    if len(blocks1) > len(blocks2):
        blocks1, blocks2 = blocks2, blocks1
    score = 0
    for block, count1 in blocks1.items():
        count2 = blocks2.get(block)
        if count2:
            score += min(count1, count2)
    return score

def _similarity_score(obj1, obj2, block_cache=None):
Loading ...