~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-05-11 15:04:23 UTC
  • mfrom: (5848.1.1 2.4-cython-first)
  • Revision ID: pqm@pqm.ubuntu.com-20110511150423-tpm1ablukqalkvim
(jameinel) Default to using Cython for compiling code,
 rather than Pyrex. (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
17
import warnings
20
18
 
21
19
from bzrlib.lazy_import import lazy_import
40
38
    versionedfile,
41
39
    workingtree,
42
40
    )
43
 
from bzrlib.i18n import gettext
44
41
""")
45
42
from bzrlib import (
46
43
    decorators,
47
44
    errors,
48
45
    hooks,
49
 
    registry,
50
46
    )
51
47
from bzrlib.symbol_versioning import (
52
48
    deprecated_in,
78
74
            "See the AbstractPerFileMerger API docs for details on how it is "
79
75
            "used by merge.",
80
76
            (2, 1))
81
 
        self.add_hook('pre_merge',
82
 
            'Called before a merge. '
83
 
            'Receives a Merger object as the single argument.',
84
 
            (2, 5))
85
 
        self.add_hook('post_merge',
86
 
            'Called after a merge. '
87
 
            'Receives a Merger object as the single argument. '
88
 
            'The return value is ignored.',
89
 
            (2, 5))
90
77
 
91
78
 
92
79
class AbstractPerFileMerger(object):
104
91
    def merge_contents(self, merge_params):
105
92
        """Attempt to merge the contents of a single file.
106
93
        
107
 
        :param merge_params: A bzrlib.merge.MergeFileHookParams
108
 
        :return: A tuple of (status, chunks), where status is one of
 
94
        :param merge_params: A bzrlib.merge.MergeHookParams
 
95
        :return : A tuple of (status, chunks), where status is one of
109
96
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
110
97
            is 'success' or 'conflicted', then chunks should be an iterable of
111
98
            strings for the new file contents.
131
118
 
132
119
    def get_filename(self, params, tree):
133
120
        """Lookup the filename (i.e. basename, not path), given a Tree (e.g.
134
 
        self.merger.this_tree) and a MergeFileHookParams.
 
121
        self.merger.this_tree) and a MergeHookParams.
135
122
        """
136
123
        return osutils.basename(tree.id2path(params.file_id))
137
124
 
138
125
    def get_filepath(self, params, tree):
139
126
        """Calculate the path to the file in a tree.
140
127
 
141
 
        :param params: A MergeFileHookParams describing the file to merge
 
128
        :param params: A MergeHookParams describing the file to merge
142
129
        :param tree: a Tree, e.g. self.merger.this_tree.
143
130
        """
144
131
        return tree.id2path(params.file_id)
151
138
            params.winner == 'other' or
152
139
            # THIS and OTHER aren't both files.
153
140
            not params.is_file_merge() or
154
 
            # The filename doesn't match
 
141
            # The filename doesn't match *.xml
155
142
            not self.file_matches(params)):
156
143
            return 'not_applicable', None
157
144
        return self.merge_matching(params)
233
220
        raise NotImplementedError(self.merge_text)
234
221
 
235
222
 
236
 
class MergeFileHookParams(object):
 
223
class MergeHookParams(object):
237
224
    """Object holding parameters passed to merge_file_content hooks.
238
225
 
239
226
    There are some fields hooks can access:
454
441
        revision_id = _mod_revision.ensure_null(revision_id)
455
442
        return branch, self.revision_tree(revision_id, branch)
456
443
 
 
444
    @deprecated_method(deprecated_in((2, 1, 0)))
 
445
    def ensure_revision_trees(self):
 
446
        if self.this_revision_tree is None:
 
447
            self.this_basis_tree = self.revision_tree(self.this_basis)
 
448
            if self.this_basis == self.this_rev_id:
 
449
                self.this_revision_tree = self.this_basis_tree
 
450
 
 
451
        if self.other_rev_id is None:
 
452
            other_basis_tree = self.revision_tree(self.other_basis)
 
453
            if other_basis_tree.has_changes(self.other_tree):
 
454
                raise errors.WorkingTreeNotRevision(self.this_tree)
 
455
            other_rev_id = self.other_basis
 
456
            self.other_tree = other_basis_tree
 
457
 
 
458
    @deprecated_method(deprecated_in((2, 1, 0)))
 
459
    def file_revisions(self, file_id):
 
460
        self.ensure_revision_trees()
 
461
        if self.this_rev_id is None:
 
462
            if self.this_basis_tree.get_file_sha1(file_id) != \
 
463
                self.this_tree.get_file_sha1(file_id):
 
464
                raise errors.WorkingTreeNotRevision(self.this_tree)
 
465
 
 
466
        trees = (self.this_basis_tree, self.other_tree)
 
467
        return [tree.get_file_revision(file_id) for tree in trees]
 
468
 
 
469
    @deprecated_method(deprecated_in((2, 1, 0)))
 
470
    def check_basis(self, check_clean, require_commits=True):
 
471
        if self.this_basis is None and require_commits is True:
 
472
            raise errors.BzrCommandError(
 
473
                "This branch has no commits."
 
474
                " (perhaps you would prefer 'bzr pull')")
 
475
        if check_clean:
 
476
            self.compare_basis()
 
477
            if self.this_basis != self.this_rev_id:
 
478
                raise errors.UncommittedChanges(self.this_tree)
 
479
 
 
480
    @deprecated_method(deprecated_in((2, 1, 0)))
 
481
    def compare_basis(self):
 
482
        try:
 
483
            basis_tree = self.revision_tree(self.this_tree.last_revision())
 
484
        except errors.NoSuchRevision:
 
485
            basis_tree = self.this_tree.basis_tree()
 
486
        if not self.this_tree.has_changes(basis_tree):
 
487
            self.this_rev_id = self.this_basis
 
488
 
457
489
    def set_interesting_files(self, file_list):
458
490
        self.interesting_files = file_list
459
491
 
504
536
                raise errors.NoCommits(self.other_branch)
505
537
        if self.other_rev_id is not None:
506
538
            self._cached_trees[self.other_rev_id] = self.other_tree
507
 
        self._maybe_fetch(self.other_branch, self.this_branch, self.other_basis)
 
539
        self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
508
540
 
509
541
    def set_other_revision(self, revision_id, other_branch):
510
542
        """Set 'other' based on a branch and revision id
559
591
                else:
560
592
                    self.base_rev_id = self.revision_graph.find_unique_lca(
561
593
                                            *lcas)
562
 
                sorted_lca_keys = self.revision_graph.find_merge_order(
 
594
                sorted_lca_keys = self.revision_graph.find_merge_order(                
563
595
                    revisions[0], lcas)
564
596
                if self.base_rev_id == _mod_revision.NULL_REVISION:
565
597
                    self.base_rev_id = sorted_lca_keys[0]
566
 
 
 
598
                
567
599
            if self.base_rev_id == _mod_revision.NULL_REVISION:
568
600
                raise errors.UnrelatedBranches()
569
601
            if self._is_criss_cross:
572
604
                trace.mutter('Criss-cross lcas: %r' % lcas)
573
605
                if self.base_rev_id in lcas:
574
606
                    trace.mutter('Unable to find unique lca. '
575
 
                                 'Fallback %r as best option.'
576
 
                                 % self.base_rev_id)
 
607
                                 'Fallback %r as best option.' % self.base_rev_id)
577
608
                interesting_revision_ids = set(lcas)
578
609
                interesting_revision_ids.add(self.base_rev_id)
579
610
                interesting_trees = dict((t.get_revision_id(), t)
612
643
            self._maybe_fetch(base_branch, self.this_branch, self.base_rev_id)
613
644
 
614
645
    def make_merger(self):
615
 
        kwargs = {'working_tree': self.this_tree, 'this_tree': self.this_tree,
 
646
        kwargs = {'working_tree':self.this_tree, 'this_tree': self.this_tree,
616
647
                  'other_tree': self.other_tree,
617
648
                  'interesting_ids': self.interesting_ids,
618
649
                  'interesting_files': self.interesting_files,
619
650
                  'this_branch': self.this_branch,
620
 
                  'other_branch': self.other_branch,
621
651
                  'do_merge': False}
622
652
        if self.merge_type.requires_base:
623
653
            kwargs['base_tree'] = self.base_tree
649
679
        merge = self.make_merger()
650
680
        if self.other_branch is not None:
651
681
            self.other_branch.update_references(self.this_branch)
652
 
        for hook in Merger.hooks['pre_merge']:
653
 
            hook(merge)
654
682
        merge.do_merge()
655
 
        for hook in Merger.hooks['post_merge']:
656
 
            hook(merge)
657
683
        if self.recurse == 'down':
658
684
            for relpath, file_id in self.this_tree.iter_references():
659
685
                sub_tree = self.this_tree.get_nested_tree(file_id, relpath)
663
689
                    continue
664
690
                sub_merge = Merger(sub_tree.branch, this_tree=sub_tree)
665
691
                sub_merge.merge_type = self.merge_type
666
 
                other_branch = self.other_branch.reference_parent(file_id,
667
 
                                                                  relpath)
 
692
                other_branch = self.other_branch.reference_parent(file_id, relpath)
668
693
                sub_merge.set_other_revision(other_revision, other_branch)
669
694
                base_revision = self.base_tree.get_reference_revision(file_id)
670
695
                sub_merge.base_tree = \
686
711
        merge = operation.run_simple()
687
712
        if len(merge.cooked_conflicts) == 0:
688
713
            if not self.ignore_zero and not trace.is_quiet():
689
 
                trace.note(gettext("All changes applied successfully."))
 
714
                trace.note("All changes applied successfully.")
690
715
        else:
691
 
            trace.note(gettext("%d conflicts encountered.")
 
716
            trace.note("%d conflicts encountered."
692
717
                       % len(merge.cooked_conflicts))
693
718
 
694
719
        return len(merge.cooked_conflicts)
726
751
                 interesting_ids=None, reprocess=False, show_base=False,
727
752
                 pb=None, pp=None, change_reporter=None,
728
753
                 interesting_files=None, do_merge=True,
729
 
                 cherrypick=False, lca_trees=None, this_branch=None,
730
 
                 other_branch=None):
 
754
                 cherrypick=False, lca_trees=None, this_branch=None):
731
755
        """Initialize the merger object and perform the merge.
732
756
 
733
757
        :param working_tree: The working tree to apply the merge to
736
760
        :param other_tree: The other tree to merge changes from
737
761
        :param this_branch: The branch associated with this_tree.  Defaults to
738
762
            this_tree.branch if not supplied.
739
 
        :param other_branch: The branch associated with other_tree, if any.
740
763
        :param interesting_ids: The file_ids of files that should be
741
764
            participate in the merge.  May not be combined with
742
765
            interesting_files.
764
787
            this_branch = this_tree.branch
765
788
        self.interesting_ids = interesting_ids
766
789
        self.interesting_files = interesting_files
767
 
        self.working_tree = working_tree
768
 
        self.this_tree = this_tree
 
790
        self.this_tree = working_tree
769
791
        self.base_tree = base_tree
770
792
        self.other_tree = other_tree
771
793
        self.this_branch = this_branch
772
 
        self.other_branch = other_branch
773
794
        self._raw_conflicts = []
774
795
        self.cooked_conflicts = []
775
796
        self.reprocess = reprocess
791
812
 
792
813
    def do_merge(self):
793
814
        operation = cleanup.OperationWithCleanups(self._do_merge)
794
 
        self.working_tree.lock_tree_write()
795
 
        operation.add_cleanup(self.working_tree.unlock)
796
 
        self.this_tree.lock_read()
 
815
        self.this_tree.lock_tree_write()
797
816
        operation.add_cleanup(self.this_tree.unlock)
798
817
        self.base_tree.lock_read()
799
818
        operation.add_cleanup(self.base_tree.unlock)
802
821
        operation.run()
803
822
 
804
823
    def _do_merge(self, operation):
805
 
        self.tt = transform.TreeTransform(self.working_tree, None)
 
824
        self.tt = transform.TreeTransform(self.this_tree, None)
806
825
        operation.add_cleanup(self.tt.finalize)
807
826
        self._compute_transform()
808
827
        results = self.tt.apply(no_conflicts=True)
809
828
        self.write_modified(results)
810
829
        try:
811
 
            self.working_tree.add_conflicts(self.cooked_conflicts)
 
830
            self.this_tree.add_conflicts(self.cooked_conflicts)
812
831
        except errors.UnsupportedOperation:
813
832
            pass
814
833
 
821
840
        return operation.run_simple()
822
841
 
823
842
    def _make_preview_transform(self):
824
 
        self.tt = transform.TransformPreview(self.working_tree)
 
843
        self.tt = transform.TransformPreview(self.this_tree)
825
844
        self._compute_transform()
826
845
        return self.tt
827
846
 
832
851
        else:
833
852
            entries = self._entries_lca()
834
853
            resolver = self._lca_multi_way
835
 
        # Prepare merge hooks
836
 
        factories = Merger.hooks['merge_file_content']
837
 
        # One hook for each registered one plus our default merger
838
 
        hooks = [factory(self) for factory in factories] + [self]
839
 
        self.active_hooks = [hook for hook in hooks if hook is not None]
840
854
        child_pb = ui.ui_factory.nested_progress_bar()
841
855
        try:
 
856
            factories = Merger.hooks['merge_file_content']
 
857
            hooks = [factory(self) for factory in factories] + [self]
 
858
            self.active_hooks = [hook for hook in hooks if hook is not None]
842
859
            for num, (file_id, changed, parents3, names3,
843
860
                      executable3) in enumerate(entries):
844
 
                # Try merging each entry
845
 
                child_pb.update(gettext('Preparing file merge'),
846
 
                                num, len(entries))
 
861
                child_pb.update('Preparing file merge', num, len(entries))
847
862
                self._merge_names(file_id, parents3, names3, resolver=resolver)
848
863
                if changed:
849
864
                    file_status = self._do_merge_contents(file_id)
853
868
                    executable3, file_status, resolver=resolver)
854
869
        finally:
855
870
            child_pb.finished()
856
 
        self.tt.fixup_new_roots()
 
871
        self.fix_root()
857
872
        self._finish_computing_transform()
858
873
 
859
874
    def _finish_computing_transform(self):
873
888
                self.tt.iter_changes(), self.change_reporter)
874
889
        self.cook_conflicts(fs_conflicts)
875
890
        for conflict in self.cooked_conflicts:
876
 
            trace.warning(unicode(conflict))
 
891
            trace.warning(conflict)
877
892
 
878
893
    def _entries3(self):
879
894
        """Gather data about files modified between three trees.
918
933
        it then compares with THIS and BASE.
919
934
 
920
935
        For the multi-valued entries, the format will be (BASE, [lca1, lca2])
921
 
 
922
 
        :return: [(file_id, changed, parents, names, executable)], where:
923
 
 
924
 
            * file_id: Simple file_id of the entry
925
 
            * changed: Boolean, True if the kind or contents changed else False
926
 
            * parents: ((base, [parent_id, in, lcas]), parent_id_other,
927
 
                        parent_id_this)
928
 
            * names:   ((base, [name, in, lcas]), name_in_other, name_in_this)
929
 
            * executable: ((base, [exec, in, lcas]), exec_in_other,
930
 
                        exec_in_this)
 
936
        :return: [(file_id, changed, parents, names, executable)]
 
937
            file_id     Simple file_id of the entry
 
938
            changed     Boolean, True if the kind or contents changed
 
939
                        else False
 
940
            parents     ((base, [parent_id, in, lcas]), parent_id_other,
 
941
                         parent_id_this)
 
942
            names       ((base, [name, in, lcas]), name_in_other, name_in_this)
 
943
            executable  ((base, [exec, in, lcas]), exec_in_other, exec_in_this)
931
944
        """
932
945
        if self.interesting_files is not None:
933
946
            lookup_trees = [self.this_tree, self.base_tree]
940
953
        result = []
941
954
        walker = _mod_tree.MultiWalker(self.other_tree, self._lca_trees)
942
955
 
943
 
        base_inventory = self.base_tree.root_inventory
944
 
        this_inventory = self.this_tree.root_inventory
 
956
        base_inventory = self.base_tree.inventory
 
957
        this_inventory = self.this_tree.inventory
945
958
        for path, file_id, other_ie, lca_values in walker.iter_all():
946
959
            # Is this modified at all from any of the other trees?
947
960
            if other_ie is None:
975
988
                else:
976
989
                    lca_entries.append(lca_ie)
977
990
 
978
 
            if base_inventory.has_id(file_id):
 
991
            if file_id in base_inventory:
979
992
                base_ie = base_inventory[file_id]
980
993
            else:
981
994
                base_ie = _none_entry
982
995
 
983
 
            if this_inventory.has_id(file_id):
 
996
            if file_id in this_inventory:
984
997
                this_ie = this_inventory[file_id]
985
998
            else:
986
999
                this_ie = _none_entry
1078
1091
                          ))
1079
1092
        return result
1080
1093
 
 
1094
    def fix_root(self):
 
1095
        if self.tt.final_kind(self.tt.root) is None:
 
1096
            self.tt.cancel_deletion(self.tt.root)
 
1097
        if self.tt.final_file_id(self.tt.root) is None:
 
1098
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
 
1099
                                 self.tt.root)
 
1100
        other_root_file_id = self.other_tree.get_root_id()
 
1101
        if other_root_file_id is None:
 
1102
            return
 
1103
        other_root = self.tt.trans_id_file_id(other_root_file_id)
 
1104
        if other_root == self.tt.root:
 
1105
            return
 
1106
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
 
1107
            # the other tree's root is a non-root in the current tree (as when
 
1108
            # a previously unrelated branch is merged into another)
 
1109
            return
 
1110
        if self.tt.final_kind(other_root) is not None:
 
1111
            other_root_is_present = True
 
1112
        else:
 
1113
            # other_root doesn't have a physical representation. We still need
 
1114
            # to move any references to the actual root of the tree.
 
1115
            other_root_is_present = False
 
1116
        # 'other_tree.inventory.root' is not present in this tree. We are
 
1117
        # calling adjust_path for children which *want* to be present with a
 
1118
        # correct place to go.
 
1119
        for _, child in self.other_tree.inventory.root.children.iteritems():
 
1120
            trans_id = self.tt.trans_id_file_id(child.file_id)
 
1121
            if not other_root_is_present:
 
1122
                if self.tt.final_kind(trans_id) is not None:
 
1123
                    # The item exist in the final tree and has a defined place
 
1124
                    # to go already.
 
1125
                    continue
 
1126
            # Move the item into the root
 
1127
            try:
 
1128
                final_name = self.tt.final_name(trans_id)
 
1129
            except errors.NoFinalPath:
 
1130
                # This file is not present anymore, ignore it.
 
1131
                continue
 
1132
            self.tt.adjust_path(final_name, self.tt.root, trans_id)
 
1133
        if other_root_is_present:
 
1134
            self.tt.cancel_creation(other_root)
 
1135
            self.tt.cancel_versioning(other_root)
 
1136
 
1081
1137
    def write_modified(self, results):
1082
1138
        modified_hashes = {}
1083
1139
        for path in results.modified_paths:
1084
 
            file_id = self.working_tree.path2id(self.working_tree.relpath(path))
 
1140
            file_id = self.this_tree.path2id(self.this_tree.relpath(path))
1085
1141
            if file_id is None:
1086
1142
                continue
1087
 
            hash = self.working_tree.get_file_sha1(file_id)
 
1143
            hash = self.this_tree.get_file_sha1(file_id)
1088
1144
            if hash is None:
1089
1145
                continue
1090
1146
            modified_hashes[file_id] = hash
1091
 
        self.working_tree.set_merge_modified(modified_hashes)
 
1147
        self.this_tree.set_merge_modified(modified_hashes)
1092
1148
 
1093
1149
    @staticmethod
1094
1150
    def parent(entry, file_id):
1107
1163
    @staticmethod
1108
1164
    def contents_sha1(tree, file_id):
1109
1165
        """Determine the sha1 of the file contents (used as a key method)."""
1110
 
        if not tree.has_id(file_id):
 
1166
        if file_id not in tree:
1111
1167
            return None
1112
1168
        return tree.get_file_sha1(file_id)
1113
1169
 
1193
1249
        # At this point, the lcas disagree, and the tip disagree
1194
1250
        return 'conflict'
1195
1251
 
 
1252
    @staticmethod
 
1253
    @deprecated_method(deprecated_in((2, 2, 0)))
 
1254
    def scalar_three_way(this_tree, base_tree, other_tree, file_id, key):
 
1255
        """Do a three-way test on a scalar.
 
1256
        Return "this", "other" or "conflict", depending whether a value wins.
 
1257
        """
 
1258
        key_base = key(base_tree, file_id)
 
1259
        key_other = key(other_tree, file_id)
 
1260
        #if base == other, either they all agree, or only THIS has changed.
 
1261
        if key_base == key_other:
 
1262
            return "this"
 
1263
        key_this = key(this_tree, file_id)
 
1264
        # "Ambiguous clean merge"
 
1265
        if key_this == key_other:
 
1266
            return "this"
 
1267
        elif key_this == key_base:
 
1268
            return "other"
 
1269
        else:
 
1270
            return "conflict"
 
1271
 
1196
1272
    def merge_names(self, file_id):
1197
1273
        def get_entry(tree):
1198
 
            try:
1199
 
                return tree.root_inventory[file_id]
1200
 
            except errors.NoSuchId:
 
1274
            if tree.has_id(file_id):
 
1275
                return tree.inventory[file_id]
 
1276
            else:
1201
1277
                return None
1202
1278
        this_entry = get_entry(self.this_tree)
1203
1279
        other_entry = get_entry(self.other_tree)
1238
1314
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1239
1315
                                        this_parent, this_name,
1240
1316
                                        other_parent, other_name))
1241
 
        if not self.other_tree.has_id(file_id):
 
1317
        if other_name is None:
1242
1318
            # it doesn't matter whether the result was 'other' or
1243
 
            # 'conflict'-- if it has no file id, we leave it alone.
 
1319
            # 'conflict'-- if there's no 'other', we leave it alone.
1244
1320
            return
1245
1321
        parent_id = parents[self.winner_idx[parent_id_winner]]
1246
 
        name = names[self.winner_idx[name_winner]]
1247
 
        if parent_id is not None or name is not None:
 
1322
        if parent_id is not None:
1248
1323
            # if we get here, name_winner and parent_winner are set to safe
1249
1324
            # values.
1250
 
            if parent_id is None and name is not None:
1251
 
                # if parent_id is None and name is non-None, current file is
1252
 
                # the tree root.
1253
 
                if names[self.winner_idx[parent_id_winner]] != '':
1254
 
                    raise AssertionError(
1255
 
                        'File looks like a root, but named %s' %
1256
 
                        names[self.winner_idx[parent_id_winner]])
1257
 
                parent_trans_id = transform.ROOT_PARENT
1258
 
            else:
1259
 
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
1260
 
            self.tt.adjust_path(name, parent_trans_id,
 
1325
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
 
1326
                                self.tt.trans_id_file_id(parent_id),
1261
1327
                                self.tt.trans_id_file_id(file_id))
1262
1328
 
1263
1329
    def _do_merge_contents(self, file_id):
1264
1330
        """Performs a merge on file_id contents."""
1265
1331
        def contents_pair(tree):
1266
 
            if not tree.has_id(file_id):
 
1332
            if file_id not in tree:
1267
1333
                return (None, None)
1268
1334
            kind = tree.kind(file_id)
1269
1335
            if kind == "file":
1298
1364
        # We have a hypothetical conflict, but if we have files, then we
1299
1365
        # can try to merge the content
1300
1366
        trans_id = self.tt.trans_id_file_id(file_id)
1301
 
        params = MergeFileHookParams(self, file_id, trans_id, this_pair[0],
 
1367
        params = MergeHookParams(self, file_id, trans_id, this_pair[0],
1302
1368
            other_pair[0], winner)
1303
1369
        hooks = self.active_hooks
1304
1370
        hook_status = 'not_applicable'
1307
1373
            if hook_status != 'not_applicable':
1308
1374
                # Don't try any more hooks, this one applies.
1309
1375
                break
1310
 
        # If the merge ends up replacing the content of the file, we get rid of
1311
 
        # it at the end of this method (this variable is used to track the
1312
 
        # exceptions to this rule).
1313
 
        keep_this = False
1314
1376
        result = "modified"
1315
1377
        if hook_status == 'not_applicable':
1316
 
            # No merge hook was able to resolve the situation. Two cases exist:
1317
 
            # a content conflict or a duplicate one.
 
1378
            # This is a contents conflict, because none of the available
 
1379
            # functions could merge it.
1318
1380
            result = None
1319
1381
            name = self.tt.final_name(trans_id)
1320
1382
            parent_id = self.tt.final_parent(trans_id)
1321
 
            duplicate = False
1322
 
            inhibit_content_conflict = False
1323
 
            if params.this_kind is None: # file_id is not in THIS
1324
 
                # Is the name used for a different file_id ?
1325
 
                dupe_path = self.other_tree.id2path(file_id)
1326
 
                this_id = self.this_tree.path2id(dupe_path)
1327
 
                if this_id is not None:
1328
 
                    # Two entries for the same path
1329
 
                    keep_this = True
1330
 
                    # versioning the merged file will trigger a duplicate
1331
 
                    # conflict
1332
 
                    self.tt.version_file(file_id, trans_id)
1333
 
                    transform.create_from_tree(
1334
 
                        self.tt, trans_id, self.other_tree, file_id,
1335
 
                        filter_tree_path=self._get_filter_tree_path(file_id))
1336
 
                    inhibit_content_conflict = True
1337
 
            elif params.other_kind is None: # file_id is not in OTHER
1338
 
                # Is the name used for a different file_id ?
1339
 
                dupe_path = self.this_tree.id2path(file_id)
1340
 
                other_id = self.other_tree.path2id(dupe_path)
1341
 
                if other_id is not None:
1342
 
                    # Two entries for the same path again, but here, the other
1343
 
                    # entry will also be merged.  We simply inhibit the
1344
 
                    # 'content' conflict creation because we know OTHER will
1345
 
                    # create (or has already created depending on ordering) an
1346
 
                    # entry at the same path. This will trigger a 'duplicate'
1347
 
                    # conflict later.
1348
 
                    keep_this = True
1349
 
                    inhibit_content_conflict = True
1350
 
            if not inhibit_content_conflict:
1351
 
                if params.this_kind is not None:
1352
 
                    self.tt.unversion_file(trans_id)
1353
 
                # This is a contents conflict, because none of the available
1354
 
                # functions could merge it.
1355
 
                file_group = self._dump_conflicts(name, parent_id, file_id,
1356
 
                                                  set_version=True)
1357
 
                self._raw_conflicts.append(('contents conflict', file_group))
 
1383
            if self.this_tree.has_id(file_id):
 
1384
                self.tt.unversion_file(trans_id)
 
1385
            file_group = self._dump_conflicts(name, parent_id, file_id,
 
1386
                                              set_version=True)
 
1387
            self._raw_conflicts.append(('contents conflict', file_group))
1358
1388
        elif hook_status == 'success':
1359
1389
            self.tt.create_file(lines, trans_id)
1360
1390
        elif hook_status == 'conflicted':
1376
1406
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
1377
1407
        if not self.this_tree.has_id(file_id) and result == "modified":
1378
1408
            self.tt.version_file(file_id, trans_id)
1379
 
        if not keep_this:
1380
 
            # The merge has been performed and produced a new content, so the
1381
 
            # old contents should not be retained.
1382
 
            self.tt.delete_contents(trans_id)
 
1409
        # The merge has been performed, so the old contents should not be
 
1410
        # retained.
 
1411
        self.tt.delete_contents(trans_id)
1383
1412
        return result
1384
1413
 
1385
1414
    def _default_other_winner_merge(self, merge_hook_params):
1386
1415
        """Replace this contents with other."""
1387
1416
        file_id = merge_hook_params.file_id
1388
1417
        trans_id = merge_hook_params.trans_id
 
1418
        file_in_this = self.this_tree.has_id(file_id)
1389
1419
        if self.other_tree.has_id(file_id):
1390
1420
            # OTHER changed the file
1391
 
            transform.create_from_tree(
1392
 
                self.tt, trans_id, self.other_tree, file_id,
1393
 
                filter_tree_path=self._get_filter_tree_path(file_id))
 
1421
            wt = self.this_tree
 
1422
            if wt.supports_content_filtering():
 
1423
                # We get the path from the working tree if it exists.
 
1424
                # That fails though when OTHER is adding a file, so
 
1425
                # we fall back to the other tree to find the path if
 
1426
                # it doesn't exist locally.
 
1427
                try:
 
1428
                    filter_tree_path = wt.id2path(file_id)
 
1429
                except errors.NoSuchId:
 
1430
                    filter_tree_path = self.other_tree.id2path(file_id)
 
1431
            else:
 
1432
                # Skip the id2path lookup for older formats
 
1433
                filter_tree_path = None
 
1434
            transform.create_from_tree(self.tt, trans_id,
 
1435
                             self.other_tree, file_id,
 
1436
                             filter_tree_path=filter_tree_path)
1394
1437
            return 'done', None
1395
 
        elif self.this_tree.has_id(file_id):
 
1438
        elif file_in_this:
1396
1439
            # OTHER deleted the file
1397
1440
            return 'delete', None
1398
1441
        else:
1472
1515
                                              other_lines)
1473
1516
            file_group.append(trans_id)
1474
1517
 
1475
 
 
1476
 
    def _get_filter_tree_path(self, file_id):
1477
 
        if self.this_tree.supports_content_filtering():
1478
 
            # We get the path from the working tree if it exists.
1479
 
            # That fails though when OTHER is adding a file, so
1480
 
            # we fall back to the other tree to find the path if
1481
 
            # it doesn't exist locally.
1482
 
            try:
1483
 
                return self.this_tree.id2path(file_id)
1484
 
            except errors.NoSuchId:
1485
 
                return self.other_tree.id2path(file_id)
1486
 
        # Skip the id2path lookup for older formats
1487
 
        return None
1488
 
 
1489
1518
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1490
1519
                        base_lines=None, other_lines=None, set_version=False,
1491
1520
                        no_base=False):
1574
1603
 
1575
1604
    def cook_conflicts(self, fs_conflicts):
1576
1605
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1577
 
        content_conflict_file_ids = set()
1578
 
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
 
1606
        self.cooked_conflicts.extend(transform.cook_conflicts(
 
1607
                fs_conflicts, self.tt))
1579
1608
        fp = transform.FinalPaths(self.tt)
1580
1609
        for conflict in self._raw_conflicts:
1581
1610
            conflict_type = conflict[0]
1592
1621
                if other_parent is None or other_name is None:
1593
1622
                    other_path = '<deleted>'
1594
1623
                else:
1595
 
                    if other_parent == self.other_tree.get_root_id():
1596
 
                        # The tree transform doesn't know about the other root,
1597
 
                        # so we special case here to avoid a NoFinalPath
1598
 
                        # exception
1599
 
                        parent_path = ''
1600
 
                    else:
1601
 
                        parent_path =  fp.get_path(
1602
 
                            self.tt.trans_id_file_id(other_parent))
 
1624
                    parent_path =  fp.get_path(
 
1625
                        self.tt.trans_id_file_id(other_parent))
1603
1626
                    other_path = osutils.pathjoin(parent_path, other_name)
1604
1627
                c = _mod_conflicts.Conflict.factory(
1605
1628
                    'path conflict', path=this_path,
1609
1632
                for trans_id in conflict[1]:
1610
1633
                    file_id = self.tt.final_file_id(trans_id)
1611
1634
                    if file_id is not None:
1612
 
                        # Ok we found the relevant file-id
1613
1635
                        break
1614
1636
                path = fp.get_path(trans_id)
1615
1637
                for suffix in ('.BASE', '.THIS', '.OTHER'):
1616
1638
                    if path.endswith(suffix):
1617
 
                        # Here is the raw path
1618
1639
                        path = path[:-len(suffix)]
1619
1640
                        break
1620
1641
                c = _mod_conflicts.Conflict.factory(conflict_type,
1621
1642
                                                    path=path, file_id=file_id)
1622
 
                content_conflict_file_ids.add(file_id)
1623
1643
            elif conflict_type == 'text conflict':
1624
1644
                trans_id = conflict[1]
1625
1645
                path = fp.get_path(trans_id)
1628
1648
                                                    path=path, file_id=file_id)
1629
1649
            else:
1630
1650
                raise AssertionError('bad conflict type: %r' % (conflict,))
1631
 
            cooked_conflicts.append(c)
1632
 
 
1633
 
        self.cooked_conflicts = []
1634
 
        # We want to get rid of path conflicts when a corresponding contents
1635
 
        # conflict exists. This can occur when one branch deletes a file while
1636
 
        # the other renames *and* modifies it. In this case, the content
1637
 
        # conflict is enough.
1638
 
        for c in cooked_conflicts:
1639
 
            if (c.typestring == 'path conflict'
1640
 
                and c.file_id in content_conflict_file_ids):
1641
 
                continue
1642
1651
            self.cooked_conflicts.append(c)
1643
1652
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1644
1653
 
1865
1874
            entries = self._entries_to_incorporate()
1866
1875
            entries = list(entries)
1867
1876
            for num, (entry, parent_id) in enumerate(entries):
1868
 
                child_pb.update(gettext('Preparing file merge'), num, len(entries))
 
1877
                child_pb.update('Preparing file merge', num, len(entries))
1869
1878
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
1870
1879
                trans_id = transform.new_by_entry(self.tt, entry,
1871
1880
                    parent_trans_id, self.other_tree)
1875
1884
 
1876
1885
    def _entries_to_incorporate(self):
1877
1886
        """Yields pairs of (inventory_entry, new_parent)."""
1878
 
        other_inv = self.other_tree.root_inventory
 
1887
        other_inv = self.other_tree.inventory
1879
1888
        subdir_id = other_inv.path2id(self._source_subpath)
1880
1889
        if subdir_id is None:
1881
1890
            # XXX: The error would be clearer if it gave the URL of the source
1883
1892
            raise PathNotInTree(self._source_subpath, "Source tree")
1884
1893
        subdir = other_inv[subdir_id]
1885
1894
        parent_in_target = osutils.dirname(self._target_subdir)
1886
 
        target_id = self.this_tree.path2id(parent_in_target)
 
1895
        target_id = self.this_tree.inventory.path2id(parent_in_target)
1887
1896
        if target_id is None:
1888
1897
            raise PathNotInTree(self._target_subdir, "Target tree")
1889
1898
        name_in_target = osutils.basename(self._target_subdir)
1890
1899
        merge_into_root = subdir.copy()
1891
1900
        merge_into_root.name = name_in_target
1892
 
        if self.this_tree.has_id(merge_into_root.file_id):
 
1901
        if merge_into_root.file_id in self.this_tree.inventory:
1893
1902
            # Give the root a new file-id.
1894
1903
            # This can happen fairly easily if the directory we are
1895
1904
            # incorporating is the root, and both trees have 'TREE_ROOT' as
1932
1941
    """
1933
1942
    if this_tree is None:
1934
1943
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1935
 
                              "parameter")
 
1944
                              "parameter as of bzrlib version 0.8.")
1936
1945
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1937
1946
                    pb=pb, change_reporter=change_reporter)
1938
1947
    merger.backup_files = backup_files
1955
1964
    merger.set_base_revision(get_revision_id(), this_branch)
1956
1965
    return merger.do_merge()
1957
1966
 
1958
 
 
1959
 
merge_type_registry = registry.Registry()
1960
 
merge_type_registry.register('diff3', Diff3Merger,
1961
 
                             "Merge using external diff3.")
1962
 
merge_type_registry.register('lca', LCAMerger,
1963
 
                             "LCA-newness merge.")
1964
 
merge_type_registry.register('merge3', Merge3Merger,
1965
 
                             "Native diff3-style merge.")
1966
 
merge_type_registry.register('weave', WeaveMerger,
1967
 
                             "Weave-based merge.")
1968
 
 
1969
 
 
1970
1967
def get_merge_type_registry():
1971
 
    """Merge type registry was previously in bzrlib.option
 
1968
    """Merge type registry is in bzrlib.option to avoid circular imports.
1972
1969
 
1973
 
    This method provides a backwards compatible way to retrieve it.
 
1970
    This method provides a sanctioned way to retrieve it.
1974
1971
    """
1975
 
    return merge_type_registry
 
1972
    from bzrlib import option
 
1973
    return option._merge_type_registry
1976
1974
 
1977
1975
 
1978
1976
def _plan_annotate_merge(annotated_a, annotated_b, ancestors_a, ancestors_b):
2403
2401
class _PlanLCAMerge(_PlanMergeBase):
2404
2402
    """
2405
2403
    This merge algorithm differs from _PlanMerge in that:
2406
 
 
2407
2404
    1. comparisons are done against LCAs only
2408
2405
    2. cases where a contested line is new versus one LCA but old versus
2409
2406
       another are marked as conflicts, by emitting the line as conflicted-a
2450
2447
 
2451
2448
        If a line is killed and new, this indicates that the two merge
2452
2449
        revisions contain differing conflict resolutions.
2453
 
 
2454
2450
        :param revision_id: The id of the revision in which the lines are
2455
2451
            unique
2456
2452
        :param unique_line_numbers: The line numbers of unique lines.
2457
 
        :return: a tuple of (new_this, killed_other)
 
2453
        :return a tuple of (new_this, killed_other):
2458
2454
        """
2459
2455
        new = set()
2460
2456
        killed = set()