~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

(gz) Remove bzrlib/util/elementtree/ package (Martin Packman)

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
 
17
19
import warnings
18
20
 
19
21
from bzrlib.lazy_import import lazy_import
38
40
    versionedfile,
39
41
    workingtree,
40
42
    )
 
43
from bzrlib.i18n import gettext
41
44
""")
42
45
from bzrlib import (
43
46
    decorators,
44
47
    errors,
45
48
    hooks,
 
49
    registry,
46
50
    )
47
51
from bzrlib.symbol_versioning import (
48
52
    deprecated_in,
74
78
            "See the AbstractPerFileMerger API docs for details on how it is "
75
79
            "used by merge.",
76
80
            (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))
77
90
 
78
91
 
79
92
class AbstractPerFileMerger(object):
91
104
    def merge_contents(self, merge_params):
92
105
        """Attempt to merge the contents of a single file.
93
106
        
94
 
        :param merge_params: A bzrlib.merge.MergeHookParams
 
107
        :param merge_params: A bzrlib.merge.MergeFileHookParams
95
108
        :return: A tuple of (status, chunks), where status is one of
96
109
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
97
110
            is 'success' or 'conflicted', then chunks should be an iterable of
118
131
 
119
132
    def get_filename(self, params, tree):
120
133
        """Lookup the filename (i.e. basename, not path), given a Tree (e.g.
121
 
        self.merger.this_tree) and a MergeHookParams.
 
134
        self.merger.this_tree) and a MergeFileHookParams.
122
135
        """
123
136
        return osutils.basename(tree.id2path(params.file_id))
124
137
 
125
138
    def get_filepath(self, params, tree):
126
139
        """Calculate the path to the file in a tree.
127
140
 
128
 
        :param params: A MergeHookParams describing the file to merge
 
141
        :param params: A MergeFileHookParams describing the file to merge
129
142
        :param tree: a Tree, e.g. self.merger.this_tree.
130
143
        """
131
144
        return tree.id2path(params.file_id)
138
151
            params.winner == 'other' or
139
152
            # THIS and OTHER aren't both files.
140
153
            not params.is_file_merge() or
141
 
            # The filename doesn't match *.xml
 
154
            # The filename doesn't match
142
155
            not self.file_matches(params)):
143
156
            return 'not_applicable', None
144
157
        return self.merge_matching(params)
220
233
        raise NotImplementedError(self.merge_text)
221
234
 
222
235
 
223
 
class MergeHookParams(object):
 
236
class MergeFileHookParams(object):
224
237
    """Object holding parameters passed to merge_file_content hooks.
225
238
 
226
239
    There are some fields hooks can access:
441
454
        revision_id = _mod_revision.ensure_null(revision_id)
442
455
        return branch, self.revision_tree(revision_id, branch)
443
456
 
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
 
 
489
457
    def set_interesting_files(self, file_list):
490
458
        self.interesting_files = file_list
491
459
 
536
504
                raise errors.NoCommits(self.other_branch)
537
505
        if self.other_rev_id is not None:
538
506
            self._cached_trees[self.other_rev_id] = self.other_tree
539
 
        self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
 
507
        self._maybe_fetch(self.other_branch, self.this_branch, self.other_basis)
540
508
 
541
509
    def set_other_revision(self, revision_id, other_branch):
542
510
        """Set 'other' based on a branch and revision id
591
559
                else:
592
560
                    self.base_rev_id = self.revision_graph.find_unique_lca(
593
561
                                            *lcas)
594
 
                sorted_lca_keys = self.revision_graph.find_merge_order(                
 
562
                sorted_lca_keys = self.revision_graph.find_merge_order(
595
563
                    revisions[0], lcas)
596
564
                if self.base_rev_id == _mod_revision.NULL_REVISION:
597
565
                    self.base_rev_id = sorted_lca_keys[0]
598
 
                
 
566
 
599
567
            if self.base_rev_id == _mod_revision.NULL_REVISION:
600
568
                raise errors.UnrelatedBranches()
601
569
            if self._is_criss_cross:
604
572
                trace.mutter('Criss-cross lcas: %r' % lcas)
605
573
                if self.base_rev_id in lcas:
606
574
                    trace.mutter('Unable to find unique lca. '
607
 
                                 'Fallback %r as best option.' % self.base_rev_id)
 
575
                                 'Fallback %r as best option.'
 
576
                                 % self.base_rev_id)
608
577
                interesting_revision_ids = set(lcas)
609
578
                interesting_revision_ids.add(self.base_rev_id)
610
579
                interesting_trees = dict((t.get_revision_id(), t)
643
612
            self._maybe_fetch(base_branch, self.this_branch, self.base_rev_id)
644
613
 
645
614
    def make_merger(self):
646
 
        kwargs = {'working_tree':self.this_tree, 'this_tree': self.this_tree,
 
615
        kwargs = {'working_tree': self.this_tree, 'this_tree': self.this_tree,
647
616
                  'other_tree': self.other_tree,
648
617
                  'interesting_ids': self.interesting_ids,
649
618
                  'interesting_files': self.interesting_files,
650
619
                  'this_branch': self.this_branch,
 
620
                  'other_branch': self.other_branch,
651
621
                  'do_merge': False}
652
622
        if self.merge_type.requires_base:
653
623
            kwargs['base_tree'] = self.base_tree
679
649
        merge = self.make_merger()
680
650
        if self.other_branch is not None:
681
651
            self.other_branch.update_references(self.this_branch)
 
652
        for hook in Merger.hooks['pre_merge']:
 
653
            hook(merge)
682
654
        merge.do_merge()
 
655
        for hook in Merger.hooks['post_merge']:
 
656
            hook(merge)
683
657
        if self.recurse == 'down':
684
658
            for relpath, file_id in self.this_tree.iter_references():
685
659
                sub_tree = self.this_tree.get_nested_tree(file_id, relpath)
689
663
                    continue
690
664
                sub_merge = Merger(sub_tree.branch, this_tree=sub_tree)
691
665
                sub_merge.merge_type = self.merge_type
692
 
                other_branch = self.other_branch.reference_parent(file_id, relpath)
 
666
                other_branch = self.other_branch.reference_parent(file_id,
 
667
                                                                  relpath)
693
668
                sub_merge.set_other_revision(other_revision, other_branch)
694
669
                base_revision = self.base_tree.get_reference_revision(file_id)
695
670
                sub_merge.base_tree = \
711
686
        merge = operation.run_simple()
712
687
        if len(merge.cooked_conflicts) == 0:
713
688
            if not self.ignore_zero and not trace.is_quiet():
714
 
                trace.note("All changes applied successfully.")
 
689
                trace.note(gettext("All changes applied successfully."))
715
690
        else:
716
 
            trace.note("%d conflicts encountered."
 
691
            trace.note(gettext("%d conflicts encountered.")
717
692
                       % len(merge.cooked_conflicts))
718
693
 
719
694
        return len(merge.cooked_conflicts)
751
726
                 interesting_ids=None, reprocess=False, show_base=False,
752
727
                 pb=None, pp=None, change_reporter=None,
753
728
                 interesting_files=None, do_merge=True,
754
 
                 cherrypick=False, lca_trees=None, this_branch=None):
 
729
                 cherrypick=False, lca_trees=None, this_branch=None,
 
730
                 other_branch=None):
755
731
        """Initialize the merger object and perform the merge.
756
732
 
757
733
        :param working_tree: The working tree to apply the merge to
760
736
        :param other_tree: The other tree to merge changes from
761
737
        :param this_branch: The branch associated with this_tree.  Defaults to
762
738
            this_tree.branch if not supplied.
 
739
        :param other_branch: The branch associated with other_tree, if any.
763
740
        :param interesting_ids: The file_ids of files that should be
764
741
            participate in the merge.  May not be combined with
765
742
            interesting_files.
787
764
            this_branch = this_tree.branch
788
765
        self.interesting_ids = interesting_ids
789
766
        self.interesting_files = interesting_files
790
 
        self.this_tree = working_tree
 
767
        self.working_tree = working_tree
 
768
        self.this_tree = this_tree
791
769
        self.base_tree = base_tree
792
770
        self.other_tree = other_tree
793
771
        self.this_branch = this_branch
 
772
        self.other_branch = other_branch
794
773
        self._raw_conflicts = []
795
774
        self.cooked_conflicts = []
796
775
        self.reprocess = reprocess
812
791
 
813
792
    def do_merge(self):
814
793
        operation = cleanup.OperationWithCleanups(self._do_merge)
815
 
        self.this_tree.lock_tree_write()
 
794
        self.working_tree.lock_tree_write()
 
795
        operation.add_cleanup(self.working_tree.unlock)
 
796
        self.this_tree.lock_read()
816
797
        operation.add_cleanup(self.this_tree.unlock)
817
798
        self.base_tree.lock_read()
818
799
        operation.add_cleanup(self.base_tree.unlock)
821
802
        operation.run()
822
803
 
823
804
    def _do_merge(self, operation):
824
 
        self.tt = transform.TreeTransform(self.this_tree, None)
 
805
        self.tt = transform.TreeTransform(self.working_tree, None)
825
806
        operation.add_cleanup(self.tt.finalize)
826
807
        self._compute_transform()
827
808
        results = self.tt.apply(no_conflicts=True)
828
809
        self.write_modified(results)
829
810
        try:
830
 
            self.this_tree.add_conflicts(self.cooked_conflicts)
 
811
            self.working_tree.add_conflicts(self.cooked_conflicts)
831
812
        except errors.UnsupportedOperation:
832
813
            pass
833
814
 
840
821
        return operation.run_simple()
841
822
 
842
823
    def _make_preview_transform(self):
843
 
        self.tt = transform.TransformPreview(self.this_tree)
 
824
        self.tt = transform.TransformPreview(self.working_tree)
844
825
        self._compute_transform()
845
826
        return self.tt
846
827
 
851
832
        else:
852
833
            entries = self._entries_lca()
853
834
            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]
854
840
        child_pb = ui.ui_factory.nested_progress_bar()
855
841
        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]
859
842
            for num, (file_id, changed, parents3, names3,
860
843
                      executable3) in enumerate(entries):
861
 
                child_pb.update('Preparing file merge', num, len(entries))
 
844
                # Try merging each entry
 
845
                child_pb.update(gettext('Preparing file merge'),
 
846
                                num, len(entries))
862
847
                self._merge_names(file_id, parents3, names3, resolver=resolver)
863
848
                if changed:
864
849
                    file_status = self._do_merge_contents(file_id)
868
853
                    executable3, file_status, resolver=resolver)
869
854
        finally:
870
855
            child_pb.finished()
871
 
        self.fix_root()
 
856
        self.tt.fixup_new_roots()
872
857
        self._finish_computing_transform()
873
858
 
874
859
    def _finish_computing_transform(self):
990
975
                else:
991
976
                    lca_entries.append(lca_ie)
992
977
 
993
 
            if file_id in base_inventory:
 
978
            if base_inventory.has_id(file_id):
994
979
                base_ie = base_inventory[file_id]
995
980
            else:
996
981
                base_ie = _none_entry
997
982
 
998
 
            if file_id in this_inventory:
 
983
            if this_inventory.has_id(file_id):
999
984
                this_ie = this_inventory[file_id]
1000
985
            else:
1001
986
                this_ie = _none_entry
1093
1078
                          ))
1094
1079
        return result
1095
1080
 
 
1081
    @deprecated_method(deprecated_in((2, 4, 0)))
1096
1082
    def fix_root(self):
1097
1083
        if self.tt.final_kind(self.tt.root) is None:
1098
1084
            self.tt.cancel_deletion(self.tt.root)
1105
1091
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1106
1092
        if other_root == self.tt.root:
1107
1093
            return
1108
 
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1109
 
            # the other tree's root is a non-root in the current tree (as when
1110
 
            # a previously unrelated branch is merged into another)
 
1094
        if self.this_tree.inventory.has_id(
 
1095
            self.other_tree.inventory.root.file_id):
 
1096
            # the other tree's root is a non-root in the current tree (as
 
1097
            # when a previously unrelated branch is merged into another)
1111
1098
            return
1112
1099
        if self.tt.final_kind(other_root) is not None:
1113
1100
            other_root_is_present = True
1139
1126
    def write_modified(self, results):
1140
1127
        modified_hashes = {}
1141
1128
        for path in results.modified_paths:
1142
 
            file_id = self.this_tree.path2id(self.this_tree.relpath(path))
 
1129
            file_id = self.working_tree.path2id(self.working_tree.relpath(path))
1143
1130
            if file_id is None:
1144
1131
                continue
1145
 
            hash = self.this_tree.get_file_sha1(file_id)
 
1132
            hash = self.working_tree.get_file_sha1(file_id)
1146
1133
            if hash is None:
1147
1134
                continue
1148
1135
            modified_hashes[file_id] = hash
1149
 
        self.this_tree.set_merge_modified(modified_hashes)
 
1136
        self.working_tree.set_merge_modified(modified_hashes)
1150
1137
 
1151
1138
    @staticmethod
1152
1139
    def parent(entry, file_id):
1165
1152
    @staticmethod
1166
1153
    def contents_sha1(tree, file_id):
1167
1154
        """Determine the sha1 of the file contents (used as a key method)."""
1168
 
        if file_id not in tree:
 
1155
        if not tree.has_id(file_id):
1169
1156
            return None
1170
1157
        return tree.get_file_sha1(file_id)
1171
1158
 
1316
1303
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1317
1304
                                        this_parent, this_name,
1318
1305
                                        other_parent, other_name))
1319
 
        if other_name is None:
 
1306
        if not self.other_tree.has_id(file_id):
1320
1307
            # it doesn't matter whether the result was 'other' or
1321
 
            # 'conflict'-- if there's no 'other', we leave it alone.
 
1308
            # 'conflict'-- if it has no file id, we leave it alone.
1322
1309
            return
1323
1310
        parent_id = parents[self.winner_idx[parent_id_winner]]
1324
 
        if parent_id is not None:
 
1311
        name = names[self.winner_idx[name_winner]]
 
1312
        if parent_id is not None or name is not None:
1325
1313
            # if we get here, name_winner and parent_winner are set to safe
1326
1314
            # values.
1327
 
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1328
 
                                self.tt.trans_id_file_id(parent_id),
 
1315
            if parent_id is None and name is not None:
 
1316
                # if parent_id is None and name is non-None, current file is
 
1317
                # the tree root.
 
1318
                if names[self.winner_idx[parent_id_winner]] != '':
 
1319
                    raise AssertionError(
 
1320
                        'File looks like a root, but named %s' %
 
1321
                        names[self.winner_idx[parent_id_winner]])
 
1322
                parent_trans_id = transform.ROOT_PARENT
 
1323
            else:
 
1324
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1325
            self.tt.adjust_path(name, parent_trans_id,
1329
1326
                                self.tt.trans_id_file_id(file_id))
1330
1327
 
1331
1328
    def _do_merge_contents(self, file_id):
1332
1329
        """Performs a merge on file_id contents."""
1333
1330
        def contents_pair(tree):
1334
 
            if file_id not in tree:
 
1331
            if not tree.has_id(file_id):
1335
1332
                return (None, None)
1336
1333
            kind = tree.kind(file_id)
1337
1334
            if kind == "file":
1366
1363
        # We have a hypothetical conflict, but if we have files, then we
1367
1364
        # can try to merge the content
1368
1365
        trans_id = self.tt.trans_id_file_id(file_id)
1369
 
        params = MergeHookParams(self, file_id, trans_id, this_pair[0],
 
1366
        params = MergeFileHookParams(self, file_id, trans_id, this_pair[0],
1370
1367
            other_pair[0], winner)
1371
1368
        hooks = self.active_hooks
1372
1369
        hook_status = 'not_applicable'
1375
1372
            if hook_status != 'not_applicable':
1376
1373
                # Don't try any more hooks, this one applies.
1377
1374
                break
 
1375
        # If the merge ends up replacing the content of the file, we get rid of
 
1376
        # it at the end of this method (this variable is used to track the
 
1377
        # exceptions to this rule).
 
1378
        keep_this = False
1378
1379
        result = "modified"
1379
1380
        if hook_status == 'not_applicable':
1380
 
            # This is a contents conflict, because none of the available
1381
 
            # functions could merge it.
 
1381
            # No merge hook was able to resolve the situation. Two cases exist:
 
1382
            # a content conflict or a duplicate one.
1382
1383
            result = None
1383
1384
            name = self.tt.final_name(trans_id)
1384
1385
            parent_id = self.tt.final_parent(trans_id)
1385
 
            if self.this_tree.has_id(file_id):
1386
 
                self.tt.unversion_file(trans_id)
1387
 
            file_group = self._dump_conflicts(name, parent_id, file_id,
1388
 
                                              set_version=True)
1389
 
            self._raw_conflicts.append(('contents conflict', file_group))
 
1386
            duplicate = False
 
1387
            inhibit_content_conflict = False
 
1388
            if params.this_kind is None: # file_id is not in THIS
 
1389
                # Is the name used for a different file_id ?
 
1390
                dupe_path = self.other_tree.id2path(file_id)
 
1391
                this_id = self.this_tree.path2id(dupe_path)
 
1392
                if this_id is not None:
 
1393
                    # Two entries for the same path
 
1394
                    keep_this = True
 
1395
                    # versioning the merged file will trigger a duplicate
 
1396
                    # conflict
 
1397
                    self.tt.version_file(file_id, trans_id)
 
1398
                    transform.create_from_tree(
 
1399
                        self.tt, trans_id, self.other_tree, file_id,
 
1400
                        filter_tree_path=self._get_filter_tree_path(file_id))
 
1401
                    inhibit_content_conflict = True
 
1402
            elif params.other_kind is None: # file_id is not in OTHER
 
1403
                # Is the name used for a different file_id ?
 
1404
                dupe_path = self.this_tree.id2path(file_id)
 
1405
                other_id = self.other_tree.path2id(dupe_path)
 
1406
                if other_id is not None:
 
1407
                    # Two entries for the same path again, but here, the other
 
1408
                    # entry will also be merged.  We simply inhibit the
 
1409
                    # 'content' conflict creation because we know OTHER will
 
1410
                    # create (or has already created depending on ordering) an
 
1411
                    # entry at the same path. This will trigger a 'duplicate'
 
1412
                    # conflict later.
 
1413
                    keep_this = True
 
1414
                    inhibit_content_conflict = True
 
1415
            if not inhibit_content_conflict:
 
1416
                if params.this_kind is not None:
 
1417
                    self.tt.unversion_file(trans_id)
 
1418
                # This is a contents conflict, because none of the available
 
1419
                # functions could merge it.
 
1420
                file_group = self._dump_conflicts(name, parent_id, file_id,
 
1421
                                                  set_version=True)
 
1422
                self._raw_conflicts.append(('contents conflict', file_group))
1390
1423
        elif hook_status == 'success':
1391
1424
            self.tt.create_file(lines, trans_id)
1392
1425
        elif hook_status == 'conflicted':
1408
1441
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
1409
1442
        if not self.this_tree.has_id(file_id) and result == "modified":
1410
1443
            self.tt.version_file(file_id, trans_id)
1411
 
        # The merge has been performed, so the old contents should not be
1412
 
        # retained.
1413
 
        self.tt.delete_contents(trans_id)
 
1444
        if not keep_this:
 
1445
            # The merge has been performed and produced a new content, so the
 
1446
            # old contents should not be retained.
 
1447
            self.tt.delete_contents(trans_id)
1414
1448
        return result
1415
1449
 
1416
1450
    def _default_other_winner_merge(self, merge_hook_params):
1417
1451
        """Replace this contents with other."""
1418
1452
        file_id = merge_hook_params.file_id
1419
1453
        trans_id = merge_hook_params.trans_id
1420
 
        file_in_this = self.this_tree.has_id(file_id)
1421
1454
        if self.other_tree.has_id(file_id):
1422
1455
            # OTHER changed the file
1423
 
            wt = self.this_tree
1424
 
            if wt.supports_content_filtering():
1425
 
                # We get the path from the working tree if it exists.
1426
 
                # That fails though when OTHER is adding a file, so
1427
 
                # we fall back to the other tree to find the path if
1428
 
                # it doesn't exist locally.
1429
 
                try:
1430
 
                    filter_tree_path = wt.id2path(file_id)
1431
 
                except errors.NoSuchId:
1432
 
                    filter_tree_path = self.other_tree.id2path(file_id)
1433
 
            else:
1434
 
                # Skip the id2path lookup for older formats
1435
 
                filter_tree_path = None
1436
 
            transform.create_from_tree(self.tt, trans_id,
1437
 
                             self.other_tree, file_id,
1438
 
                             filter_tree_path=filter_tree_path)
 
1456
            transform.create_from_tree(
 
1457
                self.tt, trans_id, self.other_tree, file_id,
 
1458
                filter_tree_path=self._get_filter_tree_path(file_id))
1439
1459
            return 'done', None
1440
 
        elif file_in_this:
 
1460
        elif self.this_tree.has_id(file_id):
1441
1461
            # OTHER deleted the file
1442
1462
            return 'delete', None
1443
1463
        else:
1517
1537
                                              other_lines)
1518
1538
            file_group.append(trans_id)
1519
1539
 
 
1540
 
 
1541
    def _get_filter_tree_path(self, file_id):
 
1542
        if self.this_tree.supports_content_filtering():
 
1543
            # We get the path from the working tree if it exists.
 
1544
            # That fails though when OTHER is adding a file, so
 
1545
            # we fall back to the other tree to find the path if
 
1546
            # it doesn't exist locally.
 
1547
            try:
 
1548
                return self.this_tree.id2path(file_id)
 
1549
            except errors.NoSuchId:
 
1550
                return self.other_tree.id2path(file_id)
 
1551
        # Skip the id2path lookup for older formats
 
1552
        return None
 
1553
 
1520
1554
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1521
1555
                        base_lines=None, other_lines=None, set_version=False,
1522
1556
                        no_base=False):
1605
1639
 
1606
1640
    def cook_conflicts(self, fs_conflicts):
1607
1641
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1608
 
        self.cooked_conflicts.extend(transform.cook_conflicts(
1609
 
                fs_conflicts, self.tt))
 
1642
        content_conflict_file_ids = set()
 
1643
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
1610
1644
        fp = transform.FinalPaths(self.tt)
1611
1645
        for conflict in self._raw_conflicts:
1612
1646
            conflict_type = conflict[0]
1623
1657
                if other_parent is None or other_name is None:
1624
1658
                    other_path = '<deleted>'
1625
1659
                else:
1626
 
                    parent_path =  fp.get_path(
1627
 
                        self.tt.trans_id_file_id(other_parent))
 
1660
                    if other_parent == self.other_tree.get_root_id():
 
1661
                        # The tree transform doesn't know about the other root,
 
1662
                        # so we special case here to avoid a NoFinalPath
 
1663
                        # exception
 
1664
                        parent_path = ''
 
1665
                    else:
 
1666
                        parent_path =  fp.get_path(
 
1667
                            self.tt.trans_id_file_id(other_parent))
1628
1668
                    other_path = osutils.pathjoin(parent_path, other_name)
1629
1669
                c = _mod_conflicts.Conflict.factory(
1630
1670
                    'path conflict', path=this_path,
1634
1674
                for trans_id in conflict[1]:
1635
1675
                    file_id = self.tt.final_file_id(trans_id)
1636
1676
                    if file_id is not None:
 
1677
                        # Ok we found the relevant file-id
1637
1678
                        break
1638
1679
                path = fp.get_path(trans_id)
1639
1680
                for suffix in ('.BASE', '.THIS', '.OTHER'):
1640
1681
                    if path.endswith(suffix):
 
1682
                        # Here is the raw path
1641
1683
                        path = path[:-len(suffix)]
1642
1684
                        break
1643
1685
                c = _mod_conflicts.Conflict.factory(conflict_type,
1644
1686
                                                    path=path, file_id=file_id)
 
1687
                content_conflict_file_ids.add(file_id)
1645
1688
            elif conflict_type == 'text conflict':
1646
1689
                trans_id = conflict[1]
1647
1690
                path = fp.get_path(trans_id)
1650
1693
                                                    path=path, file_id=file_id)
1651
1694
            else:
1652
1695
                raise AssertionError('bad conflict type: %r' % (conflict,))
 
1696
            cooked_conflicts.append(c)
 
1697
 
 
1698
        self.cooked_conflicts = []
 
1699
        # We want to get rid of path conflicts when a corresponding contents
 
1700
        # conflict exists. This can occur when one branch deletes a file while
 
1701
        # the other renames *and* modifies it. In this case, the content
 
1702
        # conflict is enough.
 
1703
        for c in cooked_conflicts:
 
1704
            if (c.typestring == 'path conflict'
 
1705
                and c.file_id in content_conflict_file_ids):
 
1706
                continue
1653
1707
            self.cooked_conflicts.append(c)
1654
1708
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1655
1709
 
1876
1930
            entries = self._entries_to_incorporate()
1877
1931
            entries = list(entries)
1878
1932
            for num, (entry, parent_id) in enumerate(entries):
1879
 
                child_pb.update('Preparing file merge', num, len(entries))
 
1933
                child_pb.update(gettext('Preparing file merge'), num, len(entries))
1880
1934
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
1881
1935
                trans_id = transform.new_by_entry(self.tt, entry,
1882
1936
                    parent_trans_id, self.other_tree)
1900
1954
        name_in_target = osutils.basename(self._target_subdir)
1901
1955
        merge_into_root = subdir.copy()
1902
1956
        merge_into_root.name = name_in_target
1903
 
        if merge_into_root.file_id in self.this_tree.inventory:
 
1957
        if self.this_tree.inventory.has_id(merge_into_root.file_id):
1904
1958
            # Give the root a new file-id.
1905
1959
            # This can happen fairly easily if the directory we are
1906
1960
            # incorporating is the root, and both trees have 'TREE_ROOT' as
1943
1997
    """
1944
1998
    if this_tree is None:
1945
1999
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1946
 
                              "parameter as of bzrlib version 0.8.")
 
2000
                              "parameter")
1947
2001
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1948
2002
                    pb=pb, change_reporter=change_reporter)
1949
2003
    merger.backup_files = backup_files
1966
2020
    merger.set_base_revision(get_revision_id(), this_branch)
1967
2021
    return merger.do_merge()
1968
2022
 
 
2023
 
 
2024
merge_type_registry = registry.Registry()
 
2025
merge_type_registry.register('diff3', Diff3Merger,
 
2026
                             "Merge using external diff3.")
 
2027
merge_type_registry.register('lca', LCAMerger,
 
2028
                             "LCA-newness merge.")
 
2029
merge_type_registry.register('merge3', Merge3Merger,
 
2030
                             "Native diff3-style merge.")
 
2031
merge_type_registry.register('weave', WeaveMerger,
 
2032
                             "Weave-based merge.")
 
2033
 
 
2034
 
1969
2035
def get_merge_type_registry():
1970
 
    """Merge type registry is in bzrlib.option to avoid circular imports.
 
2036
    """Merge type registry was previously in bzrlib.option
1971
2037
 
1972
 
    This method provides a sanctioned way to retrieve it.
 
2038
    This method provides a backwards compatible way to retrieve it.
1973
2039
    """
1974
 
    from bzrlib import option
1975
 
    return option._merge_type_registry
 
2040
    return merge_type_registry
1976
2041
 
1977
2042
 
1978
2043
def _plan_annotate_merge(annotated_a, annotated_b, ancestors_a, ancestors_b):