/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Samuel Bronson
  • Date: 2012-08-30 21:54:35 UTC
  • mto: (6015.57.3 2.4)
  • mto: This revision was merged to the branch mainline in revision 6558.
  • Revision ID: naesten@gmail.com-20120830215435-akw1leqrtioh4q1d
Update "Python versions" section of doc/developers/code-style.txt.

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
""")
 
42
from bzrlib import (
 
43
    decorators,
 
44
    errors,
 
45
    hooks,
 
46
    )
40
47
from bzrlib.symbol_versioning import (
41
48
    deprecated_in,
42
49
    deprecated_method,
46
53
 
47
54
def transform_tree(from_tree, to_tree, interesting_ids=None):
48
55
    from_tree.lock_tree_write()
49
 
    operation = OperationWithCleanups(merge_inner)
 
56
    operation = cleanup.OperationWithCleanups(merge_inner)
50
57
    operation.add_cleanup(from_tree.unlock)
51
58
    operation.run_simple(from_tree.branch, to_tree, from_tree,
52
59
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
55
62
class MergeHooks(hooks.Hooks):
56
63
 
57
64
    def __init__(self):
58
 
        hooks.Hooks.__init__(self)
59
 
        self.create_hook(hooks.HookPoint('merge_file_content',
 
65
        hooks.Hooks.__init__(self, "bzrlib.merge", "Merger.hooks")
 
66
        self.add_hook('merge_file_content',
60
67
            "Called with a bzrlib.merge.Merger object to create a per file "
61
68
            "merge object when starting a merge. "
62
69
            "Should return either None or a subclass of "
66
73
            "side has deleted the file and the other has changed it). "
67
74
            "See the AbstractPerFileMerger API docs for details on how it is "
68
75
            "used by merge.",
69
 
            (2, 1), None))
 
76
            (2, 1))
70
77
 
71
78
 
72
79
class AbstractPerFileMerger(object):
85
92
        """Attempt to merge the contents of a single file.
86
93
        
87
94
        :param merge_params: A bzrlib.merge.MergeHookParams
88
 
        :return : A tuple of (status, chunks), where status is one of
 
95
        :return: A tuple of (status, chunks), where status is one of
89
96
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
90
97
            is 'success' or 'conflicted', then chunks should be an iterable of
91
98
            strings for the new file contents.
421
428
        return self._cached_trees[revision_id]
422
429
 
423
430
    def _get_tree(self, treespec, possible_transports=None):
424
 
        from bzrlib import workingtree
425
431
        location, revno = treespec
426
432
        if revno is None:
427
433
            tree = workingtree.WorkingTree.open_containing(location)[0]
452
458
    @deprecated_method(deprecated_in((2, 1, 0)))
453
459
    def file_revisions(self, file_id):
454
460
        self.ensure_revision_trees()
455
 
        def get_id(tree, file_id):
456
 
            revision_id = tree.inventory[file_id].revision
457
 
            return revision_id
458
461
        if self.this_rev_id is None:
459
462
            if self.this_basis_tree.get_file_sha1(file_id) != \
460
463
                self.this_tree.get_file_sha1(file_id):
461
464
                raise errors.WorkingTreeNotRevision(self.this_tree)
462
465
 
463
466
        trees = (self.this_basis_tree, self.other_tree)
464
 
        return [get_id(tree, file_id) for tree in trees]
 
467
        return [tree.get_file_revision(file_id) for tree in trees]
465
468
 
466
469
    @deprecated_method(deprecated_in((2, 1, 0)))
467
470
    def check_basis(self, check_clean, require_commits=True):
495
498
    def _add_parent(self):
496
499
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
497
500
        new_parent_trees = []
498
 
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
 
501
        operation = cleanup.OperationWithCleanups(
 
502
            self.this_tree.set_parent_trees)
499
503
        for revision_id in new_parents:
500
504
            try:
501
505
                tree = self.revision_tree(revision_id)
576
580
            elif len(lcas) == 1:
577
581
                self.base_rev_id = list(lcas)[0]
578
582
            else: # len(lcas) > 1
 
583
                self._is_criss_cross = True
579
584
                if len(lcas) > 2:
580
585
                    # find_unique_lca can only handle 2 nodes, so we have to
581
586
                    # start back at the beginning. It is a shame to traverse
586
591
                else:
587
592
                    self.base_rev_id = self.revision_graph.find_unique_lca(
588
593
                                            *lcas)
589
 
                self._is_criss_cross = True
 
594
                sorted_lca_keys = self.revision_graph.find_merge_order(
 
595
                    revisions[0], lcas)
 
596
                if self.base_rev_id == _mod_revision.NULL_REVISION:
 
597
                    self.base_rev_id = sorted_lca_keys[0]
 
598
 
590
599
            if self.base_rev_id == _mod_revision.NULL_REVISION:
591
600
                raise errors.UnrelatedBranches()
592
601
            if self._is_criss_cross:
593
602
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
594
603
                              ' help criss-cross.')
595
604
                trace.mutter('Criss-cross lcas: %r' % lcas)
596
 
                interesting_revision_ids = [self.base_rev_id]
597
 
                interesting_revision_ids.extend(lcas)
 
605
                if self.base_rev_id in lcas:
 
606
                    trace.mutter('Unable to find unique lca. '
 
607
                                 'Fallback %r as best option.'
 
608
                                 % 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:
676
690
                    continue
677
691
                sub_merge = Merger(sub_tree.branch, this_tree=sub_tree)
678
692
                sub_merge.merge_type = self.merge_type
679
 
                other_branch = self.other_branch.reference_parent(file_id, relpath)
 
693
                other_branch = self.other_branch.reference_parent(file_id,
 
694
                                                                  relpath)
680
695
                sub_merge.set_other_revision(other_revision, other_branch)
681
696
                base_revision = self.base_tree.get_reference_revision(file_id)
682
697
                sub_merge.base_tree = \
686
701
        return merge
687
702
 
688
703
    def do_merge(self):
689
 
        operation = OperationWithCleanups(self._do_merge_to)
 
704
        operation = cleanup.OperationWithCleanups(self._do_merge_to)
690
705
        self.this_tree.lock_tree_write()
691
706
        operation.add_cleanup(self.this_tree.unlock)
692
707
        if self.base_tree is not None:
798
813
            warnings.warn("pb argument to Merge3Merger is deprecated")
799
814
 
800
815
    def do_merge(self):
801
 
        operation = OperationWithCleanups(self._do_merge)
 
816
        operation = cleanup.OperationWithCleanups(self._do_merge)
802
817
        self.this_tree.lock_tree_write()
803
818
        operation.add_cleanup(self.this_tree.unlock)
804
819
        self.base_tree.lock_read()
819
834
            pass
820
835
 
821
836
    def make_preview_transform(self):
822
 
        operation = OperationWithCleanups(self._make_preview_transform)
 
837
        operation = cleanup.OperationWithCleanups(self._make_preview_transform)
823
838
        self.base_tree.lock_read()
824
839
        operation.add_cleanup(self.base_tree.unlock)
825
840
        self.other_tree.lock_read()
855
870
                    executable3, file_status, resolver=resolver)
856
871
        finally:
857
872
            child_pb.finished()
858
 
        self.fix_root()
 
873
        self.tt.fixup_new_roots()
 
874
        self._finish_computing_transform()
 
875
 
 
876
    def _finish_computing_transform(self):
 
877
        """Finalize the transform and report the changes.
 
878
 
 
879
        This is the second half of _compute_transform.
 
880
        """
859
881
        child_pb = ui.ui_factory.nested_progress_bar()
860
882
        try:
861
883
            fs_conflicts = transform.resolve_conflicts(self.tt, child_pb,
868
890
                self.tt.iter_changes(), self.change_reporter)
869
891
        self.cook_conflicts(fs_conflicts)
870
892
        for conflict in self.cooked_conflicts:
871
 
            trace.warning(conflict)
 
893
            trace.warning(unicode(conflict))
872
894
 
873
895
    def _entries3(self):
874
896
        """Gather data about files modified between three trees.
881
903
        """
882
904
        result = []
883
905
        iterator = self.other_tree.iter_changes(self.base_tree,
884
 
                include_unchanged=True, specific_files=self.interesting_files,
 
906
                specific_files=self.interesting_files,
885
907
                extra_trees=[self.this_tree])
886
908
        this_entries = dict((e.file_id, e) for p, e in
887
909
                            self.this_tree.iter_entries_by_dir(
913
935
        it then compares with THIS and BASE.
914
936
 
915
937
        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)
 
938
 
 
939
        :return: [(file_id, changed, parents, names, executable)], where:
 
940
 
 
941
            * file_id: Simple file_id of the entry
 
942
            * changed: Boolean, True if the kind or contents changed else False
 
943
            * parents: ((base, [parent_id, in, lcas]), parent_id_other,
 
944
                        parent_id_this)
 
945
            * names:   ((base, [name, in, lcas]), name_in_other, name_in_this)
 
946
            * executable: ((base, [exec, in, lcas]), exec_in_other,
 
947
                        exec_in_this)
924
948
        """
925
949
        if self.interesting_files is not None:
926
950
            lookup_trees = [self.this_tree, self.base_tree]
968
992
                else:
969
993
                    lca_entries.append(lca_ie)
970
994
 
971
 
            if file_id in base_inventory:
 
995
            if base_inventory.has_id(file_id):
972
996
                base_ie = base_inventory[file_id]
973
997
            else:
974
998
                base_ie = _none_entry
975
999
 
976
 
            if file_id in this_inventory:
 
1000
            if this_inventory.has_id(file_id):
977
1001
                this_ie = this_inventory[file_id]
978
1002
            else:
979
1003
                this_ie = _none_entry
1071
1095
                          ))
1072
1096
        return result
1073
1097
 
1074
 
 
 
1098
    @deprecated_method(deprecated_in((2, 4, 0)))
1075
1099
    def fix_root(self):
1076
 
        try:
1077
 
            self.tt.final_kind(self.tt.root)
1078
 
        except errors.NoSuchFile:
 
1100
        if self.tt.final_kind(self.tt.root) is None:
1079
1101
            self.tt.cancel_deletion(self.tt.root)
1080
1102
        if self.tt.final_file_id(self.tt.root) is None:
1081
1103
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
1086
1108
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1087
1109
        if other_root == self.tt.root:
1088
1110
            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)
 
1111
        if self.this_tree.inventory.has_id(
 
1112
            self.other_tree.inventory.root.file_id):
 
1113
            # the other tree's root is a non-root in the current tree (as
 
1114
            # when a previously unrelated branch is merged into another)
1092
1115
            return
1093
 
        try:
1094
 
            self.tt.final_kind(other_root)
 
1116
        if self.tt.final_kind(other_root) is not None:
1095
1117
            other_root_is_present = True
1096
 
        except errors.NoSuchFile:
 
1118
        else:
1097
1119
            # other_root doesn't have a physical representation. We still need
1098
1120
            # to move any references to the actual root of the tree.
1099
1121
            other_root_is_present = False
1100
1122
        # 'other_tree.inventory.root' is not present in this tree. We are
1101
1123
        # calling adjust_path for children which *want* to be present with a
1102
1124
        # correct place to go.
1103
 
        for thing, child in self.other_tree.inventory.root.children.iteritems():
 
1125
        for _, child in self.other_tree.inventory.root.children.iteritems():
1104
1126
            trans_id = self.tt.trans_id_file_id(child.file_id)
1105
1127
            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)
 
1128
                if self.tt.final_kind(trans_id) is not None:
1110
1129
                    # The item exist in the final tree and has a defined place
1111
1130
                    # to go already.
1112
1131
                    continue
1113
 
                except errors.NoSuchFile, e:
1114
 
                    pass
1115
1132
            # Move the item into the root
1116
 
            self.tt.adjust_path(self.tt.final_name(trans_id),
1117
 
                                self.tt.root, trans_id)
 
1133
            try:
 
1134
                final_name = self.tt.final_name(trans_id)
 
1135
            except errors.NoFinalPath:
 
1136
                # This file is not present anymore, ignore it.
 
1137
                continue
 
1138
            self.tt.adjust_path(final_name, self.tt.root, trans_id)
1118
1139
        if other_root_is_present:
1119
1140
            self.tt.cancel_creation(other_root)
1120
1141
            self.tt.cancel_versioning(other_root)
1148
1169
    @staticmethod
1149
1170
    def contents_sha1(tree, file_id):
1150
1171
        """Determine the sha1 of the file contents (used as a key method)."""
1151
 
        if file_id not in tree:
 
1172
        if not tree.has_id(file_id):
1152
1173
            return None
1153
1174
        return tree.get_file_sha1(file_id)
1154
1175
 
1299
1320
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1300
1321
                                        this_parent, this_name,
1301
1322
                                        other_parent, other_name))
1302
 
        if other_name is None:
 
1323
        if not self.other_tree.has_id(file_id):
1303
1324
            # it doesn't matter whether the result was 'other' or
1304
 
            # 'conflict'-- if there's no 'other', we leave it alone.
 
1325
            # 'conflict'-- if it has no file id, we leave it alone.
1305
1326
            return
1306
1327
        parent_id = parents[self.winner_idx[parent_id_winner]]
1307
 
        if parent_id is not None:
 
1328
        name = names[self.winner_idx[name_winner]]
 
1329
        if parent_id is not None or name is not None:
1308
1330
            # if we get here, name_winner and parent_winner are set to safe
1309
1331
            # values.
1310
 
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1311
 
                                self.tt.trans_id_file_id(parent_id),
 
1332
            if parent_id is None and name is not None:
 
1333
                # if parent_id is None and name is non-None, current file is
 
1334
                # the tree root.
 
1335
                if names[self.winner_idx[parent_id_winner]] != '':
 
1336
                    raise AssertionError(
 
1337
                        'File looks like a root, but named %s' %
 
1338
                        names[self.winner_idx[parent_id_winner]])
 
1339
                parent_trans_id = transform.ROOT_PARENT
 
1340
            else:
 
1341
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1342
            self.tt.adjust_path(name, parent_trans_id,
1312
1343
                                self.tt.trans_id_file_id(file_id))
1313
1344
 
1314
1345
    def _do_merge_contents(self, file_id):
1315
1346
        """Performs a merge on file_id contents."""
1316
1347
        def contents_pair(tree):
1317
 
            if file_id not in tree:
 
1348
            if not tree.has_id(file_id):
1318
1349
                return (None, None)
1319
1350
            kind = tree.kind(file_id)
1320
1351
            if kind == "file":
1358
1389
            if hook_status != 'not_applicable':
1359
1390
                # Don't try any more hooks, this one applies.
1360
1391
                break
 
1392
        # If the merge ends up replacing the content of the file, we get rid of
 
1393
        # it at the end of this method (this variable is used to track the
 
1394
        # exceptions to this rule).
 
1395
        keep_this = False
1361
1396
        result = "modified"
1362
1397
        if hook_status == 'not_applicable':
1363
 
            # This is a contents conflict, because none of the available
1364
 
            # functions could merge it.
 
1398
            # No merge hook was able to resolve the situation. Two cases exist:
 
1399
            # a content conflict or a duplicate one.
1365
1400
            result = None
1366
1401
            name = self.tt.final_name(trans_id)
1367
1402
            parent_id = self.tt.final_parent(trans_id)
1368
 
            if self.this_tree.has_id(file_id):
1369
 
                self.tt.unversion_file(trans_id)
1370
 
            file_group = self._dump_conflicts(name, parent_id, file_id,
1371
 
                                              set_version=True)
1372
 
            self._raw_conflicts.append(('contents conflict', file_group))
 
1403
            duplicate = False
 
1404
            inhibit_content_conflict = False
 
1405
            if params.this_kind is None: # file_id is not in THIS
 
1406
                # Is the name used for a different file_id ?
 
1407
                dupe_path = self.other_tree.id2path(file_id)
 
1408
                this_id = self.this_tree.path2id(dupe_path)
 
1409
                if this_id is not None:
 
1410
                    # Two entries for the same path
 
1411
                    keep_this = True
 
1412
                    # versioning the merged file will trigger a duplicate
 
1413
                    # conflict
 
1414
                    self.tt.version_file(file_id, trans_id)
 
1415
                    transform.create_from_tree(
 
1416
                        self.tt, trans_id, self.other_tree, file_id,
 
1417
                        filter_tree_path=self._get_filter_tree_path(file_id))
 
1418
                    inhibit_content_conflict = True
 
1419
            elif params.other_kind is None: # file_id is not in OTHER
 
1420
                # Is the name used for a different file_id ?
 
1421
                dupe_path = self.this_tree.id2path(file_id)
 
1422
                other_id = self.other_tree.path2id(dupe_path)
 
1423
                if other_id is not None:
 
1424
                    # Two entries for the same path again, but here, the other
 
1425
                    # entry will also be merged.  We simply inhibit the
 
1426
                    # 'content' conflict creation because we know OTHER will
 
1427
                    # create (or has already created depending on ordering) an
 
1428
                    # entry at the same path. This will trigger a 'duplicate'
 
1429
                    # conflict later.
 
1430
                    keep_this = True
 
1431
                    inhibit_content_conflict = True
 
1432
            if not inhibit_content_conflict:
 
1433
                if params.this_kind is not None:
 
1434
                    self.tt.unversion_file(trans_id)
 
1435
                # This is a contents conflict, because none of the available
 
1436
                # functions could merge it.
 
1437
                file_group = self._dump_conflicts(name, parent_id, file_id,
 
1438
                                                  set_version=True)
 
1439
                self._raw_conflicts.append(('contents conflict', file_group))
1373
1440
        elif hook_status == 'success':
1374
1441
            self.tt.create_file(lines, trans_id)
1375
1442
        elif hook_status == 'conflicted':
1391
1458
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
1392
1459
        if not self.this_tree.has_id(file_id) and result == "modified":
1393
1460
            self.tt.version_file(file_id, trans_id)
1394
 
        # The merge has been performed, so the old contents should not be
1395
 
        # retained.
1396
 
        try:
 
1461
        if not keep_this:
 
1462
            # The merge has been performed and produced a new content, so the
 
1463
            # old contents should not be retained.
1397
1464
            self.tt.delete_contents(trans_id)
1398
 
        except errors.NoSuchFile:
1399
 
            pass
1400
1465
        return result
1401
1466
 
1402
1467
    def _default_other_winner_merge(self, merge_hook_params):
1403
1468
        """Replace this contents with other."""
1404
1469
        file_id = merge_hook_params.file_id
1405
1470
        trans_id = merge_hook_params.trans_id
1406
 
        file_in_this = self.this_tree.has_id(file_id)
1407
1471
        if self.other_tree.has_id(file_id):
1408
1472
            # OTHER changed the file
1409
 
            wt = self.this_tree
1410
 
            if wt.supports_content_filtering():
1411
 
                # We get the path from the working tree if it exists.
1412
 
                # That fails though when OTHER is adding a file, so
1413
 
                # we fall back to the other tree to find the path if
1414
 
                # it doesn't exist locally.
1415
 
                try:
1416
 
                    filter_tree_path = wt.id2path(file_id)
1417
 
                except errors.NoSuchId:
1418
 
                    filter_tree_path = self.other_tree.id2path(file_id)
1419
 
            else:
1420
 
                # Skip the id2path lookup for older formats
1421
 
                filter_tree_path = None
1422
 
            transform.create_from_tree(self.tt, trans_id,
1423
 
                             self.other_tree, file_id,
1424
 
                             filter_tree_path=filter_tree_path)
 
1473
            transform.create_from_tree(
 
1474
                self.tt, trans_id, self.other_tree, file_id,
 
1475
                filter_tree_path=self._get_filter_tree_path(file_id))
1425
1476
            return 'done', None
1426
 
        elif file_in_this:
 
1477
        elif self.this_tree.has_id(file_id):
1427
1478
            # OTHER deleted the file
1428
1479
            return 'delete', None
1429
1480
        else:
1455
1506
    def get_lines(self, tree, file_id):
1456
1507
        """Return the lines in a file, or an empty list."""
1457
1508
        if tree.has_id(file_id):
1458
 
            return tree.get_file(file_id).readlines()
 
1509
            return tree.get_file_lines(file_id)
1459
1510
        else:
1460
1511
            return []
1461
1512
 
1503
1554
                                              other_lines)
1504
1555
            file_group.append(trans_id)
1505
1556
 
 
1557
 
 
1558
    def _get_filter_tree_path(self, file_id):
 
1559
        if self.this_tree.supports_content_filtering():
 
1560
            # We get the path from the working tree if it exists.
 
1561
            # That fails though when OTHER is adding a file, so
 
1562
            # we fall back to the other tree to find the path if
 
1563
            # it doesn't exist locally.
 
1564
            try:
 
1565
                return self.this_tree.id2path(file_id)
 
1566
            except errors.NoSuchId:
 
1567
                return self.other_tree.id2path(file_id)
 
1568
        # Skip the id2path lookup for older formats
 
1569
        return None
 
1570
 
1506
1571
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1507
1572
                        base_lines=None, other_lines=None, set_version=False,
1508
1573
                        no_base=False):
1574
1639
        if winner == 'this' and file_status != "modified":
1575
1640
            return
1576
1641
        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:
 
1642
        if self.tt.final_kind(trans_id) != "file":
1581
1643
            return
1582
1644
        if winner == "this":
1583
1645
            executability = this_executable
1594
1656
 
1595
1657
    def cook_conflicts(self, fs_conflicts):
1596
1658
        """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))
 
1659
        content_conflict_file_ids = set()
 
1660
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
1599
1661
        fp = transform.FinalPaths(self.tt)
1600
1662
        for conflict in self._raw_conflicts:
1601
1663
            conflict_type = conflict[0]
1612
1674
                if other_parent is None or other_name is None:
1613
1675
                    other_path = '<deleted>'
1614
1676
                else:
1615
 
                    parent_path =  fp.get_path(
1616
 
                        self.tt.trans_id_file_id(other_parent))
 
1677
                    if other_parent == self.other_tree.get_root_id():
 
1678
                        # The tree transform doesn't know about the other root,
 
1679
                        # so we special case here to avoid a NoFinalPath
 
1680
                        # exception
 
1681
                        parent_path = ''
 
1682
                    else:
 
1683
                        parent_path =  fp.get_path(
 
1684
                            self.tt.trans_id_file_id(other_parent))
1617
1685
                    other_path = osutils.pathjoin(parent_path, other_name)
1618
1686
                c = _mod_conflicts.Conflict.factory(
1619
1687
                    'path conflict', path=this_path,
1623
1691
                for trans_id in conflict[1]:
1624
1692
                    file_id = self.tt.final_file_id(trans_id)
1625
1693
                    if file_id is not None:
 
1694
                        # Ok we found the relevant file-id
1626
1695
                        break
1627
1696
                path = fp.get_path(trans_id)
1628
1697
                for suffix in ('.BASE', '.THIS', '.OTHER'):
1629
1698
                    if path.endswith(suffix):
 
1699
                        # Here is the raw path
1630
1700
                        path = path[:-len(suffix)]
1631
1701
                        break
1632
1702
                c = _mod_conflicts.Conflict.factory(conflict_type,
1633
1703
                                                    path=path, file_id=file_id)
 
1704
                content_conflict_file_ids.add(file_id)
1634
1705
            elif conflict_type == 'text conflict':
1635
1706
                trans_id = conflict[1]
1636
1707
                path = fp.get_path(trans_id)
1639
1710
                                                    path=path, file_id=file_id)
1640
1711
            else:
1641
1712
                raise AssertionError('bad conflict type: %r' % (conflict,))
 
1713
            cooked_conflicts.append(c)
 
1714
 
 
1715
        self.cooked_conflicts = []
 
1716
        # We want to get rid of path conflicts when a corresponding contents
 
1717
        # conflict exists. This can occur when one branch deletes a file while
 
1718
        # the other renames *and* modifies it. In this case, the content
 
1719
        # conflict is enough.
 
1720
        for c in cooked_conflicts:
 
1721
            if (c.typestring == 'path conflict'
 
1722
                and c.file_id in content_conflict_file_ids):
 
1723
                continue
1642
1724
            self.cooked_conflicts.append(c)
1643
1725
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1644
1726
 
1750
1832
            osutils.rmtree(temp_dir)
1751
1833
 
1752
1834
 
 
1835
class PathNotInTree(errors.BzrError):
 
1836
 
 
1837
    _fmt = """Merge-into failed because %(tree)s does not contain %(path)s."""
 
1838
 
 
1839
    def __init__(self, path, tree):
 
1840
        errors.BzrError.__init__(self, path=path, tree=tree)
 
1841
 
 
1842
 
 
1843
class MergeIntoMerger(Merger):
 
1844
    """Merger that understands other_tree will be merged into a subdir.
 
1845
 
 
1846
    This also changes the Merger api so that it uses real Branch, revision_id,
 
1847
    and RevisonTree objects, rather than using revision specs.
 
1848
    """
 
1849
 
 
1850
    def __init__(self, this_tree, other_branch, other_tree, target_subdir,
 
1851
            source_subpath, other_rev_id=None):
 
1852
        """Create a new MergeIntoMerger object.
 
1853
 
 
1854
        source_subpath in other_tree will be effectively copied to
 
1855
        target_subdir in this_tree.
 
1856
 
 
1857
        :param this_tree: The tree that we will be merging into.
 
1858
        :param other_branch: The Branch we will be merging from.
 
1859
        :param other_tree: The RevisionTree object we want to merge.
 
1860
        :param target_subdir: The relative path where we want to merge
 
1861
            other_tree into this_tree
 
1862
        :param source_subpath: The relative path specifying the subtree of
 
1863
            other_tree to merge into this_tree.
 
1864
        """
 
1865
        # It is assumed that we are merging a tree that is not in our current
 
1866
        # ancestry, which means we are using the "EmptyTree" as our basis.
 
1867
        null_ancestor_tree = this_tree.branch.repository.revision_tree(
 
1868
                                _mod_revision.NULL_REVISION)
 
1869
        super(MergeIntoMerger, self).__init__(
 
1870
            this_branch=this_tree.branch,
 
1871
            this_tree=this_tree,
 
1872
            other_tree=other_tree,
 
1873
            base_tree=null_ancestor_tree,
 
1874
            )
 
1875
        self._target_subdir = target_subdir
 
1876
        self._source_subpath = source_subpath
 
1877
        self.other_branch = other_branch
 
1878
        if other_rev_id is None:
 
1879
            other_rev_id = other_tree.get_revision_id()
 
1880
        self.other_rev_id = self.other_basis = other_rev_id
 
1881
        self.base_is_ancestor = True
 
1882
        self.backup_files = True
 
1883
        self.merge_type = Merge3Merger
 
1884
        self.show_base = False
 
1885
        self.reprocess = False
 
1886
        self.interesting_ids = None
 
1887
        self.merge_type = _MergeTypeParameterizer(MergeIntoMergeType,
 
1888
              target_subdir=self._target_subdir,
 
1889
              source_subpath=self._source_subpath)
 
1890
        if self._source_subpath != '':
 
1891
            # If this isn't a partial merge make sure the revisions will be
 
1892
            # present.
 
1893
            self._maybe_fetch(self.other_branch, self.this_branch,
 
1894
                self.other_basis)
 
1895
 
 
1896
    def set_pending(self):
 
1897
        if self._source_subpath != '':
 
1898
            return
 
1899
        Merger.set_pending(self)
 
1900
 
 
1901
 
 
1902
class _MergeTypeParameterizer(object):
 
1903
    """Wrap a merge-type class to provide extra parameters.
 
1904
    
 
1905
    This is hack used by MergeIntoMerger to pass some extra parameters to its
 
1906
    merge_type.  Merger.do_merge() sets up its own set of parameters to pass to
 
1907
    the 'merge_type' member.  It is difficult override do_merge without
 
1908
    re-writing the whole thing, so instead we create a wrapper which will pass
 
1909
    the extra parameters.
 
1910
    """
 
1911
 
 
1912
    def __init__(self, merge_type, **kwargs):
 
1913
        self._extra_kwargs = kwargs
 
1914
        self._merge_type = merge_type
 
1915
 
 
1916
    def __call__(self, *args, **kwargs):
 
1917
        kwargs.update(self._extra_kwargs)
 
1918
        return self._merge_type(*args, **kwargs)
 
1919
 
 
1920
    def __getattr__(self, name):
 
1921
        return getattr(self._merge_type, name)
 
1922
 
 
1923
 
 
1924
class MergeIntoMergeType(Merge3Merger):
 
1925
    """Merger that incorporates a tree (or part of a tree) into another."""
 
1926
 
 
1927
    def __init__(self, *args, **kwargs):
 
1928
        """Initialize the merger object.
 
1929
 
 
1930
        :param args: See Merge3Merger.__init__'s args.
 
1931
        :param kwargs: See Merge3Merger.__init__'s keyword args, except for
 
1932
            source_subpath and target_subdir.
 
1933
        :keyword source_subpath: The relative path specifying the subtree of
 
1934
            other_tree to merge into this_tree.
 
1935
        :keyword target_subdir: The relative path where we want to merge
 
1936
            other_tree into this_tree
 
1937
        """
 
1938
        # All of the interesting work happens during Merge3Merger.__init__(),
 
1939
        # so we have have to hack in to get our extra parameters set.
 
1940
        self._source_subpath = kwargs.pop('source_subpath')
 
1941
        self._target_subdir = kwargs.pop('target_subdir')
 
1942
        super(MergeIntoMergeType, self).__init__(*args, **kwargs)
 
1943
 
 
1944
    def _compute_transform(self):
 
1945
        child_pb = ui.ui_factory.nested_progress_bar()
 
1946
        try:
 
1947
            entries = self._entries_to_incorporate()
 
1948
            entries = list(entries)
 
1949
            for num, (entry, parent_id) in enumerate(entries):
 
1950
                child_pb.update('Preparing file merge', num, len(entries))
 
1951
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1952
                trans_id = transform.new_by_entry(self.tt, entry,
 
1953
                    parent_trans_id, self.other_tree)
 
1954
        finally:
 
1955
            child_pb.finished()
 
1956
        self._finish_computing_transform()
 
1957
 
 
1958
    def _entries_to_incorporate(self):
 
1959
        """Yields pairs of (inventory_entry, new_parent)."""
 
1960
        other_inv = self.other_tree.inventory
 
1961
        subdir_id = other_inv.path2id(self._source_subpath)
 
1962
        if subdir_id is None:
 
1963
            # XXX: The error would be clearer if it gave the URL of the source
 
1964
            # branch, but we don't have a reference to that here.
 
1965
            raise PathNotInTree(self._source_subpath, "Source tree")
 
1966
        subdir = other_inv[subdir_id]
 
1967
        parent_in_target = osutils.dirname(self._target_subdir)
 
1968
        target_id = self.this_tree.inventory.path2id(parent_in_target)
 
1969
        if target_id is None:
 
1970
            raise PathNotInTree(self._target_subdir, "Target tree")
 
1971
        name_in_target = osutils.basename(self._target_subdir)
 
1972
        merge_into_root = subdir.copy()
 
1973
        merge_into_root.name = name_in_target
 
1974
        if self.this_tree.inventory.has_id(merge_into_root.file_id):
 
1975
            # Give the root a new file-id.
 
1976
            # This can happen fairly easily if the directory we are
 
1977
            # incorporating is the root, and both trees have 'TREE_ROOT' as
 
1978
            # their root_id.  Users will expect this to Just Work, so we
 
1979
            # change the file-id here.
 
1980
            # Non-root file-ids could potentially conflict too.  That's really
 
1981
            # an edge case, so we don't do anything special for those.  We let
 
1982
            # them cause conflicts.
 
1983
            merge_into_root.file_id = generate_ids.gen_file_id(name_in_target)
 
1984
        yield (merge_into_root, target_id)
 
1985
        if subdir.kind != 'directory':
 
1986
            # No children, so we are done.
 
1987
            return
 
1988
        for ignored_path, entry in other_inv.iter_entries_by_dir(subdir_id):
 
1989
            parent_id = entry.parent_id
 
1990
            if parent_id == subdir.file_id:
 
1991
                # The root's parent ID has changed, so make sure children of
 
1992
                # the root refer to the new ID.
 
1993
                parent_id = merge_into_root.file_id
 
1994
            yield (entry, parent_id)
 
1995
 
 
1996
 
1753
1997
def merge_inner(this_branch, other_tree, base_tree, ignore_zero=False,
1754
1998
                backup_files=False,
1755
1999
                merge_type=Merge3Merger,
1763
2007
                change_reporter=None):
1764
2008
    """Primary interface for merging.
1765
2009
 
1766
 
        typical use is probably
1767
 
        'merge_inner(branch, branch.get_revision_tree(other_revision),
1768
 
                     branch.get_revision_tree(base_revision))'
1769
 
        """
 
2010
    Typical use is probably::
 
2011
 
 
2012
        merge_inner(branch, branch.get_revision_tree(other_revision),
 
2013
                    branch.get_revision_tree(base_revision))
 
2014
    """
1770
2015
    if this_tree is None:
1771
2016
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1772
 
                              "parameter as of bzrlib version 0.8.")
 
2017
                              "parameter")
1773
2018
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1774
2019
                    pb=pb, change_reporter=change_reporter)
1775
2020
    merger.backup_files = backup_files
2229
2474
class _PlanLCAMerge(_PlanMergeBase):
2230
2475
    """
2231
2476
    This merge algorithm differs from _PlanMerge in that:
 
2477
 
2232
2478
    1. comparisons are done against LCAs only
2233
2479
    2. cases where a contested line is new versus one LCA but old versus
2234
2480
       another are marked as conflicts, by emitting the line as conflicted-a
2275
2521
 
2276
2522
        If a line is killed and new, this indicates that the two merge
2277
2523
        revisions contain differing conflict resolutions.
 
2524
 
2278
2525
        :param revision_id: The id of the revision in which the lines are
2279
2526
            unique
2280
2527
        :param unique_line_numbers: The line numbers of unique lines.
2281
 
        :return a tuple of (new_this, killed_other):
 
2528
        :return: a tuple of (new_this, killed_other)
2282
2529
        """
2283
2530
        new = set()
2284
2531
        killed = set()