~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Jonathan Riddell
  • Date: 2011-09-16 15:37:58 UTC
  • mto: This revision was merged to the branch mainline in revision 6146.
  • Revision ID: jriddell@canonical.com-20110916153758-y936k3hysjc1tphy
update tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
lazy_import(globals(), """
21
21
from bzrlib import (
22
22
    branch as _mod_branch,
 
23
    cleanup,
23
24
    conflicts as _mod_conflicts,
24
25
    debug,
25
26
    generate_ids,
37
38
    versionedfile,
38
39
    workingtree,
39
40
    )
40
 
from bzrlib.cleanup import OperationWithCleanups
 
41
from bzrlib.i18n import gettext
41
42
""")
42
43
from bzrlib import (
43
44
    decorators,
53
54
 
54
55
def transform_tree(from_tree, to_tree, interesting_ids=None):
55
56
    from_tree.lock_tree_write()
56
 
    operation = OperationWithCleanups(merge_inner)
 
57
    operation = cleanup.OperationWithCleanups(merge_inner)
57
58
    operation.add_cleanup(from_tree.unlock)
58
59
    operation.run_simple(from_tree.branch, to_tree, from_tree,
59
60
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
62
63
class MergeHooks(hooks.Hooks):
63
64
 
64
65
    def __init__(self):
65
 
        hooks.Hooks.__init__(self)
66
 
        self.create_hook(hooks.HookPoint('merge_file_content',
 
66
        hooks.Hooks.__init__(self, "bzrlib.merge", "Merger.hooks")
 
67
        self.add_hook('merge_file_content',
67
68
            "Called with a bzrlib.merge.Merger object to create a per file "
68
69
            "merge object when starting a merge. "
69
70
            "Should return either None or a subclass of "
73
74
            "side has deleted the file and the other has changed it). "
74
75
            "See the AbstractPerFileMerger API docs for details on how it is "
75
76
            "used by merge.",
76
 
            (2, 1), None))
 
77
            (2, 1))
77
78
 
78
79
 
79
80
class AbstractPerFileMerger(object):
92
93
        """Attempt to merge the contents of a single file.
93
94
        
94
95
        :param merge_params: A bzrlib.merge.MergeHookParams
95
 
        :return : A tuple of (status, chunks), where status is one of
 
96
        :return: A tuple of (status, chunks), where status is one of
96
97
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
97
98
            is 'success' or 'conflicted', then chunks should be an iterable of
98
99
            strings for the new file contents.
458
459
    @deprecated_method(deprecated_in((2, 1, 0)))
459
460
    def file_revisions(self, file_id):
460
461
        self.ensure_revision_trees()
461
 
        def get_id(tree, file_id):
462
 
            revision_id = tree.inventory[file_id].revision
463
 
            return revision_id
464
462
        if self.this_rev_id is None:
465
463
            if self.this_basis_tree.get_file_sha1(file_id) != \
466
464
                self.this_tree.get_file_sha1(file_id):
467
465
                raise errors.WorkingTreeNotRevision(self.this_tree)
468
466
 
469
467
        trees = (self.this_basis_tree, self.other_tree)
470
 
        return [get_id(tree, file_id) for tree in trees]
 
468
        return [tree.get_file_revision(file_id) for tree in trees]
471
469
 
472
470
    @deprecated_method(deprecated_in((2, 1, 0)))
473
471
    def check_basis(self, check_clean, require_commits=True):
501
499
    def _add_parent(self):
502
500
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
503
501
        new_parent_trees = []
504
 
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
 
502
        operation = cleanup.OperationWithCleanups(
 
503
            self.this_tree.set_parent_trees)
505
504
        for revision_id in new_parents:
506
505
            try:
507
506
                tree = self.revision_tree(revision_id)
582
581
            elif len(lcas) == 1:
583
582
                self.base_rev_id = list(lcas)[0]
584
583
            else: # len(lcas) > 1
 
584
                self._is_criss_cross = True
585
585
                if len(lcas) > 2:
586
586
                    # find_unique_lca can only handle 2 nodes, so we have to
587
587
                    # start back at the beginning. It is a shame to traverse
592
592
                else:
593
593
                    self.base_rev_id = self.revision_graph.find_unique_lca(
594
594
                                            *lcas)
595
 
                self._is_criss_cross = True
 
595
                sorted_lca_keys = self.revision_graph.find_merge_order(                
 
596
                    revisions[0], lcas)
 
597
                if self.base_rev_id == _mod_revision.NULL_REVISION:
 
598
                    self.base_rev_id = sorted_lca_keys[0]
 
599
                
596
600
            if self.base_rev_id == _mod_revision.NULL_REVISION:
597
601
                raise errors.UnrelatedBranches()
598
602
            if self._is_criss_cross:
599
603
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
600
604
                              ' help criss-cross.')
601
605
                trace.mutter('Criss-cross lcas: %r' % lcas)
602
 
                interesting_revision_ids = [self.base_rev_id]
603
 
                interesting_revision_ids.extend(lcas)
 
606
                if self.base_rev_id in lcas:
 
607
                    trace.mutter('Unable to find unique lca. '
 
608
                                 'Fallback %r as best option.' % self.base_rev_id)
 
609
                interesting_revision_ids = set(lcas)
 
610
                interesting_revision_ids.add(self.base_rev_id)
604
611
                interesting_trees = dict((t.get_revision_id(), t)
605
612
                    for t in self.this_branch.repository.revision_trees(
606
613
                        interesting_revision_ids))
607
614
                self._cached_trees.update(interesting_trees)
608
 
                self.base_tree = interesting_trees.pop(self.base_rev_id)
609
 
                sorted_lca_keys = self.revision_graph.find_merge_order(
610
 
                    revisions[0], lcas)
 
615
                if self.base_rev_id in lcas:
 
616
                    self.base_tree = interesting_trees[self.base_rev_id]
 
617
                else:
 
618
                    self.base_tree = interesting_trees.pop(self.base_rev_id)
611
619
                self._lca_trees = [interesting_trees[key]
612
620
                                   for key in sorted_lca_keys]
613
621
            else:
692
700
        return merge
693
701
 
694
702
    def do_merge(self):
695
 
        operation = OperationWithCleanups(self._do_merge_to)
 
703
        operation = cleanup.OperationWithCleanups(self._do_merge_to)
696
704
        self.this_tree.lock_tree_write()
697
705
        operation.add_cleanup(self.this_tree.unlock)
698
706
        if self.base_tree is not None:
704
712
        merge = operation.run_simple()
705
713
        if len(merge.cooked_conflicts) == 0:
706
714
            if not self.ignore_zero and not trace.is_quiet():
707
 
                trace.note("All changes applied successfully.")
 
715
                trace.note(gettext("All changes applied successfully."))
708
716
        else:
709
 
            trace.note("%d conflicts encountered."
 
717
            trace.note(gettext("%d conflicts encountered.")
710
718
                       % len(merge.cooked_conflicts))
711
719
 
712
720
        return len(merge.cooked_conflicts)
804
812
            warnings.warn("pb argument to Merge3Merger is deprecated")
805
813
 
806
814
    def do_merge(self):
807
 
        operation = OperationWithCleanups(self._do_merge)
 
815
        operation = cleanup.OperationWithCleanups(self._do_merge)
808
816
        self.this_tree.lock_tree_write()
809
817
        operation.add_cleanup(self.this_tree.unlock)
810
818
        self.base_tree.lock_read()
825
833
            pass
826
834
 
827
835
    def make_preview_transform(self):
828
 
        operation = OperationWithCleanups(self._make_preview_transform)
 
836
        operation = cleanup.OperationWithCleanups(self._make_preview_transform)
829
837
        self.base_tree.lock_read()
830
838
        operation.add_cleanup(self.base_tree.unlock)
831
839
        self.other_tree.lock_read()
861
869
                    executable3, file_status, resolver=resolver)
862
870
        finally:
863
871
            child_pb.finished()
864
 
        self.fix_root()
 
872
        self.tt.fixup_new_roots()
865
873
        self._finish_computing_transform()
866
874
 
867
875
    def _finish_computing_transform(self):
881
889
                self.tt.iter_changes(), self.change_reporter)
882
890
        self.cook_conflicts(fs_conflicts)
883
891
        for conflict in self.cooked_conflicts:
884
 
            trace.warning(conflict)
 
892
            trace.warning(unicode(conflict))
885
893
 
886
894
    def _entries3(self):
887
895
        """Gather data about files modified between three trees.
894
902
        """
895
903
        result = []
896
904
        iterator = self.other_tree.iter_changes(self.base_tree,
897
 
                include_unchanged=True, specific_files=self.interesting_files,
 
905
                specific_files=self.interesting_files,
898
906
                extra_trees=[self.this_tree])
899
907
        this_entries = dict((e.file_id, e) for p, e in
900
908
                            self.this_tree.iter_entries_by_dir(
926
934
        it then compares with THIS and BASE.
927
935
 
928
936
        For the multi-valued entries, the format will be (BASE, [lca1, lca2])
929
 
        :return: [(file_id, changed, parents, names, executable)]
930
 
            file_id     Simple file_id of the entry
931
 
            changed     Boolean, True if the kind or contents changed
932
 
                        else False
933
 
            parents     ((base, [parent_id, in, lcas]), parent_id_other,
934
 
                         parent_id_this)
935
 
            names       ((base, [name, in, lcas]), name_in_other, name_in_this)
936
 
            executable  ((base, [exec, in, lcas]), exec_in_other, exec_in_this)
 
937
 
 
938
        :return: [(file_id, changed, parents, names, executable)], where:
 
939
 
 
940
            * file_id: Simple file_id of the entry
 
941
            * changed: Boolean, True if the kind or contents changed else False
 
942
            * parents: ((base, [parent_id, in, lcas]), parent_id_other,
 
943
                        parent_id_this)
 
944
            * names:   ((base, [name, in, lcas]), name_in_other, name_in_this)
 
945
            * executable: ((base, [exec, in, lcas]), exec_in_other,
 
946
                        exec_in_this)
937
947
        """
938
948
        if self.interesting_files is not None:
939
949
            lookup_trees = [self.this_tree, self.base_tree]
981
991
                else:
982
992
                    lca_entries.append(lca_ie)
983
993
 
984
 
            if file_id in base_inventory:
 
994
            if base_inventory.has_id(file_id):
985
995
                base_ie = base_inventory[file_id]
986
996
            else:
987
997
                base_ie = _none_entry
988
998
 
989
 
            if file_id in this_inventory:
 
999
            if this_inventory.has_id(file_id):
990
1000
                this_ie = this_inventory[file_id]
991
1001
            else:
992
1002
                this_ie = _none_entry
1084
1094
                          ))
1085
1095
        return result
1086
1096
 
 
1097
    @deprecated_method(deprecated_in((2, 4, 0)))
1087
1098
    def fix_root(self):
1088
1099
        if self.tt.final_kind(self.tt.root) is None:
1089
1100
            self.tt.cancel_deletion(self.tt.root)
1096
1107
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1097
1108
        if other_root == self.tt.root:
1098
1109
            return
1099
 
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1100
 
            # the other tree's root is a non-root in the current tree (as when
1101
 
            # a previously unrelated branch is merged into another)
 
1110
        if self.this_tree.inventory.has_id(
 
1111
            self.other_tree.inventory.root.file_id):
 
1112
            # the other tree's root is a non-root in the current tree (as
 
1113
            # when a previously unrelated branch is merged into another)
1102
1114
            return
1103
1115
        if self.tt.final_kind(other_root) is not None:
1104
1116
            other_root_is_present = True
1109
1121
        # 'other_tree.inventory.root' is not present in this tree. We are
1110
1122
        # calling adjust_path for children which *want* to be present with a
1111
1123
        # correct place to go.
1112
 
        for thing, child in self.other_tree.inventory.root.children.iteritems():
 
1124
        for _, child in self.other_tree.inventory.root.children.iteritems():
1113
1125
            trans_id = self.tt.trans_id_file_id(child.file_id)
1114
1126
            if not other_root_is_present:
1115
1127
                if self.tt.final_kind(trans_id) is not None:
1117
1129
                    # to go already.
1118
1130
                    continue
1119
1131
            # Move the item into the root
1120
 
            self.tt.adjust_path(self.tt.final_name(trans_id),
1121
 
                                self.tt.root, trans_id)
 
1132
            try:
 
1133
                final_name = self.tt.final_name(trans_id)
 
1134
            except errors.NoFinalPath:
 
1135
                # This file is not present anymore, ignore it.
 
1136
                continue
 
1137
            self.tt.adjust_path(final_name, self.tt.root, trans_id)
1122
1138
        if other_root_is_present:
1123
1139
            self.tt.cancel_creation(other_root)
1124
1140
            self.tt.cancel_versioning(other_root)
1152
1168
    @staticmethod
1153
1169
    def contents_sha1(tree, file_id):
1154
1170
        """Determine the sha1 of the file contents (used as a key method)."""
1155
 
        if file_id not in tree:
 
1171
        if not tree.has_id(file_id):
1156
1172
            return None
1157
1173
        return tree.get_file_sha1(file_id)
1158
1174
 
1303
1319
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1304
1320
                                        this_parent, this_name,
1305
1321
                                        other_parent, other_name))
1306
 
        if other_name is None:
 
1322
        if not self.other_tree.has_id(file_id):
1307
1323
            # it doesn't matter whether the result was 'other' or
1308
 
            # 'conflict'-- if there's no 'other', we leave it alone.
 
1324
            # 'conflict'-- if it has no file id, we leave it alone.
1309
1325
            return
1310
1326
        parent_id = parents[self.winner_idx[parent_id_winner]]
1311
 
        if parent_id is not None:
 
1327
        name = names[self.winner_idx[name_winner]]
 
1328
        if parent_id is not None or name is not None:
1312
1329
            # if we get here, name_winner and parent_winner are set to safe
1313
1330
            # values.
1314
 
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1315
 
                                self.tt.trans_id_file_id(parent_id),
 
1331
            if parent_id is None and name is not None:
 
1332
                # if parent_id is None and name is non-None, current file is
 
1333
                # the tree root.
 
1334
                if names[self.winner_idx[parent_id_winner]] != '':
 
1335
                    raise AssertionError(
 
1336
                        'File looks like a root, but named %s' %
 
1337
                        names[self.winner_idx[parent_id_winner]])
 
1338
                parent_trans_id = transform.ROOT_PARENT
 
1339
            else:
 
1340
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1341
            self.tt.adjust_path(name, parent_trans_id,
1316
1342
                                self.tt.trans_id_file_id(file_id))
1317
1343
 
1318
1344
    def _do_merge_contents(self, file_id):
1319
1345
        """Performs a merge on file_id contents."""
1320
1346
        def contents_pair(tree):
1321
 
            if file_id not in tree:
 
1347
            if not tree.has_id(file_id):
1322
1348
                return (None, None)
1323
1349
            kind = tree.kind(file_id)
1324
1350
            if kind == "file":
1592
1618
 
1593
1619
    def cook_conflicts(self, fs_conflicts):
1594
1620
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1595
 
        self.cooked_conflicts.extend(transform.cook_conflicts(
1596
 
                fs_conflicts, self.tt))
 
1621
        content_conflict_file_ids = set()
 
1622
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
1597
1623
        fp = transform.FinalPaths(self.tt)
1598
1624
        for conflict in self._raw_conflicts:
1599
1625
            conflict_type = conflict[0]
1610
1636
                if other_parent is None or other_name is None:
1611
1637
                    other_path = '<deleted>'
1612
1638
                else:
1613
 
                    parent_path =  fp.get_path(
1614
 
                        self.tt.trans_id_file_id(other_parent))
 
1639
                    if other_parent == self.other_tree.get_root_id():
 
1640
                        # The tree transform doesn't know about the other root,
 
1641
                        # so we special case here to avoid a NoFinalPath
 
1642
                        # exception
 
1643
                        parent_path = ''
 
1644
                    else:
 
1645
                        parent_path =  fp.get_path(
 
1646
                            self.tt.trans_id_file_id(other_parent))
1615
1647
                    other_path = osutils.pathjoin(parent_path, other_name)
1616
1648
                c = _mod_conflicts.Conflict.factory(
1617
1649
                    'path conflict', path=this_path,
1629
1661
                        break
1630
1662
                c = _mod_conflicts.Conflict.factory(conflict_type,
1631
1663
                                                    path=path, file_id=file_id)
 
1664
                content_conflict_file_ids.add(file_id)
1632
1665
            elif conflict_type == 'text conflict':
1633
1666
                trans_id = conflict[1]
1634
1667
                path = fp.get_path(trans_id)
1637
1670
                                                    path=path, file_id=file_id)
1638
1671
            else:
1639
1672
                raise AssertionError('bad conflict type: %r' % (conflict,))
 
1673
            cooked_conflicts.append(c)
 
1674
 
 
1675
        self.cooked_conflicts = []
 
1676
        # We want to get rid of path conflicts when a corresponding contents
 
1677
        # conflict exists. This can occur when one branch deletes a file while
 
1678
        # the other renames *and* modifies it. In this case, the content
 
1679
        # conflict is enough.
 
1680
        for c in cooked_conflicts:
 
1681
            if (c.typestring == 'path conflict'
 
1682
                and c.file_id in content_conflict_file_ids):
 
1683
                continue
1640
1684
            self.cooked_conflicts.append(c)
1641
1685
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1642
1686
 
1887
1931
        name_in_target = osutils.basename(self._target_subdir)
1888
1932
        merge_into_root = subdir.copy()
1889
1933
        merge_into_root.name = name_in_target
1890
 
        if merge_into_root.file_id in self.this_tree.inventory:
 
1934
        if self.this_tree.inventory.has_id(merge_into_root.file_id):
1891
1935
            # Give the root a new file-id.
1892
1936
            # This can happen fairly easily if the directory we are
1893
1937
            # incorporating is the root, and both trees have 'TREE_ROOT' as
1930
1974
    """
1931
1975
    if this_tree is None:
1932
1976
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1933
 
                              "parameter as of bzrlib version 0.8.")
 
1977
                              "parameter")
1934
1978
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1935
1979
                    pb=pb, change_reporter=change_reporter)
1936
1980
    merger.backup_files = backup_files
2390
2434
class _PlanLCAMerge(_PlanMergeBase):
2391
2435
    """
2392
2436
    This merge algorithm differs from _PlanMerge in that:
 
2437
 
2393
2438
    1. comparisons are done against LCAs only
2394
2439
    2. cases where a contested line is new versus one LCA but old versus
2395
2440
       another are marked as conflicts, by emitting the line as conflicted-a
2436
2481
 
2437
2482
        If a line is killed and new, this indicates that the two merge
2438
2483
        revisions contain differing conflict resolutions.
 
2484
 
2439
2485
        :param revision_id: The id of the revision in which the lines are
2440
2486
            unique
2441
2487
        :param unique_line_numbers: The line numbers of unique lines.
2442
 
        :return a tuple of (new_this, killed_other):
 
2488
        :return: a tuple of (new_this, killed_other)
2443
2489
        """
2444
2490
        new = set()
2445
2491
        killed = set()