~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

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
16
16
 
17
17
import warnings
18
18
 
 
19
from bzrlib.lazy_import import lazy_import
 
20
lazy_import(globals(), """
19
21
from bzrlib import (
20
22
    branch as _mod_branch,
 
23
    cleanup,
21
24
    conflicts as _mod_conflicts,
22
25
    debug,
23
 
    decorators,
24
 
    errors,
 
26
    generate_ids,
25
27
    graph as _mod_graph,
26
 
    hooks,
27
28
    merge3,
28
29
    osutils,
29
30
    patiencediff,
34
35
    tree as _mod_tree,
35
36
    tsort,
36
37
    ui,
37
 
    versionedfile
38
 
    )
39
 
from bzrlib.cleanup import OperationWithCleanups
 
38
    versionedfile,
 
39
    workingtree,
 
40
    )
 
41
from bzrlib.i18n import gettext
 
42
""")
 
43
from bzrlib import (
 
44
    decorators,
 
45
    errors,
 
46
    hooks,
 
47
    )
40
48
from bzrlib.symbol_versioning import (
41
49
    deprecated_in,
42
50
    deprecated_method,
46
54
 
47
55
def transform_tree(from_tree, to_tree, interesting_ids=None):
48
56
    from_tree.lock_tree_write()
49
 
    operation = OperationWithCleanups(merge_inner)
 
57
    operation = cleanup.OperationWithCleanups(merge_inner)
50
58
    operation.add_cleanup(from_tree.unlock)
51
59
    operation.run_simple(from_tree.branch, to_tree, from_tree,
52
60
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
55
63
class MergeHooks(hooks.Hooks):
56
64
 
57
65
    def __init__(self):
58
 
        hooks.Hooks.__init__(self)
59
 
        self.create_hook(hooks.HookPoint('merge_file_content',
 
66
        hooks.Hooks.__init__(self, "bzrlib.merge", "Merger.hooks")
 
67
        self.add_hook('merge_file_content',
60
68
            "Called with a bzrlib.merge.Merger object to create a per file "
61
69
            "merge object when starting a merge. "
62
70
            "Should return either None or a subclass of "
66
74
            "side has deleted the file and the other has changed it). "
67
75
            "See the AbstractPerFileMerger API docs for details on how it is "
68
76
            "used by merge.",
69
 
            (2, 1), None))
 
77
            (2, 1))
70
78
 
71
79
 
72
80
class AbstractPerFileMerger(object):
85
93
        """Attempt to merge the contents of a single file.
86
94
        
87
95
        :param merge_params: A bzrlib.merge.MergeHookParams
88
 
        :return : A tuple of (status, chunks), where status is one of
 
96
        :return: A tuple of (status, chunks), where status is one of
89
97
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
90
98
            is 'success' or 'conflicted', then chunks should be an iterable of
91
99
            strings for the new file contents.
421
429
        return self._cached_trees[revision_id]
422
430
 
423
431
    def _get_tree(self, treespec, possible_transports=None):
424
 
        from bzrlib import workingtree
425
432
        location, revno = treespec
426
433
        if revno is None:
427
434
            tree = workingtree.WorkingTree.open_containing(location)[0]
452
459
    @deprecated_method(deprecated_in((2, 1, 0)))
453
460
    def file_revisions(self, file_id):
454
461
        self.ensure_revision_trees()
455
 
        def get_id(tree, file_id):
456
 
            revision_id = tree.inventory[file_id].revision
457
 
            return revision_id
458
462
        if self.this_rev_id is None:
459
463
            if self.this_basis_tree.get_file_sha1(file_id) != \
460
464
                self.this_tree.get_file_sha1(file_id):
461
465
                raise errors.WorkingTreeNotRevision(self.this_tree)
462
466
 
463
467
        trees = (self.this_basis_tree, self.other_tree)
464
 
        return [get_id(tree, file_id) for tree in trees]
 
468
        return [tree.get_file_revision(file_id) for tree in trees]
465
469
 
466
470
    @deprecated_method(deprecated_in((2, 1, 0)))
467
471
    def check_basis(self, check_clean, require_commits=True):
495
499
    def _add_parent(self):
496
500
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
497
501
        new_parent_trees = []
498
 
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
 
502
        operation = cleanup.OperationWithCleanups(
 
503
            self.this_tree.set_parent_trees)
499
504
        for revision_id in new_parents:
500
505
            try:
501
506
                tree = self.revision_tree(revision_id)
576
581
            elif len(lcas) == 1:
577
582
                self.base_rev_id = list(lcas)[0]
578
583
            else: # len(lcas) > 1
 
584
                self._is_criss_cross = True
579
585
                if len(lcas) > 2:
580
586
                    # find_unique_lca can only handle 2 nodes, so we have to
581
587
                    # start back at the beginning. It is a shame to traverse
586
592
                else:
587
593
                    self.base_rev_id = self.revision_graph.find_unique_lca(
588
594
                                            *lcas)
589
 
                self._is_criss_cross = True
 
595
                sorted_lca_keys = self.revision_graph.find_merge_order(                
 
596
                    revisions[0], lcas)
 
597
                if self.base_rev_id == _mod_revision.NULL_REVISION:
 
598
                    self.base_rev_id = sorted_lca_keys[0]
 
599
                
590
600
            if self.base_rev_id == _mod_revision.NULL_REVISION:
591
601
                raise errors.UnrelatedBranches()
592
602
            if self._is_criss_cross:
593
603
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
594
604
                              ' help criss-cross.')
595
605
                trace.mutter('Criss-cross lcas: %r' % lcas)
596
 
                interesting_revision_ids = [self.base_rev_id]
597
 
                interesting_revision_ids.extend(lcas)
 
606
                if self.base_rev_id in lcas:
 
607
                    trace.mutter('Unable to find unique lca. '
 
608
                                 'Fallback %r as best option.' % self.base_rev_id)
 
609
                interesting_revision_ids = set(lcas)
 
610
                interesting_revision_ids.add(self.base_rev_id)
598
611
                interesting_trees = dict((t.get_revision_id(), t)
599
612
                    for t in self.this_branch.repository.revision_trees(
600
613
                        interesting_revision_ids))
601
614
                self._cached_trees.update(interesting_trees)
602
 
                self.base_tree = interesting_trees.pop(self.base_rev_id)
603
 
                sorted_lca_keys = self.revision_graph.find_merge_order(
604
 
                    revisions[0], lcas)
 
615
                if self.base_rev_id in lcas:
 
616
                    self.base_tree = interesting_trees[self.base_rev_id]
 
617
                else:
 
618
                    self.base_tree = interesting_trees.pop(self.base_rev_id)
605
619
                self._lca_trees = [interesting_trees[key]
606
620
                                   for key in sorted_lca_keys]
607
621
            else:
686
700
        return merge
687
701
 
688
702
    def do_merge(self):
689
 
        operation = OperationWithCleanups(self._do_merge_to)
 
703
        operation = cleanup.OperationWithCleanups(self._do_merge_to)
690
704
        self.this_tree.lock_tree_write()
691
705
        operation.add_cleanup(self.this_tree.unlock)
692
706
        if self.base_tree is not None:
698
712
        merge = operation.run_simple()
699
713
        if len(merge.cooked_conflicts) == 0:
700
714
            if not self.ignore_zero and not trace.is_quiet():
701
 
                trace.note("All changes applied successfully.")
 
715
                trace.note(gettext("All changes applied successfully."))
702
716
        else:
703
 
            trace.note("%d conflicts encountered."
 
717
            trace.note(gettext("%d conflicts encountered.")
704
718
                       % len(merge.cooked_conflicts))
705
719
 
706
720
        return len(merge.cooked_conflicts)
798
812
            warnings.warn("pb argument to Merge3Merger is deprecated")
799
813
 
800
814
    def do_merge(self):
801
 
        operation = OperationWithCleanups(self._do_merge)
 
815
        operation = cleanup.OperationWithCleanups(self._do_merge)
802
816
        self.this_tree.lock_tree_write()
803
817
        operation.add_cleanup(self.this_tree.unlock)
804
818
        self.base_tree.lock_read()
819
833
            pass
820
834
 
821
835
    def make_preview_transform(self):
822
 
        operation = OperationWithCleanups(self._make_preview_transform)
 
836
        operation = cleanup.OperationWithCleanups(self._make_preview_transform)
823
837
        self.base_tree.lock_read()
824
838
        operation.add_cleanup(self.base_tree.unlock)
825
839
        self.other_tree.lock_read()
845
859
            self.active_hooks = [hook for hook in hooks if hook is not None]
846
860
            for num, (file_id, changed, parents3, names3,
847
861
                      executable3) in enumerate(entries):
848
 
                child_pb.update('Preparing file merge', num, len(entries))
 
862
                child_pb.update(gettext('Preparing file merge'), num, len(entries))
849
863
                self._merge_names(file_id, parents3, names3, resolver=resolver)
850
864
                if changed:
851
865
                    file_status = self._do_merge_contents(file_id)
855
869
                    executable3, file_status, resolver=resolver)
856
870
        finally:
857
871
            child_pb.finished()
858
 
        self.fix_root()
 
872
        self.tt.fixup_new_roots()
 
873
        self._finish_computing_transform()
 
874
 
 
875
    def _finish_computing_transform(self):
 
876
        """Finalize the transform and report the changes.
 
877
 
 
878
        This is the second half of _compute_transform.
 
879
        """
859
880
        child_pb = ui.ui_factory.nested_progress_bar()
860
881
        try:
861
882
            fs_conflicts = transform.resolve_conflicts(self.tt, child_pb,
868
889
                self.tt.iter_changes(), self.change_reporter)
869
890
        self.cook_conflicts(fs_conflicts)
870
891
        for conflict in self.cooked_conflicts:
871
 
            trace.warning(conflict)
 
892
            trace.warning(unicode(conflict))
872
893
 
873
894
    def _entries3(self):
874
895
        """Gather data about files modified between three trees.
881
902
        """
882
903
        result = []
883
904
        iterator = self.other_tree.iter_changes(self.base_tree,
884
 
                include_unchanged=True, specific_files=self.interesting_files,
 
905
                specific_files=self.interesting_files,
885
906
                extra_trees=[self.this_tree])
886
907
        this_entries = dict((e.file_id, e) for p, e in
887
908
                            self.this_tree.iter_entries_by_dir(
913
934
        it then compares with THIS and BASE.
914
935
 
915
936
        For the multi-valued entries, the format will be (BASE, [lca1, lca2])
916
 
        :return: [(file_id, changed, parents, names, executable)]
917
 
            file_id     Simple file_id of the entry
918
 
            changed     Boolean, True if the kind or contents changed
919
 
                        else False
920
 
            parents     ((base, [parent_id, in, lcas]), parent_id_other,
921
 
                         parent_id_this)
922
 
            names       ((base, [name, in, lcas]), name_in_other, name_in_this)
923
 
            executable  ((base, [exec, in, lcas]), exec_in_other, exec_in_this)
 
937
 
 
938
        :return: [(file_id, changed, parents, names, executable)], where:
 
939
 
 
940
            * file_id: Simple file_id of the entry
 
941
            * changed: Boolean, True if the kind or contents changed else False
 
942
            * parents: ((base, [parent_id, in, lcas]), parent_id_other,
 
943
                        parent_id_this)
 
944
            * names:   ((base, [name, in, lcas]), name_in_other, name_in_this)
 
945
            * executable: ((base, [exec, in, lcas]), exec_in_other,
 
946
                        exec_in_this)
924
947
        """
925
948
        if self.interesting_files is not None:
926
949
            lookup_trees = [self.this_tree, self.base_tree]
968
991
                else:
969
992
                    lca_entries.append(lca_ie)
970
993
 
971
 
            if file_id in base_inventory:
 
994
            if base_inventory.has_id(file_id):
972
995
                base_ie = base_inventory[file_id]
973
996
            else:
974
997
                base_ie = _none_entry
975
998
 
976
 
            if file_id in this_inventory:
 
999
            if this_inventory.has_id(file_id):
977
1000
                this_ie = this_inventory[file_id]
978
1001
            else:
979
1002
                this_ie = _none_entry
1071
1094
                          ))
1072
1095
        return result
1073
1096
 
1074
 
 
 
1097
    @deprecated_method(deprecated_in((2, 4, 0)))
1075
1098
    def fix_root(self):
1076
 
        try:
1077
 
            self.tt.final_kind(self.tt.root)
1078
 
        except errors.NoSuchFile:
 
1099
        if self.tt.final_kind(self.tt.root) is None:
1079
1100
            self.tt.cancel_deletion(self.tt.root)
1080
1101
        if self.tt.final_file_id(self.tt.root) is None:
1081
1102
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
1086
1107
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1087
1108
        if other_root == self.tt.root:
1088
1109
            return
1089
 
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1090
 
            # the other tree's root is a non-root in the current tree (as when
1091
 
            # a previously unrelated branch is merged into another)
 
1110
        if self.this_tree.inventory.has_id(
 
1111
            self.other_tree.inventory.root.file_id):
 
1112
            # the other tree's root is a non-root in the current tree (as
 
1113
            # when a previously unrelated branch is merged into another)
1092
1114
            return
1093
 
        try:
1094
 
            self.tt.final_kind(other_root)
 
1115
        if self.tt.final_kind(other_root) is not None:
1095
1116
            other_root_is_present = True
1096
 
        except errors.NoSuchFile:
 
1117
        else:
1097
1118
            # other_root doesn't have a physical representation. We still need
1098
1119
            # to move any references to the actual root of the tree.
1099
1120
            other_root_is_present = False
1100
1121
        # 'other_tree.inventory.root' is not present in this tree. We are
1101
1122
        # calling adjust_path for children which *want* to be present with a
1102
1123
        # correct place to go.
1103
 
        for thing, child in self.other_tree.inventory.root.children.iteritems():
 
1124
        for _, child in self.other_tree.inventory.root.children.iteritems():
1104
1125
            trans_id = self.tt.trans_id_file_id(child.file_id)
1105
1126
            if not other_root_is_present:
1106
 
                # FIXME: Make final_kind returns None instead of raising
1107
 
                # NoSuchFile to avoid the ugly construct below -- vila 20100402
1108
 
                try:
1109
 
                    self.tt.final_kind(trans_id)
 
1127
                if self.tt.final_kind(trans_id) is not None:
1110
1128
                    # The item exist in the final tree and has a defined place
1111
1129
                    # to go already.
1112
1130
                    continue
1113
 
                except errors.NoSuchFile, e:
1114
 
                    pass
1115
1131
            # Move the item into the root
1116
 
            self.tt.adjust_path(self.tt.final_name(trans_id),
1117
 
                                self.tt.root, trans_id)
 
1132
            try:
 
1133
                final_name = self.tt.final_name(trans_id)
 
1134
            except errors.NoFinalPath:
 
1135
                # This file is not present anymore, ignore it.
 
1136
                continue
 
1137
            self.tt.adjust_path(final_name, self.tt.root, trans_id)
1118
1138
        if other_root_is_present:
1119
1139
            self.tt.cancel_creation(other_root)
1120
1140
            self.tt.cancel_versioning(other_root)
1148
1168
    @staticmethod
1149
1169
    def contents_sha1(tree, file_id):
1150
1170
        """Determine the sha1 of the file contents (used as a key method)."""
1151
 
        if file_id not in tree:
 
1171
        if not tree.has_id(file_id):
1152
1172
            return None
1153
1173
        return tree.get_file_sha1(file_id)
1154
1174
 
1299
1319
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1300
1320
                                        this_parent, this_name,
1301
1321
                                        other_parent, other_name))
1302
 
        if other_name is None:
 
1322
        if not self.other_tree.has_id(file_id):
1303
1323
            # it doesn't matter whether the result was 'other' or
1304
 
            # 'conflict'-- if there's no 'other', we leave it alone.
 
1324
            # 'conflict'-- if it has no file id, we leave it alone.
1305
1325
            return
1306
1326
        parent_id = parents[self.winner_idx[parent_id_winner]]
1307
 
        if parent_id is not None:
 
1327
        name = names[self.winner_idx[name_winner]]
 
1328
        if parent_id is not None or name is not None:
1308
1329
            # if we get here, name_winner and parent_winner are set to safe
1309
1330
            # values.
1310
 
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1311
 
                                self.tt.trans_id_file_id(parent_id),
 
1331
            if parent_id is None and name is not None:
 
1332
                # if parent_id is None and name is non-None, current file is
 
1333
                # the tree root.
 
1334
                if names[self.winner_idx[parent_id_winner]] != '':
 
1335
                    raise AssertionError(
 
1336
                        'File looks like a root, but named %s' %
 
1337
                        names[self.winner_idx[parent_id_winner]])
 
1338
                parent_trans_id = transform.ROOT_PARENT
 
1339
            else:
 
1340
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1341
            self.tt.adjust_path(name, parent_trans_id,
1312
1342
                                self.tt.trans_id_file_id(file_id))
1313
1343
 
1314
1344
    def _do_merge_contents(self, file_id):
1315
1345
        """Performs a merge on file_id contents."""
1316
1346
        def contents_pair(tree):
1317
 
            if file_id not in tree:
 
1347
            if not tree.has_id(file_id):
1318
1348
                return (None, None)
1319
1349
            kind = tree.kind(file_id)
1320
1350
            if kind == "file":
1393
1423
            self.tt.version_file(file_id, trans_id)
1394
1424
        # The merge has been performed, so the old contents should not be
1395
1425
        # retained.
1396
 
        try:
1397
 
            self.tt.delete_contents(trans_id)
1398
 
        except errors.NoSuchFile:
1399
 
            pass
 
1426
        self.tt.delete_contents(trans_id)
1400
1427
        return result
1401
1428
 
1402
1429
    def _default_other_winner_merge(self, merge_hook_params):
1455
1482
    def get_lines(self, tree, file_id):
1456
1483
        """Return the lines in a file, or an empty list."""
1457
1484
        if tree.has_id(file_id):
1458
 
            return tree.get_file(file_id).readlines()
 
1485
            return tree.get_file_lines(file_id)
1459
1486
        else:
1460
1487
            return []
1461
1488
 
1574
1601
        if winner == 'this' and file_status != "modified":
1575
1602
            return
1576
1603
        trans_id = self.tt.trans_id_file_id(file_id)
1577
 
        try:
1578
 
            if self.tt.final_kind(trans_id) != "file":
1579
 
                return
1580
 
        except errors.NoSuchFile:
 
1604
        if self.tt.final_kind(trans_id) != "file":
1581
1605
            return
1582
1606
        if winner == "this":
1583
1607
            executability = this_executable
1594
1618
 
1595
1619
    def cook_conflicts(self, fs_conflicts):
1596
1620
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1597
 
        self.cooked_conflicts.extend(transform.cook_conflicts(
1598
 
                fs_conflicts, self.tt))
 
1621
        content_conflict_file_ids = set()
 
1622
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
1599
1623
        fp = transform.FinalPaths(self.tt)
1600
1624
        for conflict in self._raw_conflicts:
1601
1625
            conflict_type = conflict[0]
1612
1636
                if other_parent is None or other_name is None:
1613
1637
                    other_path = '<deleted>'
1614
1638
                else:
1615
 
                    parent_path =  fp.get_path(
1616
 
                        self.tt.trans_id_file_id(other_parent))
 
1639
                    if other_parent == self.other_tree.get_root_id():
 
1640
                        # The tree transform doesn't know about the other root,
 
1641
                        # so we special case here to avoid a NoFinalPath
 
1642
                        # exception
 
1643
                        parent_path = ''
 
1644
                    else:
 
1645
                        parent_path =  fp.get_path(
 
1646
                            self.tt.trans_id_file_id(other_parent))
1617
1647
                    other_path = osutils.pathjoin(parent_path, other_name)
1618
1648
                c = _mod_conflicts.Conflict.factory(
1619
1649
                    'path conflict', path=this_path,
1631
1661
                        break
1632
1662
                c = _mod_conflicts.Conflict.factory(conflict_type,
1633
1663
                                                    path=path, file_id=file_id)
 
1664
                content_conflict_file_ids.add(file_id)
1634
1665
            elif conflict_type == 'text conflict':
1635
1666
                trans_id = conflict[1]
1636
1667
                path = fp.get_path(trans_id)
1639
1670
                                                    path=path, file_id=file_id)
1640
1671
            else:
1641
1672
                raise AssertionError('bad conflict type: %r' % (conflict,))
 
1673
            cooked_conflicts.append(c)
 
1674
 
 
1675
        self.cooked_conflicts = []
 
1676
        # We want to get rid of path conflicts when a corresponding contents
 
1677
        # conflict exists. This can occur when one branch deletes a file while
 
1678
        # the other renames *and* modifies it. In this case, the content
 
1679
        # conflict is enough.
 
1680
        for c in cooked_conflicts:
 
1681
            if (c.typestring == 'path conflict'
 
1682
                and c.file_id in content_conflict_file_ids):
 
1683
                continue
1642
1684
            self.cooked_conflicts.append(c)
1643
1685
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1644
1686
 
1750
1792
            osutils.rmtree(temp_dir)
1751
1793
 
1752
1794
 
 
1795
class PathNotInTree(errors.BzrError):
 
1796
 
 
1797
    _fmt = """Merge-into failed because %(tree)s does not contain %(path)s."""
 
1798
 
 
1799
    def __init__(self, path, tree):
 
1800
        errors.BzrError.__init__(self, path=path, tree=tree)
 
1801
 
 
1802
 
 
1803
class MergeIntoMerger(Merger):
 
1804
    """Merger that understands other_tree will be merged into a subdir.
 
1805
 
 
1806
    This also changes the Merger api so that it uses real Branch, revision_id,
 
1807
    and RevisonTree objects, rather than using revision specs.
 
1808
    """
 
1809
 
 
1810
    def __init__(self, this_tree, other_branch, other_tree, target_subdir,
 
1811
            source_subpath, other_rev_id=None):
 
1812
        """Create a new MergeIntoMerger object.
 
1813
 
 
1814
        source_subpath in other_tree will be effectively copied to
 
1815
        target_subdir in this_tree.
 
1816
 
 
1817
        :param this_tree: The tree that we will be merging into.
 
1818
        :param other_branch: The Branch we will be merging from.
 
1819
        :param other_tree: The RevisionTree object we want to merge.
 
1820
        :param target_subdir: The relative path where we want to merge
 
1821
            other_tree into this_tree
 
1822
        :param source_subpath: The relative path specifying the subtree of
 
1823
            other_tree to merge into this_tree.
 
1824
        """
 
1825
        # It is assumed that we are merging a tree that is not in our current
 
1826
        # ancestry, which means we are using the "EmptyTree" as our basis.
 
1827
        null_ancestor_tree = this_tree.branch.repository.revision_tree(
 
1828
                                _mod_revision.NULL_REVISION)
 
1829
        super(MergeIntoMerger, self).__init__(
 
1830
            this_branch=this_tree.branch,
 
1831
            this_tree=this_tree,
 
1832
            other_tree=other_tree,
 
1833
            base_tree=null_ancestor_tree,
 
1834
            )
 
1835
        self._target_subdir = target_subdir
 
1836
        self._source_subpath = source_subpath
 
1837
        self.other_branch = other_branch
 
1838
        if other_rev_id is None:
 
1839
            other_rev_id = other_tree.get_revision_id()
 
1840
        self.other_rev_id = self.other_basis = other_rev_id
 
1841
        self.base_is_ancestor = True
 
1842
        self.backup_files = True
 
1843
        self.merge_type = Merge3Merger
 
1844
        self.show_base = False
 
1845
        self.reprocess = False
 
1846
        self.interesting_ids = None
 
1847
        self.merge_type = _MergeTypeParameterizer(MergeIntoMergeType,
 
1848
              target_subdir=self._target_subdir,
 
1849
              source_subpath=self._source_subpath)
 
1850
        if self._source_subpath != '':
 
1851
            # If this isn't a partial merge make sure the revisions will be
 
1852
            # present.
 
1853
            self._maybe_fetch(self.other_branch, self.this_branch,
 
1854
                self.other_basis)
 
1855
 
 
1856
    def set_pending(self):
 
1857
        if self._source_subpath != '':
 
1858
            return
 
1859
        Merger.set_pending(self)
 
1860
 
 
1861
 
 
1862
class _MergeTypeParameterizer(object):
 
1863
    """Wrap a merge-type class to provide extra parameters.
 
1864
    
 
1865
    This is hack used by MergeIntoMerger to pass some extra parameters to its
 
1866
    merge_type.  Merger.do_merge() sets up its own set of parameters to pass to
 
1867
    the 'merge_type' member.  It is difficult override do_merge without
 
1868
    re-writing the whole thing, so instead we create a wrapper which will pass
 
1869
    the extra parameters.
 
1870
    """
 
1871
 
 
1872
    def __init__(self, merge_type, **kwargs):
 
1873
        self._extra_kwargs = kwargs
 
1874
        self._merge_type = merge_type
 
1875
 
 
1876
    def __call__(self, *args, **kwargs):
 
1877
        kwargs.update(self._extra_kwargs)
 
1878
        return self._merge_type(*args, **kwargs)
 
1879
 
 
1880
    def __getattr__(self, name):
 
1881
        return getattr(self._merge_type, name)
 
1882
 
 
1883
 
 
1884
class MergeIntoMergeType(Merge3Merger):
 
1885
    """Merger that incorporates a tree (or part of a tree) into another."""
 
1886
 
 
1887
    def __init__(self, *args, **kwargs):
 
1888
        """Initialize the merger object.
 
1889
 
 
1890
        :param args: See Merge3Merger.__init__'s args.
 
1891
        :param kwargs: See Merge3Merger.__init__'s keyword args, except for
 
1892
            source_subpath and target_subdir.
 
1893
        :keyword source_subpath: The relative path specifying the subtree of
 
1894
            other_tree to merge into this_tree.
 
1895
        :keyword target_subdir: The relative path where we want to merge
 
1896
            other_tree into this_tree
 
1897
        """
 
1898
        # All of the interesting work happens during Merge3Merger.__init__(),
 
1899
        # so we have have to hack in to get our extra parameters set.
 
1900
        self._source_subpath = kwargs.pop('source_subpath')
 
1901
        self._target_subdir = kwargs.pop('target_subdir')
 
1902
        super(MergeIntoMergeType, self).__init__(*args, **kwargs)
 
1903
 
 
1904
    def _compute_transform(self):
 
1905
        child_pb = ui.ui_factory.nested_progress_bar()
 
1906
        try:
 
1907
            entries = self._entries_to_incorporate()
 
1908
            entries = list(entries)
 
1909
            for num, (entry, parent_id) in enumerate(entries):
 
1910
                child_pb.update(gettext('Preparing file merge'), num, len(entries))
 
1911
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1912
                trans_id = transform.new_by_entry(self.tt, entry,
 
1913
                    parent_trans_id, self.other_tree)
 
1914
        finally:
 
1915
            child_pb.finished()
 
1916
        self._finish_computing_transform()
 
1917
 
 
1918
    def _entries_to_incorporate(self):
 
1919
        """Yields pairs of (inventory_entry, new_parent)."""
 
1920
        other_inv = self.other_tree.inventory
 
1921
        subdir_id = other_inv.path2id(self._source_subpath)
 
1922
        if subdir_id is None:
 
1923
            # XXX: The error would be clearer if it gave the URL of the source
 
1924
            # branch, but we don't have a reference to that here.
 
1925
            raise PathNotInTree(self._source_subpath, "Source tree")
 
1926
        subdir = other_inv[subdir_id]
 
1927
        parent_in_target = osutils.dirname(self._target_subdir)
 
1928
        target_id = self.this_tree.inventory.path2id(parent_in_target)
 
1929
        if target_id is None:
 
1930
            raise PathNotInTree(self._target_subdir, "Target tree")
 
1931
        name_in_target = osutils.basename(self._target_subdir)
 
1932
        merge_into_root = subdir.copy()
 
1933
        merge_into_root.name = name_in_target
 
1934
        if self.this_tree.inventory.has_id(merge_into_root.file_id):
 
1935
            # Give the root a new file-id.
 
1936
            # This can happen fairly easily if the directory we are
 
1937
            # incorporating is the root, and both trees have 'TREE_ROOT' as
 
1938
            # their root_id.  Users will expect this to Just Work, so we
 
1939
            # change the file-id here.
 
1940
            # Non-root file-ids could potentially conflict too.  That's really
 
1941
            # an edge case, so we don't do anything special for those.  We let
 
1942
            # them cause conflicts.
 
1943
            merge_into_root.file_id = generate_ids.gen_file_id(name_in_target)
 
1944
        yield (merge_into_root, target_id)
 
1945
        if subdir.kind != 'directory':
 
1946
            # No children, so we are done.
 
1947
            return
 
1948
        for ignored_path, entry in other_inv.iter_entries_by_dir(subdir_id):
 
1949
            parent_id = entry.parent_id
 
1950
            if parent_id == subdir.file_id:
 
1951
                # The root's parent ID has changed, so make sure children of
 
1952
                # the root refer to the new ID.
 
1953
                parent_id = merge_into_root.file_id
 
1954
            yield (entry, parent_id)
 
1955
 
 
1956
 
1753
1957
def merge_inner(this_branch, other_tree, base_tree, ignore_zero=False,
1754
1958
                backup_files=False,
1755
1959
                merge_type=Merge3Merger,
1763
1967
                change_reporter=None):
1764
1968
    """Primary interface for merging.
1765
1969
 
1766
 
        typical use is probably
1767
 
        'merge_inner(branch, branch.get_revision_tree(other_revision),
1768
 
                     branch.get_revision_tree(base_revision))'
1769
 
        """
 
1970
    Typical use is probably::
 
1971
 
 
1972
        merge_inner(branch, branch.get_revision_tree(other_revision),
 
1973
                    branch.get_revision_tree(base_revision))
 
1974
    """
1770
1975
    if this_tree is None:
1771
1976
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1772
 
                              "parameter as of bzrlib version 0.8.")
 
1977
                              "parameter")
1773
1978
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1774
1979
                    pb=pb, change_reporter=change_reporter)
1775
1980
    merger.backup_files = backup_files
2229
2434
class _PlanLCAMerge(_PlanMergeBase):
2230
2435
    """
2231
2436
    This merge algorithm differs from _PlanMerge in that:
 
2437
 
2232
2438
    1. comparisons are done against LCAs only
2233
2439
    2. cases where a contested line is new versus one LCA but old versus
2234
2440
       another are marked as conflicts, by emitting the line as conflicted-a
2275
2481
 
2276
2482
        If a line is killed and new, this indicates that the two merge
2277
2483
        revisions contain differing conflict resolutions.
 
2484
 
2278
2485
        :param revision_id: The id of the revision in which the lines are
2279
2486
            unique
2280
2487
        :param unique_line_numbers: The line numbers of unique lines.
2281
 
        :return a tuple of (new_this, killed_other):
 
2488
        :return: a tuple of (new_this, killed_other)
2282
2489
        """
2283
2490
        new = set()
2284
2491
        killed = set()