56
class MergeHooks(hooks.Hooks):
59
hooks.Hooks.__init__(self)
60
self.create_hook(hooks.HookPoint('merge_file_content',
61
"Called with a bzrlib.merge.Merger object to create a per file "
62
"merge object when starting a merge. "
63
"Should return either None or a subclass of "
64
"``bzrlib.merge.AbstractPerFileMerger``. "
65
"Such objects will then be called per file "
66
"that needs to be merged (including when one "
67
"side has deleted the file and the other has changed it). "
68
"See the AbstractPerFileMerger API docs for details on how it is "
73
class AbstractPerFileMerger(object):
74
"""PerFileMerger objects are used by plugins extending merge for bzrlib.
76
See ``bzrlib.plugins.news_merge.news_merge`` for an example concrete class.
78
:ivar merger: The Merge3Merger performing the merge.
81
def __init__(self, merger):
82
"""Create a PerFileMerger for use with merger."""
85
def merge_contents(self, merge_params):
86
"""Attempt to merge the contents of a single file.
88
:param merge_params: A bzrlib.merge.MergeHookParams
89
:return : A tuple of (status, chunks), where status is one of
90
'not_applicable', 'success', 'conflicted', or 'delete'. If status
91
is 'success' or 'conflicted', then chunks should be an iterable of
92
strings for the new file contents.
94
return ('not applicable', None)
97
class ConfigurableFileMerger(AbstractPerFileMerger):
98
"""Merge individual files when configured via a .conf file.
100
This is a base class for concrete custom file merging logic. Concrete
101
classes should implement ``merge_text``.
103
See ``bzrlib.plugins.news_merge.news_merge`` for an example concrete class.
105
:ivar affected_files: The configured file paths to merge.
107
:cvar name_prefix: The prefix to use when looking up configuration
108
details. <name_prefix>_merge_files describes the files targeted by the
111
:cvar default_files: The default file paths to merge when no configuration
118
def __init__(self, merger):
119
super(ConfigurableFileMerger, self).__init__(merger)
120
self.affected_files = None
121
self.default_files = self.__class__.default_files or []
122
self.name_prefix = self.__class__.name_prefix
123
if self.name_prefix is None:
124
raise ValueError("name_prefix must be set.")
126
def filename_matches_config(self, params):
127
"""Check whether the file should call the merge hook.
129
<name_prefix>_merge_files configuration variable is a list of files
130
that should use the hook.
132
affected_files = self.affected_files
133
if affected_files is None:
134
config = self.merger.this_tree.branch.get_config()
135
# Until bzr provides a better policy for caching the config, we
136
# just add the part we're interested in to the params to avoid
137
# reading the config files repeatedly (bazaar.conf, location.conf,
139
config_key = self.name_prefix + '_merge_files'
140
affected_files = config.get_user_option_as_list(config_key)
141
if affected_files is None:
142
# If nothing was specified in the config, use the default.
143
affected_files = self.default_files
144
self.affected_files = affected_files
146
filename = self.merger.this_tree.id2path(params.file_id)
147
if filename in affected_files:
151
def merge_contents(self, params):
152
"""Merge the contents of a single file."""
153
# First, check whether this custom merge logic should be used. We
154
# expect most files should not be merged by this handler.
156
# OTHER is a straight winner, rely on default merge.
157
params.winner == 'other' or
158
# THIS and OTHER aren't both files.
159
not params.is_file_merge() or
160
# The filename isn't listed in the 'NAME_merge_files' config
162
not self.filename_matches_config(params)):
163
return 'not_applicable', None
164
return self.merge_text(params)
166
def merge_text(self, params):
167
"""Merge the byte contents of a single file.
169
This is called after checking that the merge should be performed in
170
merge_contents, and it should behave as per
171
``bzrlib.merge.AbstractPerFileMerger.merge_contents``.
173
raise NotImplementedError(self.merge_text)
176
class MergeHookParams(object):
177
"""Object holding parameters passed to merge_file_content hooks.
179
There are some fields hooks can access:
181
:ivar file_id: the file ID of the file being merged
182
:ivar trans_id: the transform ID for the merge of this file
183
:ivar this_kind: kind of file_id in 'this' tree
184
:ivar other_kind: kind of file_id in 'other' tree
185
:ivar winner: one of 'this', 'other', 'conflict'
188
def __init__(self, merger, file_id, trans_id, this_kind, other_kind,
190
self._merger = merger
191
self.file_id = file_id
192
self.trans_id = trans_id
193
self.this_kind = this_kind
194
self.other_kind = other_kind
197
def is_file_merge(self):
198
"""True if this_kind and other_kind are both 'file'."""
199
return self.this_kind == 'file' and self.other_kind == 'file'
201
@decorators.cachedproperty
202
def base_lines(self):
203
"""The lines of the 'base' version of the file."""
204
return self._merger.get_lines(self._merger.base_tree, self.file_id)
206
@decorators.cachedproperty
207
def this_lines(self):
208
"""The lines of the 'this' version of the file."""
209
return self._merger.get_lines(self._merger.this_tree, self.file_id)
211
@decorators.cachedproperty
212
def other_lines(self):
213
"""The lines of the 'other' version of the file."""
214
return self._merger.get_lines(self._merger.other_tree, self.file_id)
54
217
class Merger(object):
55
221
def __init__(self, this_branch, other_tree=None, base_tree=None,
56
222
this_tree=None, pb=None, change_reporter=None,
57
223
recurse='down', revision_graph=None):
542
707
def __init__(self, working_tree, this_tree, base_tree, other_tree,
543
708
interesting_ids=None, reprocess=False, show_base=False,
544
pb=progress.DummyProgress(), pp=None, change_reporter=None,
709
pb=None, pp=None, change_reporter=None,
545
710
interesting_files=None, do_merge=True,
546
cherrypick=False, lca_trees=None):
711
cherrypick=False, lca_trees=None, this_branch=None):
547
712
"""Initialize the merger object and perform the merge.
549
714
:param working_tree: The working tree to apply the merge to
550
715
:param this_tree: The local tree in the merge operation
551
716
:param base_tree: The common tree in the merge operation
552
717
:param other_tree: The other tree to merge changes from
718
:param this_branch: The branch associated with this_tree
553
719
:param interesting_ids: The file_ids of files that should be
554
720
participate in the merge. May not be combined with
555
721
interesting_files.
556
722
:param: reprocess If True, perform conflict-reduction processing.
557
723
:param show_base: If True, show the base revision in text conflicts.
558
724
(incompatible with reprocess)
559
:param pb: A Progress bar
560
726
:param pp: A ProgressPhase object
561
727
:param change_reporter: An object that should report changes made
562
728
:param interesting_files: The tree-relative paths of files that should
1141
1292
if winner == 'this':
1142
1293
# No interesting changes introduced by OTHER
1143
1294
return "unmodified"
1295
# We have a hypothetical conflict, but if we have files, then we
1296
# can try to merge the content
1144
1297
trans_id = self.tt.trans_id_file_id(file_id)
1145
if winner == 'other':
1298
params = MergeHookParams(self, file_id, trans_id, this_pair[0],
1299
other_pair[0], winner)
1300
hooks = self.active_hooks
1301
hook_status = 'not_applicable'
1303
hook_status, lines = hook.merge_contents(params)
1304
if hook_status != 'not_applicable':
1305
# Don't try any more hooks, this one applies.
1308
if hook_status == 'not_applicable':
1309
# This is a contents conflict, because none of the available
1310
# functions could merge it.
1312
name = self.tt.final_name(trans_id)
1313
parent_id = self.tt.final_parent(trans_id)
1314
if self.this_tree.has_id(file_id):
1315
self.tt.unversion_file(trans_id)
1316
file_group = self._dump_conflicts(name, parent_id, file_id,
1318
self._raw_conflicts.append(('contents conflict', file_group))
1319
elif hook_status == 'success':
1320
self.tt.create_file(lines, trans_id)
1321
elif hook_status == 'conflicted':
1322
# XXX: perhaps the hook should be able to provide
1323
# the BASE/THIS/OTHER files?
1324
self.tt.create_file(lines, trans_id)
1325
self._raw_conflicts.append(('text conflict', trans_id))
1326
name = self.tt.final_name(trans_id)
1327
parent_id = self.tt.final_parent(trans_id)
1328
self._dump_conflicts(name, parent_id, file_id)
1329
elif hook_status == 'delete':
1330
self.tt.unversion_file(trans_id)
1332
elif hook_status == 'done':
1333
# The hook function did whatever it needs to do directly, no
1334
# further action needed here.
1337
raise AssertionError('unknown hook_status: %r' % (hook_status,))
1338
if not self.this_tree.has_id(file_id) and result == "modified":
1339
self.tt.version_file(file_id, trans_id)
1340
# The merge has been performed, so the old contents should not be
1343
self.tt.delete_contents(trans_id)
1344
except errors.NoSuchFile:
1348
def _default_other_winner_merge(self, merge_hook_params):
1349
"""Replace this contents with other."""
1350
file_id = merge_hook_params.file_id
1351
trans_id = merge_hook_params.trans_id
1352
file_in_this = self.this_tree.has_id(file_id)
1353
if self.other_tree.has_id(file_id):
1354
# OTHER changed the file
1356
if wt.supports_content_filtering():
1357
# We get the path from the working tree if it exists.
1358
# That fails though when OTHER is adding a file, so
1359
# we fall back to the other tree to find the path if
1360
# it doesn't exist locally.
1362
filter_tree_path = wt.id2path(file_id)
1363
except errors.NoSuchId:
1364
filter_tree_path = self.other_tree.id2path(file_id)
1366
# Skip the id2path lookup for older formats
1367
filter_tree_path = None
1368
transform.create_from_tree(self.tt, trans_id,
1369
self.other_tree, file_id,
1370
filter_tree_path=filter_tree_path)
1373
# OTHER deleted the file
1374
return 'delete', None
1376
raise AssertionError(
1377
'winner is OTHER, but file_id %r not in THIS or OTHER tree'
1380
def merge_contents(self, merge_hook_params):
1381
"""Fallback merge logic after user installed hooks."""
1382
# This function is used in merge hooks as the fallback instance.
1383
# Perhaps making this function and the functions it calls be a
1384
# a separate class would be better.
1385
if merge_hook_params.winner == 'other':
1146
1386
# OTHER is a straight winner, so replace this contents with other
1147
file_in_this = file_id in self.this_tree
1149
# Remove any existing contents
1150
self.tt.delete_contents(trans_id)
1151
if file_id in self.other_tree:
1152
# OTHER changed the file
1153
transform.create_from_tree(self.tt, trans_id,
1154
self.other_tree, file_id)
1155
if not file_in_this:
1156
self.tt.version_file(file_id, trans_id)
1159
# OTHER deleted the file
1160
self.tt.unversion_file(trans_id)
1387
return self._default_other_winner_merge(merge_hook_params)
1388
elif merge_hook_params.is_file_merge():
1389
# THIS and OTHER are both files, so text merge. Either
1390
# BASE is a file, or both converted to files, so at least we
1391
# have agreement that output should be a file.
1393
self.text_merge(merge_hook_params.file_id,
1394
merge_hook_params.trans_id)
1395
except errors.BinaryFile:
1396
return 'not_applicable', None
1163
# We have a hypothetical conflict, but if we have files, then we
1164
# can try to merge the content
1165
if this_pair[0] == 'file' and other_pair[0] == 'file':
1166
# THIS and OTHER are both files, so text merge. Either
1167
# BASE is a file, or both converted to files, so at least we
1168
# have agreement that output should be a file.
1170
self.text_merge(file_id, trans_id)
1171
except errors.BinaryFile:
1172
return contents_conflict()
1173
if file_id not in self.this_tree:
1174
self.tt.version_file(file_id, trans_id)
1176
self.tt.tree_kind(trans_id)
1177
self.tt.delete_contents(trans_id)
1178
except errors.NoSuchFile:
1182
return contents_conflict()
1399
return 'not_applicable', None
1184
1401
def get_lines(self, tree, file_id):
1185
1402
"""Return the lines in a file, or an empty list."""
1403
if tree.has_id(file_id):
1187
1404
return tree.get_file(file_id).readlines()
1378
1610
supports_reverse_cherrypick = False
1379
1611
history_based = True
1381
def _merged_lines(self, file_id):
1382
"""Generate the merged lines.
1383
There is no distinction between lines that are meant to contain <<<<<<<
1387
base = self.base_tree
1390
plan = self.this_tree.plan_file_merge(file_id, self.other_tree,
1613
def _generate_merge_plan(self, file_id, base):
1614
return self.this_tree.plan_file_merge(file_id, self.other_tree,
1617
def _merged_lines(self, file_id):
1618
"""Generate the merged lines.
1619
There is no distinction between lines that are meant to contain <<<<<<<
1623
base = self.base_tree
1626
plan = self._generate_merge_plan(file_id, base)
1392
1627
if 'merge' in debug.debug_flags:
1393
1628
plan = list(plan)
1394
1629
trans_id = self.tt.trans_id_file_id(file_id)
1395
1630
name = self.tt.final_name(trans_id) + '.plan'
1396
contents = ('%10s|%s' % l for l in plan)
1631
contents = ('%11s|%s' % l for l in plan)
1397
1632
self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
1398
1633
textmerge = versionedfile.PlanWeaveMerge(plan, '<<<<<<< TREE\n',
1399
1634
'>>>>>>> MERGE-SOURCE\n')
1400
return textmerge.merge_lines(self.reprocess)
1635
lines, conflicts = textmerge.merge_lines(self.reprocess)
1637
base_lines = textmerge.base_from_plan()
1640
return lines, base_lines
1402
1642
def text_merge(self, file_id, trans_id):
1403
1643
"""Perform a (weave) text merge for a given file and file-id.
1404
1644
If conflicts are encountered, .THIS and .OTHER files will be emitted,
1405
1645
and a conflict will be noted.
1407
lines, conflicts = self._merged_lines(file_id)
1647
lines, base_lines = self._merged_lines(file_id)
1408
1648
lines = list(lines)
1409
1649
# Note we're checking whether the OUTPUT is binary in this case,
1410
1650
# because we don't want to get into weave merge guts.
1411
1651
textfile.check_text_lines(lines)
1412
1652
self.tt.create_file(lines, trans_id)
1653
if base_lines is not None:
1414
1655
self._raw_conflicts.append(('text conflict', trans_id))
1415
1656
name = self.tt.final_name(trans_id)
1416
1657
parent_id = self.tt.final_parent(trans_id)
1417
1658
file_group = self._dump_conflicts(name, parent_id, file_id,
1660
base_lines=base_lines)
1419
1661
file_group.append(trans_id)
1422
1664
class LCAMerger(WeaveMerger):
1424
def _merged_lines(self, file_id):
1425
"""Generate the merged lines.
1426
There is no distinction between lines that are meant to contain <<<<<<<
1430
base = self.base_tree
1433
plan = self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
1666
def _generate_merge_plan(self, file_id, base):
1667
return self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
1435
if 'merge' in debug.debug_flags:
1437
trans_id = self.tt.trans_id_file_id(file_id)
1438
name = self.tt.final_name(trans_id) + '.plan'
1439
contents = ('%10s|%s' % l for l in plan)
1440
self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
1441
textmerge = versionedfile.PlanWeaveMerge(plan, '<<<<<<< TREE\n',
1442
'>>>>>>> MERGE-SOURCE\n')
1443
return textmerge.merge_lines(self.reprocess)
1446
1670
class Diff3Merger(Merge3Merger):
1447
1671
"""Three-way merger using external diff3 for text merging"""