~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Martin Pool
  • Date: 2010-08-18 07:25:22 UTC
  • mto: This revision was merged to the branch mainline in revision 5383.
  • Revision ID: mbp@sourcefrog.net-20100818072522-uk3gsazoia3l3s0a
Start adding 'what's new in 2.3'

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
20
20
lazy_import(globals(), """
21
21
from bzrlib import (
22
22
    branch as _mod_branch,
23
 
    cleanup,
24
23
    conflicts as _mod_conflicts,
25
24
    debug,
26
25
    generate_ids,
38
37
    versionedfile,
39
38
    workingtree,
40
39
    )
 
40
from bzrlib.cleanup import OperationWithCleanups
41
41
""")
42
42
from bzrlib import (
43
43
    decorators,
53
53
 
54
54
def transform_tree(from_tree, to_tree, interesting_ids=None):
55
55
    from_tree.lock_tree_write()
56
 
    operation = cleanup.OperationWithCleanups(merge_inner)
 
56
    operation = OperationWithCleanups(merge_inner)
57
57
    operation.add_cleanup(from_tree.unlock)
58
58
    operation.run_simple(from_tree.branch, to_tree, from_tree,
59
59
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
62
62
class MergeHooks(hooks.Hooks):
63
63
 
64
64
    def __init__(self):
65
 
        hooks.Hooks.__init__(self, "bzrlib.merge", "Merger.hooks")
66
 
        self.add_hook('merge_file_content',
 
65
        hooks.Hooks.__init__(self)
 
66
        self.create_hook(hooks.HookPoint('merge_file_content',
67
67
            "Called with a bzrlib.merge.Merger object to create a per file "
68
68
            "merge object when starting a merge. "
69
69
            "Should return either None or a subclass of "
73
73
            "side has deleted the file and the other has changed it). "
74
74
            "See the AbstractPerFileMerger API docs for details on how it is "
75
75
            "used by merge.",
76
 
            (2, 1))
 
76
            (2, 1), None))
77
77
 
78
78
 
79
79
class AbstractPerFileMerger(object):
92
92
        """Attempt to merge the contents of a single file.
93
93
        
94
94
        :param merge_params: A bzrlib.merge.MergeHookParams
95
 
        :return: A tuple of (status, chunks), where status is one of
 
95
        :return : A tuple of (status, chunks), where status is one of
96
96
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
97
97
            is 'success' or 'conflicted', then chunks should be an iterable of
98
98
            strings for the new file contents.
458
458
    @deprecated_method(deprecated_in((2, 1, 0)))
459
459
    def file_revisions(self, file_id):
460
460
        self.ensure_revision_trees()
 
461
        def get_id(tree, file_id):
 
462
            revision_id = tree.inventory[file_id].revision
 
463
            return revision_id
461
464
        if self.this_rev_id is None:
462
465
            if self.this_basis_tree.get_file_sha1(file_id) != \
463
466
                self.this_tree.get_file_sha1(file_id):
464
467
                raise errors.WorkingTreeNotRevision(self.this_tree)
465
468
 
466
469
        trees = (self.this_basis_tree, self.other_tree)
467
 
        return [tree.get_file_revision(file_id) for tree in trees]
 
470
        return [get_id(tree, file_id) for tree in trees]
468
471
 
469
472
    @deprecated_method(deprecated_in((2, 1, 0)))
470
473
    def check_basis(self, check_clean, require_commits=True):
498
501
    def _add_parent(self):
499
502
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
500
503
        new_parent_trees = []
501
 
        operation = cleanup.OperationWithCleanups(
502
 
            self.this_tree.set_parent_trees)
 
504
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
503
505
        for revision_id in new_parents:
504
506
            try:
505
507
                tree = self.revision_tree(revision_id)
580
582
            elif len(lcas) == 1:
581
583
                self.base_rev_id = list(lcas)[0]
582
584
            else: # len(lcas) > 1
583
 
                self._is_criss_cross = True
584
585
                if len(lcas) > 2:
585
586
                    # find_unique_lca can only handle 2 nodes, so we have to
586
587
                    # start back at the beginning. It is a shame to traverse
591
592
                else:
592
593
                    self.base_rev_id = self.revision_graph.find_unique_lca(
593
594
                                            *lcas)
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
 
                
 
595
                self._is_criss_cross = True
599
596
            if self.base_rev_id == _mod_revision.NULL_REVISION:
600
597
                raise errors.UnrelatedBranches()
601
598
            if self._is_criss_cross:
602
599
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
603
600
                              ' help criss-cross.')
604
601
                trace.mutter('Criss-cross lcas: %r' % lcas)
605
 
                if self.base_rev_id in lcas:
606
 
                    trace.mutter('Unable to find unique lca. '
607
 
                                 'Fallback %r as best option.' % self.base_rev_id)
608
 
                interesting_revision_ids = set(lcas)
609
 
                interesting_revision_ids.add(self.base_rev_id)
 
602
                interesting_revision_ids = [self.base_rev_id]
 
603
                interesting_revision_ids.extend(lcas)
610
604
                interesting_trees = dict((t.get_revision_id(), t)
611
605
                    for t in self.this_branch.repository.revision_trees(
612
606
                        interesting_revision_ids))
613
607
                self._cached_trees.update(interesting_trees)
614
 
                if self.base_rev_id in lcas:
615
 
                    self.base_tree = interesting_trees[self.base_rev_id]
616
 
                else:
617
 
                    self.base_tree = interesting_trees.pop(self.base_rev_id)
 
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)
618
611
                self._lca_trees = [interesting_trees[key]
619
612
                                   for key in sorted_lca_keys]
620
613
            else:
699
692
        return merge
700
693
 
701
694
    def do_merge(self):
702
 
        operation = cleanup.OperationWithCleanups(self._do_merge_to)
 
695
        operation = OperationWithCleanups(self._do_merge_to)
703
696
        self.this_tree.lock_tree_write()
704
697
        operation.add_cleanup(self.this_tree.unlock)
705
698
        if self.base_tree is not None:
811
804
            warnings.warn("pb argument to Merge3Merger is deprecated")
812
805
 
813
806
    def do_merge(self):
814
 
        operation = cleanup.OperationWithCleanups(self._do_merge)
 
807
        operation = OperationWithCleanups(self._do_merge)
815
808
        self.this_tree.lock_tree_write()
816
809
        operation.add_cleanup(self.this_tree.unlock)
817
810
        self.base_tree.lock_read()
832
825
            pass
833
826
 
834
827
    def make_preview_transform(self):
835
 
        operation = cleanup.OperationWithCleanups(self._make_preview_transform)
 
828
        operation = OperationWithCleanups(self._make_preview_transform)
836
829
        self.base_tree.lock_read()
837
830
        operation.add_cleanup(self.base_tree.unlock)
838
831
        self.other_tree.lock_read()
868
861
                    executable3, file_status, resolver=resolver)
869
862
        finally:
870
863
            child_pb.finished()
871
 
        self.tt.fixup_new_roots()
 
864
        self.fix_root()
872
865
        self._finish_computing_transform()
873
866
 
874
867
    def _finish_computing_transform(self):
888
881
                self.tt.iter_changes(), self.change_reporter)
889
882
        self.cook_conflicts(fs_conflicts)
890
883
        for conflict in self.cooked_conflicts:
891
 
            trace.warning(unicode(conflict))
 
884
            trace.warning(conflict)
892
885
 
893
886
    def _entries3(self):
894
887
        """Gather data about files modified between three trees.
901
894
        """
902
895
        result = []
903
896
        iterator = self.other_tree.iter_changes(self.base_tree,
904
 
                specific_files=self.interesting_files,
 
897
                include_unchanged=True, specific_files=self.interesting_files,
905
898
                extra_trees=[self.this_tree])
906
899
        this_entries = dict((e.file_id, e) for p, e in
907
900
                            self.this_tree.iter_entries_by_dir(
933
926
        it then compares with THIS and BASE.
934
927
 
935
928
        For the multi-valued entries, the format will be (BASE, [lca1, lca2])
936
 
 
937
 
        :return: [(file_id, changed, parents, names, executable)], where:
938
 
 
939
 
            * file_id: Simple file_id of the entry
940
 
            * changed: Boolean, True if the kind or contents changed else False
941
 
            * parents: ((base, [parent_id, in, lcas]), parent_id_other,
942
 
                        parent_id_this)
943
 
            * names:   ((base, [name, in, lcas]), name_in_other, name_in_this)
944
 
            * executable: ((base, [exec, in, lcas]), exec_in_other,
945
 
                        exec_in_this)
 
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)
946
937
        """
947
938
        if self.interesting_files is not None:
948
939
            lookup_trees = [self.this_tree, self.base_tree]
990
981
                else:
991
982
                    lca_entries.append(lca_ie)
992
983
 
993
 
            if base_inventory.has_id(file_id):
 
984
            if file_id in base_inventory:
994
985
                base_ie = base_inventory[file_id]
995
986
            else:
996
987
                base_ie = _none_entry
997
988
 
998
 
            if this_inventory.has_id(file_id):
 
989
            if file_id in this_inventory:
999
990
                this_ie = this_inventory[file_id]
1000
991
            else:
1001
992
                this_ie = _none_entry
1093
1084
                          ))
1094
1085
        return result
1095
1086
 
1096
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1097
1087
    def fix_root(self):
1098
 
        if self.tt.final_kind(self.tt.root) is None:
 
1088
        try:
 
1089
            self.tt.final_kind(self.tt.root)
 
1090
        except errors.NoSuchFile:
1099
1091
            self.tt.cancel_deletion(self.tt.root)
1100
1092
        if self.tt.final_file_id(self.tt.root) is None:
1101
1093
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
1106
1098
        other_root = self.tt.trans_id_file_id(other_root_file_id)
1107
1099
        if other_root == self.tt.root:
1108
1100
            return
1109
 
        if self.this_tree.inventory.has_id(
1110
 
            self.other_tree.inventory.root.file_id):
1111
 
            # the other tree's root is a non-root in the current tree (as
1112
 
            # when a previously unrelated branch is merged into another)
 
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)
1113
1104
            return
1114
 
        if self.tt.final_kind(other_root) is not None:
 
1105
        try:
 
1106
            self.tt.final_kind(other_root)
1115
1107
            other_root_is_present = True
1116
 
        else:
 
1108
        except errors.NoSuchFile:
1117
1109
            # other_root doesn't have a physical representation. We still need
1118
1110
            # to move any references to the actual root of the tree.
1119
1111
            other_root_is_present = False
1120
1112
        # 'other_tree.inventory.root' is not present in this tree. We are
1121
1113
        # calling adjust_path for children which *want* to be present with a
1122
1114
        # correct place to go.
1123
 
        for _, child in self.other_tree.inventory.root.children.iteritems():
 
1115
        for thing, child in self.other_tree.inventory.root.children.iteritems():
1124
1116
            trans_id = self.tt.trans_id_file_id(child.file_id)
1125
1117
            if not other_root_is_present:
1126
 
                if self.tt.final_kind(trans_id) is not None:
 
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)
1127
1122
                    # The item exist in the final tree and has a defined place
1128
1123
                    # to go already.
1129
1124
                    continue
 
1125
                except errors.NoSuchFile, e:
 
1126
                    pass
1130
1127
            # Move the item into the root
1131
 
            try:
1132
 
                final_name = self.tt.final_name(trans_id)
1133
 
            except errors.NoFinalPath:
1134
 
                # This file is not present anymore, ignore it.
1135
 
                continue
1136
 
            self.tt.adjust_path(final_name, self.tt.root, trans_id)
 
1128
            self.tt.adjust_path(self.tt.final_name(trans_id),
 
1129
                                self.tt.root, trans_id)
1137
1130
        if other_root_is_present:
1138
1131
            self.tt.cancel_creation(other_root)
1139
1132
            self.tt.cancel_versioning(other_root)
1167
1160
    @staticmethod
1168
1161
    def contents_sha1(tree, file_id):
1169
1162
        """Determine the sha1 of the file contents (used as a key method)."""
1170
 
        if not tree.has_id(file_id):
 
1163
        if file_id not in tree:
1171
1164
            return None
1172
1165
        return tree.get_file_sha1(file_id)
1173
1166
 
1318
1311
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
1319
1312
                                        this_parent, this_name,
1320
1313
                                        other_parent, other_name))
1321
 
        if not self.other_tree.has_id(file_id):
 
1314
        if other_name is None:
1322
1315
            # it doesn't matter whether the result was 'other' or
1323
 
            # 'conflict'-- if it has no file id, we leave it alone.
 
1316
            # 'conflict'-- if there's no 'other', we leave it alone.
1324
1317
            return
1325
1318
        parent_id = parents[self.winner_idx[parent_id_winner]]
1326
 
        name = names[self.winner_idx[name_winner]]
1327
 
        if parent_id is not None or name is not None:
 
1319
        if parent_id is not None:
1328
1320
            # if we get here, name_winner and parent_winner are set to safe
1329
1321
            # values.
1330
 
            if parent_id is None and name is not None:
1331
 
                # if parent_id is None and name is non-None, current file is
1332
 
                # the tree root.
1333
 
                if names[self.winner_idx[parent_id_winner]] != '':
1334
 
                    raise AssertionError(
1335
 
                        'File looks like a root, but named %s' %
1336
 
                        names[self.winner_idx[parent_id_winner]])
1337
 
                parent_trans_id = transform.ROOT_PARENT
1338
 
            else:
1339
 
                parent_trans_id = self.tt.trans_id_file_id(parent_id)
1340
 
            self.tt.adjust_path(name, parent_trans_id,
 
1322
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
 
1323
                                self.tt.trans_id_file_id(parent_id),
1341
1324
                                self.tt.trans_id_file_id(file_id))
1342
1325
 
1343
1326
    def _do_merge_contents(self, file_id):
1344
1327
        """Performs a merge on file_id contents."""
1345
1328
        def contents_pair(tree):
1346
 
            if not tree.has_id(file_id):
 
1329
            if file_id not in tree:
1347
1330
                return (None, None)
1348
1331
            kind = tree.kind(file_id)
1349
1332
            if kind == "file":
1422
1405
            self.tt.version_file(file_id, trans_id)
1423
1406
        # The merge has been performed, so the old contents should not be
1424
1407
        # retained.
1425
 
        self.tt.delete_contents(trans_id)
 
1408
        try:
 
1409
            self.tt.delete_contents(trans_id)
 
1410
        except errors.NoSuchFile:
 
1411
            pass
1426
1412
        return result
1427
1413
 
1428
1414
    def _default_other_winner_merge(self, merge_hook_params):
1600
1586
        if winner == 'this' and file_status != "modified":
1601
1587
            return
1602
1588
        trans_id = self.tt.trans_id_file_id(file_id)
1603
 
        if self.tt.final_kind(trans_id) != "file":
 
1589
        try:
 
1590
            if self.tt.final_kind(trans_id) != "file":
 
1591
                return
 
1592
        except errors.NoSuchFile:
1604
1593
            return
1605
1594
        if winner == "this":
1606
1595
            executability = this_executable
1617
1606
 
1618
1607
    def cook_conflicts(self, fs_conflicts):
1619
1608
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1620
 
        content_conflict_file_ids = set()
1621
 
        cooked_conflicts = transform.cook_conflicts(fs_conflicts, self.tt)
 
1609
        self.cooked_conflicts.extend(transform.cook_conflicts(
 
1610
                fs_conflicts, self.tt))
1622
1611
        fp = transform.FinalPaths(self.tt)
1623
1612
        for conflict in self._raw_conflicts:
1624
1613
            conflict_type = conflict[0]
1635
1624
                if other_parent is None or other_name is None:
1636
1625
                    other_path = '<deleted>'
1637
1626
                else:
1638
 
                    if other_parent == self.other_tree.get_root_id():
1639
 
                        # The tree transform doesn't know about the other root,
1640
 
                        # so we special case here to avoid a NoFinalPath
1641
 
                        # exception
1642
 
                        parent_path = ''
1643
 
                    else:
1644
 
                        parent_path =  fp.get_path(
1645
 
                            self.tt.trans_id_file_id(other_parent))
 
1627
                    parent_path =  fp.get_path(
 
1628
                        self.tt.trans_id_file_id(other_parent))
1646
1629
                    other_path = osutils.pathjoin(parent_path, other_name)
1647
1630
                c = _mod_conflicts.Conflict.factory(
1648
1631
                    'path conflict', path=this_path,
1660
1643
                        break
1661
1644
                c = _mod_conflicts.Conflict.factory(conflict_type,
1662
1645
                                                    path=path, file_id=file_id)
1663
 
                content_conflict_file_ids.add(file_id)
1664
1646
            elif conflict_type == 'text conflict':
1665
1647
                trans_id = conflict[1]
1666
1648
                path = fp.get_path(trans_id)
1669
1651
                                                    path=path, file_id=file_id)
1670
1652
            else:
1671
1653
                raise AssertionError('bad conflict type: %r' % (conflict,))
1672
 
            cooked_conflicts.append(c)
1673
 
 
1674
 
        self.cooked_conflicts = []
1675
 
        # We want to get rid of path conflicts when a corresponding contents
1676
 
        # conflict exists. This can occur when one branch deletes a file while
1677
 
        # the other renames *and* modifies it. In this case, the content
1678
 
        # conflict is enough.
1679
 
        for c in cooked_conflicts:
1680
 
            if (c.typestring == 'path conflict'
1681
 
                and c.file_id in content_conflict_file_ids):
1682
 
                continue
1683
1654
            self.cooked_conflicts.append(c)
1684
1655
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1685
1656
 
1930
1901
        name_in_target = osutils.basename(self._target_subdir)
1931
1902
        merge_into_root = subdir.copy()
1932
1903
        merge_into_root.name = name_in_target
1933
 
        if self.this_tree.inventory.has_id(merge_into_root.file_id):
 
1904
        if merge_into_root.file_id in self.this_tree.inventory:
1934
1905
            # Give the root a new file-id.
1935
1906
            # This can happen fairly easily if the directory we are
1936
1907
            # incorporating is the root, and both trees have 'TREE_ROOT' as
1973
1944
    """
1974
1945
    if this_tree is None:
1975
1946
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1976
 
                              "parameter")
 
1947
                              "parameter as of bzrlib version 0.8.")
1977
1948
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1978
1949
                    pb=pb, change_reporter=change_reporter)
1979
1950
    merger.backup_files = backup_files
2433
2404
class _PlanLCAMerge(_PlanMergeBase):
2434
2405
    """
2435
2406
    This merge algorithm differs from _PlanMerge in that:
2436
 
 
2437
2407
    1. comparisons are done against LCAs only
2438
2408
    2. cases where a contested line is new versus one LCA but old versus
2439
2409
       another are marked as conflicts, by emitting the line as conflicted-a
2480
2450
 
2481
2451
        If a line is killed and new, this indicates that the two merge
2482
2452
        revisions contain differing conflict resolutions.
2483
 
 
2484
2453
        :param revision_id: The id of the revision in which the lines are
2485
2454
            unique
2486
2455
        :param unique_line_numbers: The line numbers of unique lines.
2487
 
        :return: a tuple of (new_this, killed_other)
 
2456
        :return a tuple of (new_this, killed_other):
2488
2457
        """
2489
2458
        new = set()
2490
2459
        killed = set()