74
78
"See the AbstractPerFileMerger API docs for details on how it is "
81
self.add_hook('pre_merge',
82
'Called before a merge. '
83
'Receives a Merger object as the single argument.',
85
self.add_hook('post_merge',
86
'Called after a merge. '
87
'Receives a Merger object as the single argument. '
88
'The return value is ignored.',
79
92
class AbstractPerFileMerger(object):
91
104
def merge_contents(self, merge_params):
92
105
"""Attempt to merge the contents of a single file.
94
:param merge_params: A bzrlib.merge.MergeHookParams
107
:param merge_params: A bzrlib.merge.MergeFileHookParams
95
108
:return: A tuple of (status, chunks), where status is one of
96
109
'not_applicable', 'success', 'conflicted', or 'delete'. If status
97
110
is 'success' or 'conflicted', then chunks should be an iterable of
119
132
def get_filename(self, params, tree):
120
133
"""Lookup the filename (i.e. basename, not path), given a Tree (e.g.
121
self.merger.this_tree) and a MergeHookParams.
134
self.merger.this_tree) and a MergeFileHookParams.
123
136
return osutils.basename(tree.id2path(params.file_id))
125
138
def get_filepath(self, params, tree):
126
139
"""Calculate the path to the file in a tree.
128
:param params: A MergeHookParams describing the file to merge
141
:param params: A MergeFileHookParams describing the file to merge
129
142
:param tree: a Tree, e.g. self.merger.this_tree.
131
144
return tree.id2path(params.file_id)
138
151
params.winner == 'other' or
139
152
# THIS and OTHER aren't both files.
140
153
not params.is_file_merge() or
141
# The filename doesn't match *.xml
154
# The filename doesn't match
142
155
not self.file_matches(params)):
143
156
return 'not_applicable', None
144
157
return self.merge_matching(params)
441
454
revision_id = _mod_revision.ensure_null(revision_id)
442
455
return branch, self.revision_tree(revision_id, branch)
444
@deprecated_method(deprecated_in((2, 1, 0)))
445
def ensure_revision_trees(self):
446
if self.this_revision_tree is None:
447
self.this_basis_tree = self.revision_tree(self.this_basis)
448
if self.this_basis == self.this_rev_id:
449
self.this_revision_tree = self.this_basis_tree
451
if self.other_rev_id is None:
452
other_basis_tree = self.revision_tree(self.other_basis)
453
if other_basis_tree.has_changes(self.other_tree):
454
raise errors.WorkingTreeNotRevision(self.this_tree)
455
other_rev_id = self.other_basis
456
self.other_tree = other_basis_tree
458
@deprecated_method(deprecated_in((2, 1, 0)))
459
def file_revisions(self, file_id):
460
self.ensure_revision_trees()
461
if self.this_rev_id is None:
462
if self.this_basis_tree.get_file_sha1(file_id) != \
463
self.this_tree.get_file_sha1(file_id):
464
raise errors.WorkingTreeNotRevision(self.this_tree)
466
trees = (self.this_basis_tree, self.other_tree)
467
return [tree.get_file_revision(file_id) for tree in trees]
469
@deprecated_method(deprecated_in((2, 1, 0)))
470
def check_basis(self, check_clean, require_commits=True):
471
if self.this_basis is None and require_commits is True:
472
raise errors.BzrCommandError(
473
"This branch has no commits."
474
" (perhaps you would prefer 'bzr pull')")
477
if self.this_basis != self.this_rev_id:
478
raise errors.UncommittedChanges(self.this_tree)
480
@deprecated_method(deprecated_in((2, 1, 0)))
481
def compare_basis(self):
483
basis_tree = self.revision_tree(self.this_tree.last_revision())
484
except errors.NoSuchRevision:
485
basis_tree = self.this_tree.basis_tree()
486
if not self.this_tree.has_changes(basis_tree):
487
self.this_rev_id = self.this_basis
489
457
def set_interesting_files(self, file_list):
490
458
self.interesting_files = file_list
536
504
raise errors.NoCommits(self.other_branch)
537
505
if self.other_rev_id is not None:
538
506
self._cached_trees[self.other_rev_id] = self.other_tree
539
self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
507
self._maybe_fetch(self.other_branch, self.this_branch, self.other_basis)
541
509
def set_other_revision(self, revision_id, other_branch):
542
510
"""Set 'other' based on a branch and revision id
604
572
trace.mutter('Criss-cross lcas: %r' % lcas)
605
573
if self.base_rev_id in lcas:
606
574
trace.mutter('Unable to find unique lca. '
607
'Fallback %r as best option.' % self.base_rev_id)
575
'Fallback %r as best option.'
608
577
interesting_revision_ids = set(lcas)
609
578
interesting_revision_ids.add(self.base_rev_id)
610
579
interesting_trees = dict((t.get_revision_id(), t)
643
612
self._maybe_fetch(base_branch, self.this_branch, self.base_rev_id)
645
614
def make_merger(self):
646
kwargs = {'working_tree':self.this_tree, 'this_tree': self.this_tree,
615
kwargs = {'working_tree': self.this_tree, 'this_tree': self.this_tree,
647
616
'other_tree': self.other_tree,
648
617
'interesting_ids': self.interesting_ids,
649
618
'interesting_files': self.interesting_files,
650
619
'this_branch': self.this_branch,
620
'other_branch': self.other_branch,
651
621
'do_merge': False}
652
622
if self.merge_type.requires_base:
653
623
kwargs['base_tree'] = self.base_tree
679
649
merge = self.make_merger()
680
650
if self.other_branch is not None:
681
651
self.other_branch.update_references(self.this_branch)
652
for hook in Merger.hooks['pre_merge']:
655
for hook in Merger.hooks['post_merge']:
683
657
if self.recurse == 'down':
684
658
for relpath, file_id in self.this_tree.iter_references():
685
659
sub_tree = self.this_tree.get_nested_tree(file_id, relpath)
711
686
merge = operation.run_simple()
712
687
if len(merge.cooked_conflicts) == 0:
713
688
if not self.ignore_zero and not trace.is_quiet():
714
trace.note("All changes applied successfully.")
689
trace.note(gettext("All changes applied successfully."))
716
trace.note("%d conflicts encountered."
691
trace.note(gettext("%d conflicts encountered.")
717
692
% len(merge.cooked_conflicts))
719
694
return len(merge.cooked_conflicts)
751
726
interesting_ids=None, reprocess=False, show_base=False,
752
727
pb=None, pp=None, change_reporter=None,
753
728
interesting_files=None, do_merge=True,
754
cherrypick=False, lca_trees=None, this_branch=None):
729
cherrypick=False, lca_trees=None, this_branch=None,
755
731
"""Initialize the merger object and perform the merge.
757
733
:param working_tree: The working tree to apply the merge to
787
764
this_branch = this_tree.branch
788
765
self.interesting_ids = interesting_ids
789
766
self.interesting_files = interesting_files
790
self.this_tree = working_tree
767
self.working_tree = working_tree
768
self.this_tree = this_tree
791
769
self.base_tree = base_tree
792
770
self.other_tree = other_tree
793
771
self.this_branch = this_branch
772
self.other_branch = other_branch
794
773
self._raw_conflicts = []
795
774
self.cooked_conflicts = []
796
775
self.reprocess = reprocess
823
804
def _do_merge(self, operation):
824
self.tt = transform.TreeTransform(self.this_tree, None)
805
self.tt = transform.TreeTransform(self.working_tree, None)
825
806
operation.add_cleanup(self.tt.finalize)
826
807
self._compute_transform()
827
808
results = self.tt.apply(no_conflicts=True)
828
809
self.write_modified(results)
830
self.this_tree.add_conflicts(self.cooked_conflicts)
811
self.working_tree.add_conflicts(self.cooked_conflicts)
831
812
except errors.UnsupportedOperation:
852
833
entries = self._entries_lca()
853
834
resolver = self._lca_multi_way
835
# Prepare merge hooks
836
factories = Merger.hooks['merge_file_content']
837
# One hook for each registered one plus our default merger
838
hooks = [factory(self) for factory in factories] + [self]
839
self.active_hooks = [hook for hook in hooks if hook is not None]
854
840
child_pb = ui.ui_factory.nested_progress_bar()
856
factories = Merger.hooks['merge_file_content']
857
hooks = [factory(self) for factory in factories] + [self]
858
self.active_hooks = [hook for hook in hooks if hook is not None]
859
842
for num, (file_id, changed, parents3, names3,
860
843
executable3) in enumerate(entries):
861
child_pb.update('Preparing file merge', num, len(entries))
844
# Try merging each entry
845
child_pb.update(gettext('Preparing file merge'),
862
847
self._merge_names(file_id, parents3, names3, resolver=resolver)
864
849
file_status = self._do_merge_contents(file_id)
956
941
walker = _mod_tree.MultiWalker(self.other_tree, self._lca_trees)
958
base_inventory = self.base_tree.inventory
959
this_inventory = self.this_tree.inventory
943
base_inventory = self.base_tree.root_inventory
944
this_inventory = self.this_tree.root_inventory
960
945
for path, file_id, other_ie, lca_values in walker.iter_all():
961
946
# Is this modified at all from any of the other trees?
962
947
if other_ie is None:
1117
1102
# other_root doesn't have a physical representation. We still need
1118
1103
# to move any references to the actual root of the tree.
1119
1104
other_root_is_present = False
1120
# 'other_tree.inventory.root' is not present in this tree. We are
1105
# the other tree root is not present in this tree. We are
1121
1106
# calling adjust_path for children which *want* to be present with a
1122
1107
# correct place to go.
1123
for _, child in self.other_tree.inventory.root.children.iteritems():
1124
trans_id = self.tt.trans_id_file_id(child.file_id)
1108
for child_id in self.other_tree.iter_children(
1109
self.other_tree.get_root_id()):
1110
trans_id = self.tt.trans_id_file_id(child_id)
1125
1111
if not other_root_is_present:
1126
1112
if self.tt.final_kind(trans_id) is not None:
1127
1113
# The item exist in the final tree and has a defined place
1141
1127
def write_modified(self, results):
1142
1128
modified_hashes = {}
1143
1129
for path in results.modified_paths:
1144
file_id = self.this_tree.path2id(self.this_tree.relpath(path))
1130
file_id = self.working_tree.path2id(self.working_tree.relpath(path))
1145
1131
if file_id is None:
1147
hash = self.this_tree.get_file_sha1(file_id)
1133
hash = self.working_tree.get_file_sha1(file_id)
1148
1134
if hash is None:
1150
1136
modified_hashes[file_id] = hash
1151
self.this_tree.set_merge_modified(modified_hashes)
1137
self.working_tree.set_merge_modified(modified_hashes)
1154
1140
def parent(entry, file_id):
1378
1364
# We have a hypothetical conflict, but if we have files, then we
1379
1365
# can try to merge the content
1380
1366
trans_id = self.tt.trans_id_file_id(file_id)
1381
params = MergeHookParams(self, file_id, trans_id, this_pair[0],
1367
params = MergeFileHookParams(self, file_id, trans_id, this_pair[0],
1382
1368
other_pair[0], winner)
1383
1369
hooks = self.active_hooks
1384
1370
hook_status = 'not_applicable'
1387
1373
if hook_status != 'not_applicable':
1388
1374
# Don't try any more hooks, this one applies.
1376
# If the merge ends up replacing the content of the file, we get rid of
1377
# it at the end of this method (this variable is used to track the
1378
# exceptions to this rule).
1390
1380
result = "modified"
1391
1381
if hook_status == 'not_applicable':
1392
# This is a contents conflict, because none of the available
1393
# functions could merge it.
1382
# No merge hook was able to resolve the situation. Two cases exist:
1383
# a content conflict or a duplicate one.
1395
1385
name = self.tt.final_name(trans_id)
1396
1386
parent_id = self.tt.final_parent(trans_id)
1397
if self.this_tree.has_id(file_id):
1398
self.tt.unversion_file(trans_id)
1399
file_group = self._dump_conflicts(name, parent_id, file_id,
1401
self._raw_conflicts.append(('contents conflict', file_group))
1388
inhibit_content_conflict = False
1389
if params.this_kind is None: # file_id is not in THIS
1390
# Is the name used for a different file_id ?
1391
dupe_path = self.other_tree.id2path(file_id)
1392
this_id = self.this_tree.path2id(dupe_path)
1393
if this_id is not None:
1394
# Two entries for the same path
1396
# versioning the merged file will trigger a duplicate
1398
self.tt.version_file(file_id, trans_id)
1399
transform.create_from_tree(
1400
self.tt, trans_id, self.other_tree, file_id,
1401
filter_tree_path=self._get_filter_tree_path(file_id))
1402
inhibit_content_conflict = True
1403
elif params.other_kind is None: # file_id is not in OTHER
1404
# Is the name used for a different file_id ?
1405
dupe_path = self.this_tree.id2path(file_id)
1406
other_id = self.other_tree.path2id(dupe_path)
1407
if other_id is not None:
1408
# Two entries for the same path again, but here, the other
1409
# entry will also be merged. We simply inhibit the
1410
# 'content' conflict creation because we know OTHER will
1411
# create (or has already created depending on ordering) an
1412
# entry at the same path. This will trigger a 'duplicate'
1415
inhibit_content_conflict = True
1416
if not inhibit_content_conflict:
1417
if params.this_kind is not None:
1418
self.tt.unversion_file(trans_id)
1419
# This is a contents conflict, because none of the available
1420
# functions could merge it.
1421
file_group = self._dump_conflicts(name, parent_id, file_id,
1423
self._raw_conflicts.append(('contents conflict', file_group))
1402
1424
elif hook_status == 'success':
1403
1425
self.tt.create_file(lines, trans_id)
1404
1426
elif hook_status == 'conflicted':
1420
1442
raise AssertionError('unknown hook_status: %r' % (hook_status,))
1421
1443
if not self.this_tree.has_id(file_id) and result == "modified":
1422
1444
self.tt.version_file(file_id, trans_id)
1423
# The merge has been performed, so the old contents should not be
1425
self.tt.delete_contents(trans_id)
1446
# The merge has been performed and produced a new content, so the
1447
# old contents should not be retained.
1448
self.tt.delete_contents(trans_id)
1428
1451
def _default_other_winner_merge(self, merge_hook_params):
1429
1452
"""Replace this contents with other."""
1430
1453
file_id = merge_hook_params.file_id
1431
1454
trans_id = merge_hook_params.trans_id
1432
file_in_this = self.this_tree.has_id(file_id)
1433
1455
if self.other_tree.has_id(file_id):
1434
1456
# OTHER changed the file
1436
if wt.supports_content_filtering():
1437
# We get the path from the working tree if it exists.
1438
# That fails though when OTHER is adding a file, so
1439
# we fall back to the other tree to find the path if
1440
# it doesn't exist locally.
1442
filter_tree_path = wt.id2path(file_id)
1443
except errors.NoSuchId:
1444
filter_tree_path = self.other_tree.id2path(file_id)
1446
# Skip the id2path lookup for older formats
1447
filter_tree_path = None
1448
transform.create_from_tree(self.tt, trans_id,
1449
self.other_tree, file_id,
1450
filter_tree_path=filter_tree_path)
1457
transform.create_from_tree(
1458
self.tt, trans_id, self.other_tree, file_id,
1459
filter_tree_path=self._get_filter_tree_path(file_id))
1451
1460
return 'done', None
1461
elif self.this_tree.has_id(file_id):
1453
1462
# OTHER deleted the file
1454
1463
return 'delete', None
1530
1539
file_group.append(trans_id)
1542
def _get_filter_tree_path(self, file_id):
1543
if self.this_tree.supports_content_filtering():
1544
# We get the path from the working tree if it exists.
1545
# That fails though when OTHER is adding a file, so
1546
# we fall back to the other tree to find the path if
1547
# it doesn't exist locally.
1549
return self.this_tree.id2path(file_id)
1550
except errors.NoSuchId:
1551
return self.other_tree.id2path(file_id)
1552
# Skip the id2path lookup for older formats
1532
1555
def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1533
1556
base_lines=None, other_lines=None, set_version=False,
1534
1557
no_base=False):
1635
1658
if other_parent is None or other_name is None:
1636
1659
other_path = '<deleted>'
1638
parent_path = fp.get_path(
1639
self.tt.trans_id_file_id(other_parent))
1661
if other_parent == self.other_tree.get_root_id():
1662
# The tree transform doesn't know about the other root,
1663
# so we special case here to avoid a NoFinalPath
1667
parent_path = fp.get_path(
1668
self.tt.trans_id_file_id(other_parent))
1640
1669
other_path = osutils.pathjoin(parent_path, other_name)
1641
1670
c = _mod_conflicts.Conflict.factory(
1642
1671
'path conflict', path=this_path,
1646
1675
for trans_id in conflict[1]:
1647
1676
file_id = self.tt.final_file_id(trans_id)
1648
1677
if file_id is not None:
1678
# Ok we found the relevant file-id
1650
1680
path = fp.get_path(trans_id)
1651
1681
for suffix in ('.BASE', '.THIS', '.OTHER'):
1652
1682
if path.endswith(suffix):
1683
# Here is the raw path
1653
1684
path = path[:-len(suffix)]
1655
1686
c = _mod_conflicts.Conflict.factory(conflict_type,
1900
1931
entries = self._entries_to_incorporate()
1901
1932
entries = list(entries)
1902
1933
for num, (entry, parent_id) in enumerate(entries):
1903
child_pb.update('Preparing file merge', num, len(entries))
1934
child_pb.update(gettext('Preparing file merge'), num, len(entries))
1904
1935
parent_trans_id = self.tt.trans_id_file_id(parent_id)
1905
1936
trans_id = transform.new_by_entry(self.tt, entry,
1906
1937
parent_trans_id, self.other_tree)
1918
1949
raise PathNotInTree(self._source_subpath, "Source tree")
1919
1950
subdir = other_inv[subdir_id]
1920
1951
parent_in_target = osutils.dirname(self._target_subdir)
1921
target_id = self.this_tree.inventory.path2id(parent_in_target)
1952
target_id = self.this_tree.path2id(parent_in_target)
1922
1953
if target_id is None:
1923
1954
raise PathNotInTree(self._target_subdir, "Target tree")
1924
1955
name_in_target = osutils.basename(self._target_subdir)
1925
1956
merge_into_root = subdir.copy()
1926
1957
merge_into_root.name = name_in_target
1927
if self.this_tree.inventory.has_id(merge_into_root.file_id):
1958
if self.this_tree.has_id(merge_into_root.file_id):
1928
1959
# Give the root a new file-id.
1929
1960
# This can happen fairly easily if the directory we are
1930
1961
# incorporating is the root, and both trees have 'TREE_ROOT' as
1990
2021
merger.set_base_revision(get_revision_id(), this_branch)
1991
2022
return merger.do_merge()
2025
merge_type_registry = registry.Registry()
2026
merge_type_registry.register('diff3', Diff3Merger,
2027
"Merge using external diff3.")
2028
merge_type_registry.register('lca', LCAMerger,
2029
"LCA-newness merge.")
2030
merge_type_registry.register('merge3', Merge3Merger,
2031
"Native diff3-style merge.")
2032
merge_type_registry.register('weave', WeaveMerger,
2033
"Weave-based merge.")
1993
2036
def get_merge_type_registry():
1994
"""Merge type registry is in bzrlib.option to avoid circular imports.
2037
"""Merge type registry was previously in bzrlib.option
1996
This method provides a sanctioned way to retrieve it.
2039
This method provides a backwards compatible way to retrieve it.
1998
from bzrlib import option
1999
return option._merge_type_registry
2041
return merge_type_registry
2002
2044
def _plan_annotate_merge(annotated_a, annotated_b, ancestors_a, ancestors_b):