~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

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
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
20
22
lazy_import(globals(), """
21
23
from bzrlib import (
22
24
    branch as _mod_branch,
 
25
    cleanup,
23
26
    conflicts as _mod_conflicts,
24
27
    debug,
25
28
    generate_ids,
37
40
    versionedfile,
38
41
    workingtree,
39
42
    )
40
 
from bzrlib.cleanup import OperationWithCleanups
 
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,
53
57
 
54
58
def transform_tree(from_tree, to_tree, interesting_ids=None):
55
59
    from_tree.lock_tree_write()
56
 
    operation = OperationWithCleanups(merge_inner)
 
60
    operation = cleanup.OperationWithCleanups(merge_inner)
57
61
    operation.add_cleanup(from_tree.unlock)
58
62
    operation.run_simple(from_tree.branch, to_tree, from_tree,
59
63
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
62
66
class MergeHooks(hooks.Hooks):
63
67
 
64
68
    def __init__(self):
65
 
        hooks.Hooks.__init__(self)
66
 
        self.create_hook(hooks.HookPoint('merge_file_content',
 
69
        hooks.Hooks.__init__(self, "bzrlib.merge", "Merger.hooks")
 
70
        self.add_hook('merge_file_content',
67
71
            "Called with a bzrlib.merge.Merger object to create a per file "
68
72
            "merge object when starting a merge. "
69
73
            "Should return either None or a subclass of "
73
77
            "side has deleted the file and the other has changed it). "
74
78
            "See the AbstractPerFileMerger API docs for details on how it is "
75
79
            "used by merge.",
76
 
            (2, 1), None))
 
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
95
 
        :return : A tuple of (status, chunks), where status is one of
 
107
        :param merge_params: A bzrlib.merge.MergeFileHookParams
 
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
98
111
            strings for the new file contents.
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
 
        def get_id(tree, file_id):
462
 
            revision_id = tree.inventory[file_id].revision
463
 
            return revision_id
464
 
        if self.this_rev_id is None:
465
 
            if self.this_basis_tree.get_file_sha1(file_id) != \
466
 
                self.this_tree.get_file_sha1(file_id):
467
 
                raise errors.WorkingTreeNotRevision(self.this_tree)
468
 
 
469
 
        trees = (self.this_basis_tree, self.other_tree)
470
 
        return [get_id(tree, file_id) for tree in trees]
471
 
 
472
 
    @deprecated_method(deprecated_in((2, 1, 0)))
473
 
    def check_basis(self, check_clean, require_commits=True):
474
 
        if self.this_basis is None and require_commits is True:
475
 
            raise errors.BzrCommandError(
476
 
                "This branch has no commits."
477
 
                " (perhaps you would prefer 'bzr pull')")
478
 
        if check_clean:
479
 
            self.compare_basis()
480
 
            if self.this_basis != self.this_rev_id:
481
 
                raise errors.UncommittedChanges(self.this_tree)
482
 
 
483
 
    @deprecated_method(deprecated_in((2, 1, 0)))
484
 
    def compare_basis(self):
485
 
        try:
486
 
            basis_tree = self.revision_tree(self.this_tree.last_revision())
487
 
        except errors.NoSuchRevision:
488
 
            basis_tree = self.this_tree.basis_tree()
489
 
        if not self.this_tree.has_changes(basis_tree):
490
 
            self.this_rev_id = self.this_basis
491
 
 
492
457
    def set_interesting_files(self, file_list):
493
458
        self.interesting_files = file_list
494
459
 
501
466
    def _add_parent(self):
502
467
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
503
468
        new_parent_trees = []
504
 
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
 
469
        operation = cleanup.OperationWithCleanups(
 
470
            self.this_tree.set_parent_trees)
505
471
        for revision_id in new_parents:
506
472
            try:
507
473
                tree = self.revision_tree(revision_id)
538
504
                raise errors.NoCommits(self.other_branch)
539
505
        if self.other_rev_id is not None:
540
506
            self._cached_trees[self.other_rev_id] = self.other_tree
541
 
        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)
542
508
 
543
509
    def set_other_revision(self, revision_id, other_branch):
544
510
        """Set 'other' based on a branch and revision id
582
548
            elif len(lcas) == 1:
583
549
                self.base_rev_id = list(lcas)[0]
584
550
            else: # len(lcas) > 1
 
551
                self._is_criss_cross = True
585
552
                if len(lcas) > 2:
586
553
                    # find_unique_lca can only handle 2 nodes, so we have to
587
554
                    # start back at the beginning. It is a shame to traverse
592
559
                else:
593
560
                    self.base_rev_id = self.revision_graph.find_unique_lca(
594
561
                                            *lcas)
595
 
                self._is_criss_cross = True
 
562
                sorted_lca_keys = self.revision_graph.find_merge_order(
 
563
                    revisions[0], lcas)
 
564
                if self.base_rev_id == _mod_revision.NULL_REVISION:
 
565
                    self.base_rev_id = sorted_lca_keys[0]
 
566
 
596
567
            if self.base_rev_id == _mod_revision.NULL_REVISION:
597
568
                raise errors.UnrelatedBranches()
598
569
            if self._is_criss_cross:
599
570
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
600
571
                              ' help criss-cross.')
601
572
                trace.mutter('Criss-cross lcas: %r' % lcas)
602
 
                interesting_revision_ids = [self.base_rev_id]
603
 
                interesting_revision_ids.extend(lcas)
 
573
                if self.base_rev_id in lcas:
 
574
                    trace.mutter('Unable to find unique lca. '
 
575
                                 'Fallback %r as best option.'
 
576
                                 % self.base_rev_id)
 
577
                interesting_revision_ids = set(lcas)
 
578
                interesting_revision_ids.add(self.base_rev_id)
604
579
                interesting_trees = dict((t.get_revision_id(), t)
605
580
                    for t in self.this_branch.repository.revision_trees(
606
581
                        interesting_revision_ids))
607
582
                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)
 
583
                if self.base_rev_id in lcas:
 
584
                    self.base_tree = interesting_trees[self.base_rev_id]
 
585
                else:
 
586
                    self.base_tree = interesting_trees.pop(self.base_rev_id)
611
587
                self._lca_trees = [interesting_trees[key]
612
588
                                   for key in sorted_lca_keys]
613
589
            else:
636
612
            self._maybe_fetch(base_branch, self.this_branch, self.base_rev_id)
637
613
 
638
614
    def make_merger(self):
639
 
        kwargs = {'working_tree':self.this_tree, 'this_tree': self.this_tree,
 
615
        kwargs = {'working_tree': self.this_tree, 'this_tree': self.this_tree,
640
616
                  'other_tree': self.other_tree,
641
617
                  'interesting_ids': self.interesting_ids,
642
618
                  'interesting_files': self.interesting_files,
643
619
                  'this_branch': self.this_branch,
 
620
                  'other_branch': self.other_branch,
644
621
                  'do_merge': False}
645
622
        if self.merge_type.requires_base:
646
623
            kwargs['base_tree'] = self.base_tree
672
649
        merge = self.make_merger()
673
650
        if self.other_branch is not None:
674
651
            self.other_branch.update_references(self.this_branch)
 
652
        for hook in Merger.hooks['pre_merge']:
 
653
            hook(merge)
675
654
        merge.do_merge()
 
655
        for hook in Merger.hooks['post_merge']:
 
656
            hook(merge)
676
657
        if self.recurse == 'down':
677
658
            for relpath, file_id in self.this_tree.iter_references():
678
659
                sub_tree = self.this_tree.get_nested_tree(file_id, relpath)
682
663
                    continue
683
664
                sub_merge = Merger(sub_tree.branch, this_tree=sub_tree)
684
665
                sub_merge.merge_type = self.merge_type
685
 
                other_branch = self.other_branch.reference_parent(file_id, relpath)
 
666
                other_branch = self.other_branch.reference_parent(file_id,
 
667
                                                                  relpath)
686
668
                sub_merge.set_other_revision(other_revision, other_branch)
687
669
                base_revision = self.base_tree.get_reference_revision(file_id)
688
670
                sub_merge.base_tree = \
692
674
        return merge
693
675
 
694
676
    def do_merge(self):
695
 
        operation = OperationWithCleanups(self._do_merge_to)
 
677
        operation = cleanup.OperationWithCleanups(self._do_merge_to)
696
678
        self.this_tree.lock_tree_write()
697
679
        operation.add_cleanup(self.this_tree.unlock)
698
680
        if self.base_tree is not None:
704
686
        merge = operation.run_simple()
705
687
        if len(merge.cooked_conflicts) == 0:
706
688
            if not self.ignore_zero and not trace.is_quiet():
707
 
                trace.note("All changes applied successfully.")
 
689
                trace.note(gettext("All changes applied successfully."))
708
690
        else:
709
 
            trace.note("%d conflicts encountered."
 
691
            trace.note(gettext("%d conflicts encountered.")
710
692
                       % len(merge.cooked_conflicts))
711
693
 
712
694
        return len(merge.cooked_conflicts)
744
726
                 interesting_ids=None, reprocess=False, show_base=False,
745
727
                 pb=None, pp=None, change_reporter=None,
746
728
                 interesting_files=None, do_merge=True,
747
 
                 cherrypick=False, lca_trees=None, this_branch=None):
 
729
                 cherrypick=False, lca_trees=None, this_branch=None,
 
730
                 other_branch=None):
748
731
        """Initialize the merger object and perform the merge.
749
732
 
750
733
        :param working_tree: The working tree to apply the merge to
753
736
        :param other_tree: The other tree to merge changes from
754
737
        :param this_branch: The branch associated with this_tree.  Defaults to
755
738
            this_tree.branch if not supplied.
 
739
        :param other_branch: The branch associated with other_tree, if any.
756
740
        :param interesting_ids: The file_ids of files that should be
757
741
            participate in the merge.  May not be combined with
758
742
            interesting_files.
780
764
            this_branch = this_tree.branch
781
765
        self.interesting_ids = interesting_ids
782
766
        self.interesting_files = interesting_files
783
 
        self.this_tree = working_tree
 
767
        self.working_tree = working_tree
 
768
        self.this_tree = this_tree
784
769
        self.base_tree = base_tree
785
770
        self.other_tree = other_tree
786
771
        self.this_branch = this_branch
 
772
        self.other_branch = other_branch
787
773
        self._raw_conflicts = []
788
774
        self.cooked_conflicts = []
789
775
        self.reprocess = reprocess
804
790
            warnings.warn("pb argument to Merge3Merger is deprecated")
805
791
 
806
792
    def do_merge(self):
807
 
        operation = OperationWithCleanups(self._do_merge)
808
 
        self.this_tree.lock_tree_write()
 
793
        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()
809
797
        operation.add_cleanup(self.this_tree.unlock)
810
798
        self.base_tree.lock_read()
811
799
        operation.add_cleanup(self.base_tree.unlock)
814
802
        operation.run()
815
803
 
816
804
    def _do_merge(self, operation):
817
 
        self.tt = transform.TreeTransform(self.this_tree, None)
 
805
        self.tt = transform.TreeTransform(self.working_tree, None)
818
806
        operation.add_cleanup(self.tt.finalize)
819
807
        self._compute_transform()
820
808
        results = self.tt.apply(no_conflicts=True)
821
809
        self.write_modified(results)
822
810
        try:
823
 
            self.this_tree.add_conflicts(self.cooked_conflicts)
 
811
            self.working_tree.add_conflicts(self.cooked_conflicts)
824
812
        except errors.UnsupportedOperation:
825
813
            pass
826
814
 
827
815
    def make_preview_transform(self):
828
 
        operation = OperationWithCleanups(self._make_preview_transform)
 
816
        operation = cleanup.OperationWithCleanups(self._make_preview_transform)
829
817
        self.base_tree.lock_read()
830
818
        operation.add_cleanup(self.base_tree.unlock)
831
819
        self.other_tree.lock_read()
833
821
        return operation.run_simple()
834
822
 
835
823
    def _make_preview_transform(self):
836
 
        self.tt = transform.TransformPreview(self.this_tree)
 
824
        self.tt = transform.TransformPreview(self.working_tree)
837
825
        self._compute_transform()
838
826
        return self.tt
839
827
 
844
832
        else:
845
833
            entries = self._entries_lca()
846
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]
847
840
        child_pb = ui.ui_factory.nested_progress_bar()
848
841
        try:
849
 
            factories = Merger.hooks['merge_file_content']
850
 
            hooks = [factory(self) for factory in factories] + [self]
851
 
            self.active_hooks = [hook for hook in hooks if hook is not None]
852
842
            for num, (file_id, changed, parents3, names3,
853
843
                      executable3) in enumerate(entries):
854
 
                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))
855
847
                self._merge_names(file_id, parents3, names3, resolver=resolver)
856
848
                if changed:
857
849
                    file_status = self._do_merge_contents(file_id)
861
853
                    executable3, file_status, resolver=resolver)
862
854
        finally:
863
855
            child_pb.finished()
864
 
        self.fix_root()
 
856
        self.tt.fixup_new_roots()
865
857
        self._finish_computing_transform()
866
858
 
867
859
    def _finish_computing_transform(self):
881
873
                self.tt.iter_changes(), self.change_reporter)
882
874
        self.cook_conflicts(fs_conflicts)
883
875
        for conflict in self.cooked_conflicts:
884
 
            trace.warning(conflict)
 
876
            trace.warning(unicode(conflict))
885
877
 
886
878
    def _entries3(self):
887
879
        """Gather data about files modified between three trees.
894
886
        """
895
887
        result = []
896
888
        iterator = self.other_tree.iter_changes(self.base_tree,
897
 
                include_unchanged=True, specific_files=self.interesting_files,
 
889
                specific_files=self.interesting_files,
898
890
                extra_trees=[self.this_tree])
899
891
        this_entries = dict((e.file_id, e) for p, e in
900
892
                            self.this_tree.iter_entries_by_dir(
926
918
        it then compares with THIS and BASE.
927
919
 
928
920
        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)
 
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)
937
931
        """
938
932
        if self.interesting_files is not None:
939
933
            lookup_trees = [self.this_tree, self.base_tree]
946
940
        result = []
947
941
        walker = _mod_tree.MultiWalker(self.other_tree, self._lca_trees)
948
942
 
949
 
        base_inventory = self.base_tree.inventory
950
 
        this_inventory = self.this_tree.inventory
 
943
        base_inventory = self.base_tree.root_inventory
 
944
        this_inventory = self.this_tree.root_inventory
951
945
        for path, file_id, other_ie, lca_values in walker.iter_all():
952
946
            # Is this modified at all from any of the other trees?
953
947
            if other_ie is None:
981
975
                else:
982
976
                    lca_entries.append(lca_ie)
983
977
 
984
 
            if file_id in base_inventory:
 
978
            if base_inventory.has_id(file_id):
985
979
                base_ie = base_inventory[file_id]
986
980
            else:
987
981
                base_ie = _none_entry
988
982
 
989
 
            if file_id in this_inventory:
 
983
            if this_inventory.has_id(file_id):
990
984
                this_ie = this_inventory[file_id]
991
985
            else:
992
986
                this_ie = _none_entry
1084
1078
                          ))
1085
1079
        return result
1086
1080
 
1087
 
    def fix_root(self):
1088
 
        try:
1089
 
            self.tt.final_kind(self.tt.root)
1090
 
        except errors.NoSuchFile:
1091
 
            self.tt.cancel_deletion(self.tt.root)
1092
 
        if self.tt.final_file_id(self.tt.root) is None:
1093
 
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
1094
 
                                 self.tt.root)
1095
 
        other_root_file_id = self.other_tree.get_root_id()
1096
 
        if other_root_file_id is None:
1097
 
            return
1098
 
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1099
 
        if other_root == self.tt.root:
1100
 
            return
1101
 
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1102
 
            # the other tree's root is a non-root in the current tree (as when
1103
 
            # a previously unrelated branch is merged into another)
1104
 
            return
1105
 
        try:
1106
 
            self.tt.final_kind(other_root)
1107
 
            other_root_is_present = True
1108
 
        except errors.NoSuchFile:
1109
 
            # other_root doesn't have a physical representation. We still need
1110
 
            # to move any references to the actual root of the tree.
1111
 
            other_root_is_present = False
1112
 
        # 'other_tree.inventory.root' is not present in this tree. We are
1113
 
        # calling adjust_path for children which *want* to be present with a
1114
 
        # correct place to go.
1115
 
        for thing, child in self.other_tree.inventory.root.children.iteritems():
1116
 
            trans_id = self.tt.trans_id_file_id(child.file_id)
1117
 
            if not other_root_is_present:
1118
 
                # FIXME: Make final_kind returns None instead of raising
1119
 
                # NoSuchFile to avoid the ugly construct below -- vila 20100402
1120
 
                try:
1121
 
                    self.tt.final_kind(trans_id)
1122
 
                    # The item exist in the final tree and has a defined place
1123
 
                    # to go already.
1124
 
                    continue
1125
 
                except errors.NoSuchFile, e:
1126
 
                    pass
1127
 
            # Move the item into the root
1128
 
            self.tt.adjust_path(self.tt.final_name(trans_id),
1129
 
                                self.tt.root, trans_id)
1130
 
        if other_root_is_present:
1131
 
            self.tt.cancel_creation(other_root)
1132
 
            self.tt.cancel_versioning(other_root)
1133
 
 
1134
1081
    def write_modified(self, results):
1135
1082
        modified_hashes = {}
1136
1083
        for path in results.modified_paths:
1137
 
            file_id = self.this_tree.path2id(self.this_tree.relpath(path))
 
1084
            file_id = self.working_tree.path2id(self.working_tree.relpath(path))
1138
1085
            if file_id is None:
1139
1086
                continue
1140
 
            hash = self.this_tree.get_file_sha1(file_id)
 
1087
            hash = self.working_tree.get_file_sha1(file_id)
1141
1088
            if hash is None:
1142
1089
                continue
1143
1090
            modified_hashes[file_id] = hash
1144
 
        self.this_tree.set_merge_modified(modified_hashes)
 
1091
        self.working_tree.set_merge_modified(modified_hashes)
1145
1092
 
1146
1093
    @staticmethod
1147
1094
    def parent(entry, file_id):
1160
1107
    @staticmethod
1161
1108
    def contents_sha1(tree, file_id):
1162
1109
        """Determine the sha1 of the file contents (used as a key method)."""
1163
 
        if file_id not in tree:
 
1110
        if not tree.has_id(file_id):
1164
1111
            return None
1165
1112
        return tree.get_file_sha1(file_id)
1166
1113
 
1246
1193
        # At this point, the lcas disagree, and the tip disagree
1247
1194
        return 'conflict'
1248
1195
 
1249
 
    @staticmethod
1250
 
    @deprecated_method(deprecated_in((2, 2, 0)))
1251
 
    def scalar_three_way(this_tree, base_tree, other_tree, file_id, key):
1252
 
        """Do a three-way test on a scalar.
1253
 
        Return "this", "other" or "conflict", depending whether a value wins.
1254
 
        """
1255
 
        key_base = key(base_tree, file_id)
1256
 
        key_other = key(other_tree, file_id)
1257
 
        #if base == other, either they all agree, or only THIS has changed.
1258
 
        if key_base == key_other:
1259
 
            return "this"
1260
 
        key_this = key(this_tree, file_id)
1261
 
        # "Ambiguous clean merge"
1262
 
        if key_this == key_other:
1263
 
            return "this"
1264
 
        elif key_this == key_base:
1265
 
            return "other"
1266
 
        else:
1267
 
            return "conflict"
1268
 
 
1269
1196
    def merge_names(self, file_id):
1270
1197
        def get_entry(tree):
1271
 
            if tree.has_id(file_id):
1272
 
                return tree.inventory[file_id]
1273
 
            else:
 
1198
            try:
 
1199
                return tree.root_inventory[file_id]
 
1200
            except errors.NoSuchId:
1274
1201
                return None
1275
1202
        this_entry = get_entry(self.this_tree)
1276
1203
        other_entry = get_entry(self.other_tree)
1311
1238
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1312
1239
                                        this_parent, this_name,
1313
1240
                                        other_parent, other_name))
1314
 
        if other_name is None:
 
1241
        if not self.other_tree.has_id(file_id):
1315
1242
            # it doesn't matter whether the result was 'other' or
1316
 
            # 'conflict'-- if there's no 'other', we leave it alone.
 
1243
            # 'conflict'-- if it has no file id, we leave it alone.
1317
1244
            return
1318
1245
        parent_id = parents[self.winner_idx[parent_id_winner]]
1319
 
        if parent_id is not None:
 
1246
        name = names[self.winner_idx[name_winner]]
 
1247
        if parent_id is not None or name is not None:
1320
1248
            # if we get here, name_winner and parent_winner are set to safe
1321
1249
            # values.
1322
 
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1323
 
                                self.tt.trans_id_file_id(parent_id),
 
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,
1324
1261
                                self.tt.trans_id_file_id(file_id))
1325
1262
 
1326
1263
    def _do_merge_contents(self, file_id):
1327
1264
        """Performs a merge on file_id contents."""
1328
1265
        def contents_pair(tree):
1329
 
            if file_id not in tree:
 
1266
            if not tree.has_id(file_id):
1330
1267
                return (None, None)
1331
1268
            kind = tree.kind(file_id)
1332
1269
            if kind == "file":
1361
1298
        # We have a hypothetical conflict, but if we have files, then we
1362
1299
        # can try to merge the content
1363
1300
        trans_id = self.tt.trans_id_file_id(file_id)
1364
 
        params = MergeHookParams(self, file_id, trans_id, this_pair[0],
 
1301
        params = MergeFileHookParams(self, file_id, trans_id, this_pair[0],
1365
1302
            other_pair[0], winner)
1366
1303
        hooks = self.active_hooks
1367
1304
        hook_status = 'not_applicable'
1370
1307
            if hook_status != 'not_applicable':
1371
1308
                # Don't try any more hooks, this one applies.
1372
1309
                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
1373
1314
        result = "modified"
1374
1315
        if hook_status == 'not_applicable':
1375
 
            # This is a contents conflict, because none of the available
1376
 
            # functions could merge it.
 
1316
            # No merge hook was able to resolve the situation. Two cases exist:
 
1317
            # a content conflict or a duplicate one.
1377
1318
            result = None
1378
1319
            name = self.tt.final_name(trans_id)
1379
1320
            parent_id = self.tt.final_parent(trans_id)
1380
 
            if self.this_tree.has_id(file_id):
1381
 
                self.tt.unversion_file(trans_id)
1382
 
            file_group = self._dump_conflicts(name, parent_id, file_id,
1383
 
                                              set_version=True)
1384
 
            self._raw_conflicts.append(('contents conflict', file_group))
 
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))
1385
1358
        elif hook_status == 'success':
1386
1359
            self.tt.create_file(lines, trans_id)
1387
1360
        elif hook_status == 'conflicted':
1403
1376
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
1404
1377
        if not self.this_tree.has_id(file_id) and result == "modified":
1405
1378
            self.tt.version_file(file_id, trans_id)
1406
 
        # The merge has been performed, so the old contents should not be
1407
 
        # retained.
1408
 
        try:
 
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.
1409
1382
            self.tt.delete_contents(trans_id)
1410
 
        except errors.NoSuchFile:
1411
 
            pass
1412
1383
        return result
1413
1384
 
1414
1385
    def _default_other_winner_merge(self, merge_hook_params):
1415
1386
        """Replace this contents with other."""
1416
1387
        file_id = merge_hook_params.file_id
1417
1388
        trans_id = merge_hook_params.trans_id
1418
 
        file_in_this = self.this_tree.has_id(file_id)
1419
1389
        if self.other_tree.has_id(file_id):
1420
1390
            # OTHER changed the file
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)
 
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))
1437
1394
            return 'done', None
1438
 
        elif file_in_this:
 
1395
        elif self.this_tree.has_id(file_id):
1439
1396
            # OTHER deleted the file
1440
1397
            return 'delete', None
1441
1398
        else:
1515
1472
                                              other_lines)
1516
1473
            file_group.append(trans_id)
1517
1474
 
 
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
 
1518
1489
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1519
1490
                        base_lines=None, other_lines=None, set_version=False,
1520
1491
                        no_base=False):
1586
1557
        if winner == 'this' and file_status != "modified":
1587
1558
            return
1588
1559
        trans_id = self.tt.trans_id_file_id(file_id)
1589
 
        try:
1590
 
            if self.tt.final_kind(trans_id) != "file":
1591
 
                return
1592
 
        except errors.NoSuchFile:
 
1560
        if self.tt.final_kind(trans_id) != "file":
1593
1561
            return
1594
1562
        if winner == "this":
1595
1563
            executability = this_executable
1606
1574
 
1607
1575
    def cook_conflicts(self, fs_conflicts):
1608
1576
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1609
 
        self.cooked_conflicts.extend(transform.cook_conflicts(
1610
 
                fs_conflicts, self.tt))
 
1577
        content_conflict_file_ids = set()
 
1578
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
1611
1579
        fp = transform.FinalPaths(self.tt)
1612
1580
        for conflict in self._raw_conflicts:
1613
1581
            conflict_type = conflict[0]
1624
1592
                if other_parent is None or other_name is None:
1625
1593
                    other_path = '<deleted>'
1626
1594
                else:
1627
 
                    parent_path =  fp.get_path(
1628
 
                        self.tt.trans_id_file_id(other_parent))
 
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))
1629
1603
                    other_path = osutils.pathjoin(parent_path, other_name)
1630
1604
                c = _mod_conflicts.Conflict.factory(
1631
1605
                    'path conflict', path=this_path,
1635
1609
                for trans_id in conflict[1]:
1636
1610
                    file_id = self.tt.final_file_id(trans_id)
1637
1611
                    if file_id is not None:
 
1612
                        # Ok we found the relevant file-id
1638
1613
                        break
1639
1614
                path = fp.get_path(trans_id)
1640
1615
                for suffix in ('.BASE', '.THIS', '.OTHER'):
1641
1616
                    if path.endswith(suffix):
 
1617
                        # Here is the raw path
1642
1618
                        path = path[:-len(suffix)]
1643
1619
                        break
1644
1620
                c = _mod_conflicts.Conflict.factory(conflict_type,
1645
1621
                                                    path=path, file_id=file_id)
 
1622
                content_conflict_file_ids.add(file_id)
1646
1623
            elif conflict_type == 'text conflict':
1647
1624
                trans_id = conflict[1]
1648
1625
                path = fp.get_path(trans_id)
1651
1628
                                                    path=path, file_id=file_id)
1652
1629
            else:
1653
1630
                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
1654
1642
            self.cooked_conflicts.append(c)
1655
1643
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1656
1644
 
1877
1865
            entries = self._entries_to_incorporate()
1878
1866
            entries = list(entries)
1879
1867
            for num, (entry, parent_id) in enumerate(entries):
1880
 
                child_pb.update('Preparing file merge', num, len(entries))
 
1868
                child_pb.update(gettext('Preparing file merge'), num, len(entries))
1881
1869
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
1882
1870
                trans_id = transform.new_by_entry(self.tt, entry,
1883
1871
                    parent_trans_id, self.other_tree)
1887
1875
 
1888
1876
    def _entries_to_incorporate(self):
1889
1877
        """Yields pairs of (inventory_entry, new_parent)."""
1890
 
        other_inv = self.other_tree.inventory
 
1878
        other_inv = self.other_tree.root_inventory
1891
1879
        subdir_id = other_inv.path2id(self._source_subpath)
1892
1880
        if subdir_id is None:
1893
1881
            # XXX: The error would be clearer if it gave the URL of the source
1895
1883
            raise PathNotInTree(self._source_subpath, "Source tree")
1896
1884
        subdir = other_inv[subdir_id]
1897
1885
        parent_in_target = osutils.dirname(self._target_subdir)
1898
 
        target_id = self.this_tree.inventory.path2id(parent_in_target)
 
1886
        target_id = self.this_tree.path2id(parent_in_target)
1899
1887
        if target_id is None:
1900
1888
            raise PathNotInTree(self._target_subdir, "Target tree")
1901
1889
        name_in_target = osutils.basename(self._target_subdir)
1902
1890
        merge_into_root = subdir.copy()
1903
1891
        merge_into_root.name = name_in_target
1904
 
        if merge_into_root.file_id in self.this_tree.inventory:
 
1892
        if self.this_tree.has_id(merge_into_root.file_id):
1905
1893
            # Give the root a new file-id.
1906
1894
            # This can happen fairly easily if the directory we are
1907
1895
            # incorporating is the root, and both trees have 'TREE_ROOT' as
1944
1932
    """
1945
1933
    if this_tree is None:
1946
1934
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1947
 
                              "parameter as of bzrlib version 0.8.")
 
1935
                              "parameter")
1948
1936
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1949
1937
                    pb=pb, change_reporter=change_reporter)
1950
1938
    merger.backup_files = backup_files
1967
1955
    merger.set_base_revision(get_revision_id(), this_branch)
1968
1956
    return merger.do_merge()
1969
1957
 
 
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
1970
def get_merge_type_registry():
1971
 
    """Merge type registry is in bzrlib.option to avoid circular imports.
 
1971
    """Merge type registry was previously in bzrlib.option
1972
1972
 
1973
 
    This method provides a sanctioned way to retrieve it.
 
1973
    This method provides a backwards compatible way to retrieve it.
1974
1974
    """
1975
 
    from bzrlib import option
1976
 
    return option._merge_type_registry
 
1975
    return merge_type_registry
1977
1976
 
1978
1977
 
1979
1978
def _plan_annotate_merge(annotated_a, annotated_b, ancestors_a, ancestors_b):
2404
2403
class _PlanLCAMerge(_PlanMergeBase):
2405
2404
    """
2406
2405
    This merge algorithm differs from _PlanMerge in that:
 
2406
 
2407
2407
    1. comparisons are done against LCAs only
2408
2408
    2. cases where a contested line is new versus one LCA but old versus
2409
2409
       another are marked as conflicts, by emitting the line as conflicted-a
2450
2450
 
2451
2451
        If a line is killed and new, this indicates that the two merge
2452
2452
        revisions contain differing conflict resolutions.
 
2453
 
2453
2454
        :param revision_id: The id of the revision in which the lines are
2454
2455
            unique
2455
2456
        :param unique_line_numbers: The line numbers of unique lines.
2456
 
        :return a tuple of (new_this, killed_other):
 
2457
        :return: a tuple of (new_this, killed_other)
2457
2458
        """
2458
2459
        new = set()
2459
2460
        killed = set()