93
100
return ('not applicable', None)
96
class ConfigurableFileMerger(AbstractPerFileMerger):
103
class PerFileMerger(AbstractPerFileMerger):
104
"""Merge individual files when self.file_matches returns True.
106
This class is intended to be subclassed. The file_matches and
107
merge_matching methods should be overridden with concrete implementations.
110
def file_matches(self, params):
111
"""Return True if merge_matching should be called on this file.
113
Only called with merges of plain files with no clear winner.
115
Subclasses must override this.
117
raise NotImplementedError(self.file_matches)
119
def get_filename(self, params, tree):
120
"""Lookup the filename (i.e. basename, not path), given a Tree (e.g.
121
self.merger.this_tree) and a MergeHookParams.
123
return osutils.basename(tree.id2path(params.file_id))
125
def get_filepath(self, params, tree):
126
"""Calculate the path to the file in a tree.
128
:param params: A MergeHookParams describing the file to merge
129
:param tree: a Tree, e.g. self.merger.this_tree.
131
return tree.id2path(params.file_id)
133
def merge_contents(self, params):
134
"""Merge the contents of a single file."""
135
# Check whether this custom merge logic should be used.
137
# OTHER is a straight winner, rely on default merge.
138
params.winner == 'other' or
139
# THIS and OTHER aren't both files.
140
not params.is_file_merge() or
141
# The filename doesn't match *.xml
142
not self.file_matches(params)):
143
return 'not_applicable', None
144
return self.merge_matching(params)
146
def merge_matching(self, params):
147
"""Merge the contents of a single file that has matched the criteria
148
in PerFileMerger.merge_contents (is a conflict, is a file,
149
self.file_matches is True).
151
Subclasses must override this.
153
raise NotImplementedError(self.merge_matching)
156
class ConfigurableFileMerger(PerFileMerger):
97
157
"""Merge individual files when configured via a .conf file.
99
159
This is a base class for concrete custom file merging logic. Concrete
100
160
classes should implement ``merge_text``.
162
See ``bzrlib.plugins.news_merge.news_merge`` for an example concrete class.
102
164
:ivar affected_files: The configured file paths to merge.
103
166
:cvar name_prefix: The prefix to use when looking up configuration
167
details. <name_prefix>_merge_files describes the files targeted by the
105
170
:cvar default_files: The default file paths to merge when no configuration
132
202
affected_files = self.default_files
133
203
self.affected_files = affected_files
134
204
if affected_files:
135
filename = self.merger.this_tree.id2path(params.file_id)
136
if filename in affected_files:
205
filepath = self.get_filepath(params, self.merger.this_tree)
206
if filepath in affected_files:
140
def merge_contents(self, params):
141
"""Merge the contents of a single file."""
142
# First, check whether this custom merge logic should be used. We
143
# expect most files should not be merged by this handler.
145
# OTHER is a straight winner, rely on default merge.
146
params.winner == 'other' or
147
# THIS and OTHER aren't both files.
148
not params.is_file_merge() or
149
# The filename isn't listed in the 'NAME_merge_files' config
151
not self.filename_matches_config(params)):
152
return 'not_applicable', None
153
return self.merge_text(self, params)
210
def merge_matching(self, params):
211
return self.merge_text(params)
155
213
def merge_text(self, params):
156
214
"""Merge the byte contents of a single file.
541
594
self.base_rev_id = self.revision_graph.find_unique_lca(
543
self._is_criss_cross = True
596
sorted_lca_keys = self.revision_graph.find_merge_order(
598
if self.base_rev_id == _mod_revision.NULL_REVISION:
599
self.base_rev_id = sorted_lca_keys[0]
544
601
if self.base_rev_id == _mod_revision.NULL_REVISION:
545
602
raise errors.UnrelatedBranches()
546
603
if self._is_criss_cross:
547
604
trace.warning('Warning: criss-cross merge encountered. See bzr'
548
605
' help criss-cross.')
549
606
trace.mutter('Criss-cross lcas: %r' % lcas)
550
interesting_revision_ids = [self.base_rev_id]
551
interesting_revision_ids.extend(lcas)
607
if self.base_rev_id in lcas:
608
trace.mutter('Unable to find unique lca. '
609
'Fallback %r as best option.' % self.base_rev_id)
610
interesting_revision_ids = set(lcas)
611
interesting_revision_ids.add(self.base_rev_id)
552
612
interesting_trees = dict((t.get_revision_id(), t)
553
613
for t in self.this_branch.repository.revision_trees(
554
614
interesting_revision_ids))
555
615
self._cached_trees.update(interesting_trees)
556
self.base_tree = interesting_trees.pop(self.base_rev_id)
557
sorted_lca_keys = self.revision_graph.find_merge_order(
616
if self.base_rev_id in lcas:
617
self.base_tree = interesting_trees[self.base_rev_id]
619
self.base_tree = interesting_trees.pop(self.base_rev_id)
559
620
self._lca_trees = [interesting_trees[key]
560
621
for key in sorted_lca_keys]
745
803
# making sure we haven't missed any corner cases.
746
804
# if lca_trees is None:
747
805
# self._lca_trees = [self.base_tree]
750
806
self.change_reporter = change_reporter
751
807
self.cherrypick = cherrypick
753
self.pp = progress.ProgressPhase("Merge phase", 3, self.pb)
811
warnings.warn("pp argument to Merge3Merger is deprecated")
813
warnings.warn("pb argument to Merge3Merger is deprecated")
757
815
def do_merge(self):
816
operation = OperationWithCleanups(self._do_merge)
758
817
self.this_tree.lock_tree_write()
818
operation.add_cleanup(self.this_tree.unlock)
759
819
self.base_tree.lock_read()
820
operation.add_cleanup(self.base_tree.unlock)
760
821
self.other_tree.lock_read()
822
operation.add_cleanup(self.other_tree.unlock)
825
def _do_merge(self, operation):
826
self.tt = transform.TreeTransform(self.this_tree, None)
827
operation.add_cleanup(self.tt.finalize)
828
self._compute_transform()
829
results = self.tt.apply(no_conflicts=True)
830
self.write_modified(results)
762
self.tt = transform.TreeTransform(self.this_tree, self.pb)
765
self._compute_transform()
767
results = self.tt.apply(no_conflicts=True)
768
self.write_modified(results)
770
self.this_tree.add_conflicts(self.cooked_conflicts)
771
except errors.UnsupportedOperation:
776
self.other_tree.unlock()
777
self.base_tree.unlock()
778
self.this_tree.unlock()
832
self.this_tree.add_conflicts(self.cooked_conflicts)
833
except errors.UnsupportedOperation:
781
836
def make_preview_transform(self):
837
operation = OperationWithCleanups(self._make_preview_transform)
782
838
self.base_tree.lock_read()
839
operation.add_cleanup(self.base_tree.unlock)
783
840
self.other_tree.lock_read()
841
operation.add_cleanup(self.other_tree.unlock)
842
return operation.run_simple()
844
def _make_preview_transform(self):
784
845
self.tt = transform.TransformPreview(self.this_tree)
787
self._compute_transform()
790
self.other_tree.unlock()
791
self.base_tree.unlock()
846
self._compute_transform()
795
849
def _compute_transform(self):
1049
1105
other_root = self.tt.trans_id_file_id(other_root_file_id)
1050
1106
if other_root == self.tt.root:
1053
self.tt.final_kind(other_root)
1054
except errors.NoSuchFile:
1056
if self.this_tree.has_id(self.other_tree.inventory.root.file_id):
1057
# the other tree's root is a non-root in the current tree
1059
self.reparent_children(self.other_tree.inventory.root, self.tt.root)
1060
self.tt.cancel_creation(other_root)
1061
self.tt.cancel_versioning(other_root)
1063
def reparent_children(self, ie, target):
1064
for thing, child in ie.children.iteritems():
1108
if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1109
# the other tree's root is a non-root in the current tree (as when
1110
# a previously unrelated branch is merged into another)
1112
if self.tt.final_kind(other_root) is not None:
1113
other_root_is_present = True
1115
# other_root doesn't have a physical representation. We still need
1116
# to move any references to the actual root of the tree.
1117
other_root_is_present = False
1118
# 'other_tree.inventory.root' is not present in this tree. We are
1119
# calling adjust_path for children which *want* to be present with a
1120
# correct place to go.
1121
for thing, child in self.other_tree.inventory.root.children.iteritems():
1065
1122
trans_id = self.tt.trans_id_file_id(child.file_id)
1066
self.tt.adjust_path(self.tt.final_name(trans_id), target, trans_id)
1123
if not other_root_is_present:
1124
if self.tt.final_kind(trans_id) is not None:
1125
# The item exist in the final tree and has a defined place
1128
# Move the item into the root
1129
self.tt.adjust_path(self.tt.final_name(trans_id),
1130
self.tt.root, trans_id)
1131
if other_root_is_present:
1132
self.tt.cancel_creation(other_root)
1133
self.tt.cancel_versioning(other_root)
1068
1135
def write_modified(self, results):
1069
1136
modified_hashes = {}
1234
1304
parent_id_winner = "other"
1235
1305
if name_winner == "this" and parent_id_winner == "this":
1237
if name_winner == "conflict":
1238
trans_id = self.tt.trans_id_file_id(file_id)
1239
self._raw_conflicts.append(('name conflict', trans_id,
1240
this_name, other_name))
1241
if parent_id_winner == "conflict":
1242
trans_id = self.tt.trans_id_file_id(file_id)
1243
self._raw_conflicts.append(('parent conflict', trans_id,
1244
this_parent, other_parent))
1307
if name_winner == 'conflict' or parent_id_winner == 'conflict':
1308
# Creating helpers (.OTHER or .THIS) here cause problems down the
1309
# road if a ContentConflict needs to be created so we should not do
1311
trans_id = self.tt.trans_id_file_id(file_id)
1312
self._raw_conflicts.append(('path conflict', trans_id, file_id,
1313
this_parent, this_name,
1314
other_parent, other_name))
1245
1315
if other_name is None:
1246
1316
# it doesn't matter whether the result was 'other' or
1247
1317
# 'conflict'-- if there's no 'other', we leave it alone.
1249
# if we get here, name_winner and parent_winner are set to safe values.
1250
trans_id = self.tt.trans_id_file_id(file_id)
1251
1319
parent_id = parents[self.winner_idx[parent_id_winner]]
1252
1320
if parent_id is not None:
1253
parent_trans_id = self.tt.trans_id_file_id(parent_id)
1321
# if we get here, name_winner and parent_winner are set to safe
1254
1323
self.tt.adjust_path(names[self.winner_idx[name_winner]],
1255
parent_trans_id, trans_id)
1324
self.tt.trans_id_file_id(parent_id),
1325
self.tt.trans_id_file_id(file_id))
1257
1327
def _do_merge_contents(self, file_id):
1258
1328
"""Performs a merge on file_id contents."""
1538
1602
def cook_conflicts(self, fs_conflicts):
1539
1603
"""Convert all conflicts into a form that doesn't depend on trans_id"""
1541
1604
self.cooked_conflicts.extend(transform.cook_conflicts(
1542
1605
fs_conflicts, self.tt))
1543
1606
fp = transform.FinalPaths(self.tt)
1544
1607
for conflict in self._raw_conflicts:
1545
1608
conflict_type = conflict[0]
1546
if conflict_type in ('name conflict', 'parent conflict'):
1547
trans_id = conflict[1]
1548
conflict_args = conflict[2:]
1549
if trans_id not in name_conflicts:
1550
name_conflicts[trans_id] = {}
1551
transform.unique_add(name_conflicts[trans_id], conflict_type,
1553
if conflict_type == 'contents conflict':
1609
if conflict_type == 'path conflict':
1611
this_parent, this_name,
1612
other_parent, other_name) = conflict[1:]
1613
if this_parent is None or this_name is None:
1614
this_path = '<deleted>'
1616
parent_path = fp.get_path(
1617
self.tt.trans_id_file_id(this_parent))
1618
this_path = osutils.pathjoin(parent_path, this_name)
1619
if other_parent is None or other_name is None:
1620
other_path = '<deleted>'
1622
parent_path = fp.get_path(
1623
self.tt.trans_id_file_id(other_parent))
1624
other_path = osutils.pathjoin(parent_path, other_name)
1625
c = _mod_conflicts.Conflict.factory(
1626
'path conflict', path=this_path,
1627
conflict_path=other_path,
1629
elif conflict_type == 'contents conflict':
1554
1630
for trans_id in conflict[1]:
1555
1631
file_id = self.tt.final_file_id(trans_id)
1556
1632
if file_id is not None:
1563
1639
c = _mod_conflicts.Conflict.factory(conflict_type,
1564
1640
path=path, file_id=file_id)
1565
self.cooked_conflicts.append(c)
1566
if conflict_type == 'text conflict':
1641
elif conflict_type == 'text conflict':
1567
1642
trans_id = conflict[1]
1568
1643
path = fp.get_path(trans_id)
1569
1644
file_id = self.tt.final_file_id(trans_id)
1570
1645
c = _mod_conflicts.Conflict.factory(conflict_type,
1571
1646
path=path, file_id=file_id)
1572
self.cooked_conflicts.append(c)
1574
for trans_id, conflicts in name_conflicts.iteritems():
1576
this_parent, other_parent = conflicts['parent conflict']
1577
if this_parent == other_parent:
1578
raise AssertionError()
1580
this_parent = other_parent = \
1581
self.tt.final_file_id(self.tt.final_parent(trans_id))
1583
this_name, other_name = conflicts['name conflict']
1584
if this_name == other_name:
1585
raise AssertionError()
1587
this_name = other_name = self.tt.final_name(trans_id)
1588
other_path = fp.get_path(trans_id)
1589
if this_parent is not None and this_name is not None:
1590
this_parent_path = \
1591
fp.get_path(self.tt.trans_id_file_id(this_parent))
1592
this_path = osutils.pathjoin(this_parent_path, this_name)
1594
this_path = "<deleted>"
1595
file_id = self.tt.final_file_id(trans_id)
1596
c = _mod_conflicts.Conflict.factory('path conflict', path=this_path,
1597
conflict_path=other_path,
1648
raise AssertionError('bad conflict type: %r' % (conflict,))
1599
1649
self.cooked_conflicts.append(c)
1600
1650
self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1707
1757
osutils.rmtree(temp_dir)
1760
class PathNotInTree(errors.BzrError):
1762
_fmt = """Merge-into failed because %(tree)s does not contain %(path)s."""
1764
def __init__(self, path, tree):
1765
errors.BzrError.__init__(self, path=path, tree=tree)
1768
class MergeIntoMerger(Merger):
1769
"""Merger that understands other_tree will be merged into a subdir.
1771
This also changes the Merger api so that it uses real Branch, revision_id,
1772
and RevisonTree objects, rather than using revision specs.
1775
def __init__(self, this_tree, other_branch, other_tree, target_subdir,
1776
source_subpath, other_rev_id=None):
1777
"""Create a new MergeIntoMerger object.
1779
source_subpath in other_tree will be effectively copied to
1780
target_subdir in this_tree.
1782
:param this_tree: The tree that we will be merging into.
1783
:param other_branch: The Branch we will be merging from.
1784
:param other_tree: The RevisionTree object we want to merge.
1785
:param target_subdir: The relative path where we want to merge
1786
other_tree into this_tree
1787
:param source_subpath: The relative path specifying the subtree of
1788
other_tree to merge into this_tree.
1790
# It is assumed that we are merging a tree that is not in our current
1791
# ancestry, which means we are using the "EmptyTree" as our basis.
1792
null_ancestor_tree = this_tree.branch.repository.revision_tree(
1793
_mod_revision.NULL_REVISION)
1794
super(MergeIntoMerger, self).__init__(
1795
this_branch=this_tree.branch,
1796
this_tree=this_tree,
1797
other_tree=other_tree,
1798
base_tree=null_ancestor_tree,
1800
self._target_subdir = target_subdir
1801
self._source_subpath = source_subpath
1802
self.other_branch = other_branch
1803
if other_rev_id is None:
1804
other_rev_id = other_tree.get_revision_id()
1805
self.other_rev_id = self.other_basis = other_rev_id
1806
self.base_is_ancestor = True
1807
self.backup_files = True
1808
self.merge_type = Merge3Merger
1809
self.show_base = False
1810
self.reprocess = False
1811
self.interesting_ids = None
1812
self.merge_type = _MergeTypeParameterizer(MergeIntoMergeType,
1813
target_subdir=self._target_subdir,
1814
source_subpath=self._source_subpath)
1815
if self._source_subpath != '':
1816
# If this isn't a partial merge make sure the revisions will be
1818
self._maybe_fetch(self.other_branch, self.this_branch,
1821
def set_pending(self):
1822
if self._source_subpath != '':
1824
Merger.set_pending(self)
1827
class _MergeTypeParameterizer(object):
1828
"""Wrap a merge-type class to provide extra parameters.
1830
This is hack used by MergeIntoMerger to pass some extra parameters to its
1831
merge_type. Merger.do_merge() sets up its own set of parameters to pass to
1832
the 'merge_type' member. It is difficult override do_merge without
1833
re-writing the whole thing, so instead we create a wrapper which will pass
1834
the extra parameters.
1837
def __init__(self, merge_type, **kwargs):
1838
self._extra_kwargs = kwargs
1839
self._merge_type = merge_type
1841
def __call__(self, *args, **kwargs):
1842
kwargs.update(self._extra_kwargs)
1843
return self._merge_type(*args, **kwargs)
1845
def __getattr__(self, name):
1846
return getattr(self._merge_type, name)
1849
class MergeIntoMergeType(Merge3Merger):
1850
"""Merger that incorporates a tree (or part of a tree) into another."""
1852
def __init__(self, *args, **kwargs):
1853
"""Initialize the merger object.
1855
:param args: See Merge3Merger.__init__'s args.
1856
:param kwargs: See Merge3Merger.__init__'s keyword args, except for
1857
source_subpath and target_subdir.
1858
:keyword source_subpath: The relative path specifying the subtree of
1859
other_tree to merge into this_tree.
1860
:keyword target_subdir: The relative path where we want to merge
1861
other_tree into this_tree
1863
# All of the interesting work happens during Merge3Merger.__init__(),
1864
# so we have have to hack in to get our extra parameters set.
1865
self._source_subpath = kwargs.pop('source_subpath')
1866
self._target_subdir = kwargs.pop('target_subdir')
1867
super(MergeIntoMergeType, self).__init__(*args, **kwargs)
1869
def _compute_transform(self):
1870
child_pb = ui.ui_factory.nested_progress_bar()
1872
entries = self._entries_to_incorporate()
1873
entries = list(entries)
1874
for num, (entry, parent_id) in enumerate(entries):
1875
child_pb.update('Preparing file merge', num, len(entries))
1876
parent_trans_id = self.tt.trans_id_file_id(parent_id)
1877
trans_id = transform.new_by_entry(self.tt, entry,
1878
parent_trans_id, self.other_tree)
1881
self._finish_computing_transform()
1883
def _entries_to_incorporate(self):
1884
"""Yields pairs of (inventory_entry, new_parent)."""
1885
other_inv = self.other_tree.inventory
1886
subdir_id = other_inv.path2id(self._source_subpath)
1887
if subdir_id is None:
1888
# XXX: The error would be clearer if it gave the URL of the source
1889
# branch, but we don't have a reference to that here.
1890
raise PathNotInTree(self._source_subpath, "Source tree")
1891
subdir = other_inv[subdir_id]
1892
parent_in_target = osutils.dirname(self._target_subdir)
1893
target_id = self.this_tree.inventory.path2id(parent_in_target)
1894
if target_id is None:
1895
raise PathNotInTree(self._target_subdir, "Target tree")
1896
name_in_target = osutils.basename(self._target_subdir)
1897
merge_into_root = subdir.copy()
1898
merge_into_root.name = name_in_target
1899
if merge_into_root.file_id in self.this_tree.inventory:
1900
# Give the root a new file-id.
1901
# This can happen fairly easily if the directory we are
1902
# incorporating is the root, and both trees have 'TREE_ROOT' as
1903
# their root_id. Users will expect this to Just Work, so we
1904
# change the file-id here.
1905
# Non-root file-ids could potentially conflict too. That's really
1906
# an edge case, so we don't do anything special for those. We let
1907
# them cause conflicts.
1908
merge_into_root.file_id = generate_ids.gen_file_id(name_in_target)
1909
yield (merge_into_root, target_id)
1910
if subdir.kind != 'directory':
1911
# No children, so we are done.
1913
for ignored_path, entry in other_inv.iter_entries_by_dir(subdir_id):
1914
parent_id = entry.parent_id
1915
if parent_id == subdir.file_id:
1916
# The root's parent ID has changed, so make sure children of
1917
# the root refer to the new ID.
1918
parent_id = merge_into_root.file_id
1919
yield (entry, parent_id)
1710
1922
def merge_inner(this_branch, other_tree, base_tree, ignore_zero=False,
1711
1923
backup_files=False,
1712
1924
merge_type=Merge3Merger,