1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
revision as _mod_revision,
28
from bzrlib.branch import Branch
29
from bzrlib.conflicts import ConflictList, Conflict
30
from bzrlib.errors import (BzrCommandError,
40
WorkingTreeNotRevision,
43
from bzrlib.merge3 import Merge3
44
from bzrlib.osutils import rename, pathjoin
45
from progress import DummyProgress, ProgressPhase
46
from bzrlib.revision import (is_ancestor, NULL_REVISION, ensure_null)
47
from bzrlib.textfile import check_text_lines
48
from bzrlib.trace import mutter, warning, note
49
from bzrlib.transform import (TreeTransform, resolve_conflicts, cook_conflicts,
50
conflict_pass, FinalPaths, create_by_entry,
51
unique_add, ROOT_PARENT)
52
from bzrlib.versionedfile import WeaveMerge
55
# TODO: Report back as changes are merged in
58
def transform_tree(from_tree, to_tree, interesting_ids=None):
59
merge_inner(from_tree.branch, to_tree, from_tree, ignore_zero=True,
60
interesting_ids=interesting_ids, this_tree=from_tree)
64
def __init__(self, this_branch, other_tree=None, base_tree=None,
65
this_tree=None, pb=DummyProgress(), change_reporter=None,
68
assert this_tree is not None, "this_tree is required"
69
self.this_branch = this_branch
70
self.this_basis = _mod_revision.ensure_null(
71
this_branch.last_revision())
72
self.this_rev_id = None
73
self.this_tree = this_tree
74
self.this_revision_tree = None
75
self.this_basis_tree = None
76
self.other_tree = other_tree
77
self.other_branch = None
78
self.base_tree = base_tree
79
self.ignore_zero = False
80
self.backup_files = False
81
self.interesting_ids = None
82
self.interesting_files = None
83
self.show_base = False
84
self.reprocess = False
87
self.recurse = recurse
88
self.change_reporter = change_reporter
89
self._cached_trees = {}
91
def revision_tree(self, revision_id, branch=None):
92
if revision_id not in self._cached_trees:
94
branch = self.this_branch
96
tree = self.this_tree.revision_tree(revision_id)
97
except errors.NoSuchRevisionInTree:
98
tree = branch.repository.revision_tree(revision_id)
99
self._cached_trees[revision_id] = tree
100
return self._cached_trees[revision_id]
102
def _get_tree(self, treespec):
103
from bzrlib import workingtree
104
location, revno = treespec
106
tree = workingtree.WorkingTree.open_containing(location)[0]
107
return tree.branch, tree
108
branch = Branch.open_containing(location)[0]
110
revision_id = branch.last_revision()
112
revision_id = branch.get_rev_id(revno)
113
revision_id = ensure_null(revision_id)
114
return branch, self.revision_tree(revision_id, branch)
116
def ensure_revision_trees(self):
117
if self.this_revision_tree is None:
118
self.this_basis_tree = self.revision_tree(self.this_basis)
119
if self.this_basis == self.this_rev_id:
120
self.this_revision_tree = self.this_basis_tree
122
if self.other_rev_id is None:
123
other_basis_tree = self.revision_tree(self.other_basis)
124
changes = other_basis_tree.changes_from(self.other_tree)
125
if changes.has_changed():
126
raise WorkingTreeNotRevision(self.this_tree)
127
other_rev_id = self.other_basis
128
self.other_tree = other_basis_tree
130
def file_revisions(self, file_id):
131
self.ensure_revision_trees()
132
def get_id(tree, file_id):
133
revision_id = tree.inventory[file_id].revision
134
assert revision_id is not None
136
if self.this_rev_id is None:
137
if self.this_basis_tree.get_file_sha1(file_id) != \
138
self.this_tree.get_file_sha1(file_id):
139
raise WorkingTreeNotRevision(self.this_tree)
141
trees = (self.this_basis_tree, self.other_tree)
142
return [get_id(tree, file_id) for tree in trees]
144
def check_basis(self, check_clean, require_commits=True):
145
if self.this_basis is None and require_commits is True:
146
raise BzrCommandError("This branch has no commits."
147
" (perhaps you would prefer 'bzr pull')")
150
if self.this_basis != self.this_rev_id:
151
raise BzrCommandError("Working tree has uncommitted changes.")
153
def compare_basis(self):
155
basis_tree = self.revision_tree(self.this_tree.last_revision())
156
except errors.RevisionNotPresent:
157
basis_tree = self.this_tree.basis_tree()
158
changes = self.this_tree.changes_from(basis_tree)
159
if not changes.has_changed():
160
self.this_rev_id = self.this_basis
162
def set_interesting_files(self, file_list):
163
self.interesting_files = file_list
165
def set_pending(self):
166
if not self.base_is_ancestor or not self.base_is_other_ancestor:
170
def _add_parent(self):
171
new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
172
new_parent_trees = []
173
for revision_id in new_parents:
175
tree = self.revision_tree(revision_id)
176
except errors.RevisionNotPresent:
180
new_parent_trees.append((revision_id, tree))
182
self.this_tree.set_parent_trees(new_parent_trees,
183
allow_leftmost_as_ghost=True)
185
for _revision_id, tree in new_parent_trees:
189
def set_other(self, other_revision):
190
"""Set the revision and tree to merge from.
192
This sets the other_tree, other_rev_id, other_basis attributes.
194
:param other_revision: The [path, revision] list to merge from.
196
self.other_branch, self.other_tree = self._get_tree(other_revision)
197
if other_revision[1] == -1:
198
self.other_rev_id = _mod_revision.ensure_null(
199
self.other_branch.last_revision())
200
if _mod_revision.is_null(self.other_rev_id):
201
raise NoCommits(self.other_branch)
202
self.other_basis = self.other_rev_id
203
elif other_revision[1] is not None:
204
self.other_rev_id = self.other_branch.get_rev_id(other_revision[1])
205
self.other_basis = self.other_rev_id
207
self.other_rev_id = None
208
self.other_basis = self.other_branch.last_revision()
209
if self.other_basis is None:
210
raise NoCommits(self.other_branch)
211
if self.other_rev_id is not None:
212
self._cached_trees[self.other_rev_id] = self.other_tree
213
self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
215
def set_other_revision(self, revision_id, other_branch):
216
"""Set 'other' based on a branch and revision id
218
:param revision_id: The revision to use for a tree
219
:param other_branch: The branch containing this tree
221
self.other_rev_id = revision_id
222
self.other_branch = other_branch
223
self._maybe_fetch(other_branch, self.this_branch, self.other_rev_id)
224
self.other_tree = self.revision_tree(revision_id)
225
self.other_basis = revision_id
227
def _maybe_fetch(self, source, target, revision_id):
228
if (source.repository.bzrdir.root_transport.base !=
229
target.repository.bzrdir.root_transport.base):
230
target.fetch(source, revision_id)
233
this_repo = self.this_branch.repository
234
graph = this_repo.get_graph()
235
revisions = [ensure_null(self.this_basis),
236
ensure_null(self.other_basis)]
237
if NULL_REVISION in revisions:
238
self.base_rev_id = NULL_REVISION
240
self.base_rev_id = graph.find_unique_lca(*revisions)
241
if self.base_rev_id == NULL_REVISION:
242
raise UnrelatedBranches()
243
self.base_tree = self.revision_tree(self.base_rev_id)
244
self.base_is_ancestor = True
245
self.base_is_other_ancestor = True
247
def set_base(self, base_revision):
248
"""Set the base revision to use for the merge.
250
:param base_revision: A 2-list containing a path and revision number.
252
mutter("doing merge() with no base_revision specified")
253
if base_revision == [None, None]:
256
base_branch, self.base_tree = self._get_tree(base_revision)
257
if base_revision[1] == -1:
258
self.base_rev_id = base_branch.last_revision()
259
elif base_revision[1] is None:
260
self.base_rev_id = _mod_revision.NULL_REVISION
262
self.base_rev_id = _mod_revision.ensure_null(
263
base_branch.get_rev_id(base_revision[1]))
264
self._maybe_fetch(base_branch, self.this_branch, self.base_rev_id)
265
self.base_is_ancestor = is_ancestor(self.this_basis,
268
self.base_is_other_ancestor = is_ancestor(self.other_basis,
273
kwargs = {'working_tree':self.this_tree, 'this_tree': self.this_tree,
274
'other_tree': self.other_tree,
275
'interesting_ids': self.interesting_ids,
276
'interesting_files': self.interesting_files,
278
if self.merge_type.requires_base:
279
kwargs['base_tree'] = self.base_tree
280
if self.merge_type.supports_reprocess:
281
kwargs['reprocess'] = self.reprocess
283
raise BzrError("Conflict reduction is not supported for merge"
284
" type %s." % self.merge_type)
285
if self.merge_type.supports_show_base:
286
kwargs['show_base'] = self.show_base
288
raise BzrError("Showing base is not supported for this"
289
" merge type. %s" % self.merge_type)
290
self.this_tree.lock_tree_write()
291
if self.base_tree is not None:
292
self.base_tree.lock_read()
293
if self.other_tree is not None:
294
self.other_tree.lock_read()
296
merge = self.merge_type(pb=self._pb,
297
change_reporter=self.change_reporter,
299
if self.recurse == 'down':
300
for path, file_id in self.this_tree.iter_references():
301
sub_tree = self.this_tree.get_nested_tree(file_id, path)
302
other_revision = self.other_tree.get_reference_revision(
304
if other_revision == sub_tree.last_revision():
306
sub_merge = Merger(sub_tree.branch, this_tree=sub_tree)
307
sub_merge.merge_type = self.merge_type
308
relpath = self.this_tree.relpath(path)
309
other_branch = self.other_branch.reference_parent(file_id, relpath)
310
sub_merge.set_other_revision(other_revision, other_branch)
311
base_revision = self.base_tree.get_reference_revision(file_id)
312
sub_merge.base_tree = \
313
sub_tree.branch.repository.revision_tree(base_revision)
317
if self.other_tree is not None:
318
self.other_tree.unlock()
319
if self.base_tree is not None:
320
self.base_tree.unlock()
321
self.this_tree.unlock()
322
if len(merge.cooked_conflicts) == 0:
323
if not self.ignore_zero:
324
note("All changes applied successfully.")
326
note("%d conflicts encountered." % len(merge.cooked_conflicts))
328
return len(merge.cooked_conflicts)
331
class Merge3Merger(object):
332
"""Three-way merger that uses the merge3 text merger"""
334
supports_reprocess = True
335
supports_show_base = True
336
history_based = False
337
winner_idx = {"this": 2, "other": 1, "conflict": 1}
339
def __init__(self, working_tree, this_tree, base_tree, other_tree,
340
interesting_ids=None, reprocess=False, show_base=False,
341
pb=DummyProgress(), pp=None, change_reporter=None,
342
interesting_files=None):
343
"""Initialize the merger object and perform the merge.
345
:param working_tree: The working tree to apply the merge to
346
:param this_tree: The local tree in the merge operation
347
:param base_tree: The common tree in the merge operation
348
:param other_tree: The other other tree to merge changes from
349
:param interesting_ids: The file_ids of files that should be
350
participate in the merge. May not be combined with
352
:param: reprocess If True, perform conflict-reduction processing.
353
:param show_base: If True, show the base revision in text conflicts.
354
(incompatible with reprocess)
355
:param pb: A Progress bar
356
:param pp: A ProgressPhase object
357
:param change_reporter: An object that should report changes made
358
:param interesting_files: The tree-relative paths of files that should
359
participate in the merge. If these paths refer to directories,
360
the contents of those directories will also be included. May not
361
be combined with interesting_ids. If neither interesting_files nor
362
interesting_ids is specified, all files may participate in the
365
object.__init__(self)
366
if interesting_files is not None:
367
assert interesting_ids is None
368
self.interesting_ids = interesting_ids
369
self.interesting_files = interesting_files
370
self.this_tree = working_tree
371
self.this_tree.lock_tree_write()
372
self.base_tree = base_tree
373
self.base_tree.lock_read()
374
self.other_tree = other_tree
375
self.other_tree.lock_read()
376
self._raw_conflicts = []
377
self.cooked_conflicts = []
378
self.reprocess = reprocess
379
self.show_base = show_base
382
self.change_reporter = change_reporter
384
self.pp = ProgressPhase("Merge phase", 3, self.pb)
386
self.tt = TreeTransform(working_tree, self.pb)
389
entries = self._entries3()
390
child_pb = ui.ui_factory.nested_progress_bar()
392
for num, (file_id, changed, parents3, names3,
393
executable3) in enumerate(entries):
394
child_pb.update('Preparing file merge', num, len(entries))
395
self._merge_names(file_id, parents3, names3)
397
file_status = self.merge_contents(file_id)
399
file_status = 'unmodified'
400
self._merge_executable(file_id,
401
executable3, file_status)
406
child_pb = ui.ui_factory.nested_progress_bar()
408
fs_conflicts = resolve_conflicts(self.tt, child_pb,
409
lambda t, c: conflict_pass(t, c, self.other_tree))
412
if change_reporter is not None:
413
from bzrlib import delta
414
delta.report_changes(self.tt._iter_changes(), change_reporter)
415
self.cook_conflicts(fs_conflicts)
416
for conflict in self.cooked_conflicts:
419
results = self.tt.apply(no_conflicts=True)
420
self.write_modified(results)
422
working_tree.add_conflicts(self.cooked_conflicts)
423
except UnsupportedOperation:
427
self.other_tree.unlock()
428
self.base_tree.unlock()
429
self.this_tree.unlock()
433
"""Gather data about files modified between three trees.
435
Return a list of tuples of file_id, changed, parents3, names3,
436
executable3. changed is a boolean indicating whether the file contents
437
or kind were changed. parents3 is a tuple of parent ids for base,
438
other and this. names3 is a tuple of names for base, other and this.
439
executable3 is a tuple of execute-bit values for base, other and this.
442
iterator = self.other_tree._iter_changes(self.base_tree,
443
include_unchanged=True, specific_files=self.interesting_files,
444
extra_trees=[self.this_tree])
445
for (file_id, paths, changed, versioned, parents, names, kind,
446
executable) in iterator:
447
if (self.interesting_ids is not None and
448
file_id not in self.interesting_ids):
450
if file_id in self.this_tree.inventory:
451
entry = self.this_tree.inventory[file_id]
452
this_name = entry.name
453
this_parent = entry.parent_id
454
this_executable = entry.executable
458
this_executable = None
459
parents3 = parents + (this_parent,)
460
names3 = names + (this_name,)
461
executable3 = executable + (this_executable,)
462
result.append((file_id, changed, parents3, names3, executable3))
467
self.tt.final_kind(self.tt.root)
469
self.tt.cancel_deletion(self.tt.root)
470
if self.tt.final_file_id(self.tt.root) is None:
471
self.tt.version_file(self.tt.tree_file_id(self.tt.root),
473
if self.other_tree.inventory.root is None:
475
other_root_file_id = self.other_tree.inventory.root.file_id
476
other_root = self.tt.trans_id_file_id(other_root_file_id)
477
if other_root == self.tt.root:
480
self.tt.final_kind(other_root)
483
self.reparent_children(self.other_tree.inventory.root, self.tt.root)
484
self.tt.cancel_creation(other_root)
485
self.tt.cancel_versioning(other_root)
487
def reparent_children(self, ie, target):
488
for thing, child in ie.children.iteritems():
489
trans_id = self.tt.trans_id_file_id(child.file_id)
490
self.tt.adjust_path(self.tt.final_name(trans_id), target, trans_id)
492
def write_modified(self, results):
494
for path in results.modified_paths:
495
file_id = self.this_tree.path2id(self.this_tree.relpath(path))
498
hash = self.this_tree.get_file_sha1(file_id)
501
modified_hashes[file_id] = hash
502
self.this_tree.set_merge_modified(modified_hashes)
505
def parent(entry, file_id):
506
"""Determine the parent for a file_id (used as a key method)"""
509
return entry.parent_id
512
def name(entry, file_id):
513
"""Determine the name for a file_id (used as a key method)"""
519
def contents_sha1(tree, file_id):
520
"""Determine the sha1 of the file contents (used as a key method)."""
521
if file_id not in tree:
523
return tree.get_file_sha1(file_id)
526
def executable(tree, file_id):
527
"""Determine the executability of a file-id (used as a key method)."""
528
if file_id not in tree:
530
if tree.kind(file_id) != "file":
532
return tree.is_executable(file_id)
535
def kind(tree, file_id):
536
"""Determine the kind of a file-id (used as a key method)."""
537
if file_id not in tree:
539
return tree.kind(file_id)
542
def _three_way(base, other, this):
543
#if base == other, either they all agree, or only THIS has changed.
546
elif this not in (base, other):
548
# "Ambiguous clean merge" -- both sides have made the same change.
551
# this == base: only other has changed.
556
def scalar_three_way(this_tree, base_tree, other_tree, file_id, key):
557
"""Do a three-way test on a scalar.
558
Return "this", "other" or "conflict", depending whether a value wins.
560
key_base = key(base_tree, file_id)
561
key_other = key(other_tree, file_id)
562
#if base == other, either they all agree, or only THIS has changed.
563
if key_base == key_other:
565
key_this = key(this_tree, file_id)
566
if key_this not in (key_base, key_other):
568
# "Ambiguous clean merge"
569
elif key_this == key_other:
572
assert key_this == key_base
575
def merge_names(self, file_id):
577
if file_id in tree.inventory:
578
return tree.inventory[file_id]
581
this_entry = get_entry(self.this_tree)
582
other_entry = get_entry(self.other_tree)
583
base_entry = get_entry(self.base_tree)
584
entries = (base_entry, other_entry, this_entry)
587
for entry in entries:
592
names.append(entry.name)
593
parents.append(entry.parent_id)
594
return self._merge_names(file_id, parents, names)
596
def _merge_names(self, file_id, parents, names):
597
"""Perform a merge on file_id names and parents"""
598
base_name, other_name, this_name = names
599
base_parent, other_parent, this_parent = parents
601
name_winner = self._three_way(*names)
603
parent_id_winner = self._three_way(*parents)
604
if this_name is None:
605
if name_winner == "this":
606
name_winner = "other"
607
if parent_id_winner == "this":
608
parent_id_winner = "other"
609
if name_winner == "this" and parent_id_winner == "this":
611
if name_winner == "conflict":
612
trans_id = self.tt.trans_id_file_id(file_id)
613
self._raw_conflicts.append(('name conflict', trans_id,
614
this_name, other_name))
615
if parent_id_winner == "conflict":
616
trans_id = self.tt.trans_id_file_id(file_id)
617
self._raw_conflicts.append(('parent conflict', trans_id,
618
this_parent, other_parent))
619
if other_name is None:
620
# it doesn't matter whether the result was 'other' or
621
# 'conflict'-- if there's no 'other', we leave it alone.
623
# if we get here, name_winner and parent_winner are set to safe values.
624
trans_id = self.tt.trans_id_file_id(file_id)
625
parent_id = parents[self.winner_idx[parent_id_winner]]
626
if parent_id is not None:
627
parent_trans_id = self.tt.trans_id_file_id(parent_id)
628
self.tt.adjust_path(names[self.winner_idx[name_winner]],
629
parent_trans_id, trans_id)
631
def merge_contents(self, file_id):
632
"""Performa a merge on file_id contents."""
633
def contents_pair(tree):
634
if file_id not in tree:
636
kind = tree.kind(file_id)
638
contents = tree.get_file_sha1(file_id)
639
elif kind == "symlink":
640
contents = tree.get_symlink_target(file_id)
643
return kind, contents
645
def contents_conflict():
646
trans_id = self.tt.trans_id_file_id(file_id)
647
name = self.tt.final_name(trans_id)
648
parent_id = self.tt.final_parent(trans_id)
649
if file_id in self.this_tree.inventory:
650
self.tt.unversion_file(trans_id)
651
if file_id in self.this_tree:
652
self.tt.delete_contents(trans_id)
653
file_group = self._dump_conflicts(name, parent_id, file_id,
655
self._raw_conflicts.append(('contents conflict', file_group))
657
# See SPOT run. run, SPOT, run.
658
# So we're not QUITE repeating ourselves; we do tricky things with
660
base_pair = contents_pair(self.base_tree)
661
other_pair = contents_pair(self.other_tree)
662
if base_pair == other_pair:
663
# OTHER introduced no changes
665
this_pair = contents_pair(self.this_tree)
666
if this_pair == other_pair:
667
# THIS and OTHER introduced the same changes
670
trans_id = self.tt.trans_id_file_id(file_id)
671
if this_pair == base_pair:
672
# only OTHER introduced changes
673
if file_id in self.this_tree:
674
# Remove any existing contents
675
self.tt.delete_contents(trans_id)
676
if file_id in self.other_tree:
677
# OTHER changed the file
678
create_by_entry(self.tt,
679
self.other_tree.inventory[file_id],
680
self.other_tree, trans_id)
681
if file_id not in self.this_tree.inventory:
682
self.tt.version_file(file_id, trans_id)
684
elif file_id in self.this_tree.inventory:
685
# OTHER deleted the file
686
self.tt.unversion_file(trans_id)
688
#BOTH THIS and OTHER introduced changes; scalar conflict
689
elif this_pair[0] == "file" and other_pair[0] == "file":
690
# THIS and OTHER are both files, so text merge. Either
691
# BASE is a file, or both converted to files, so at least we
692
# have agreement that output should be a file.
694
self.text_merge(file_id, trans_id)
696
return contents_conflict()
697
if file_id not in self.this_tree.inventory:
698
self.tt.version_file(file_id, trans_id)
700
self.tt.tree_kind(trans_id)
701
self.tt.delete_contents(trans_id)
706
# Scalar conflict, can't text merge. Dump conflicts
707
return contents_conflict()
709
def get_lines(self, tree, file_id):
710
"""Return the lines in a file, or an empty list."""
712
return tree.get_file(file_id).readlines()
716
def text_merge(self, file_id, trans_id):
717
"""Perform a three-way text merge on a file_id"""
718
# it's possible that we got here with base as a different type.
719
# if so, we just want two-way text conflicts.
720
if file_id in self.base_tree and \
721
self.base_tree.kind(file_id) == "file":
722
base_lines = self.get_lines(self.base_tree, file_id)
725
other_lines = self.get_lines(self.other_tree, file_id)
726
this_lines = self.get_lines(self.this_tree, file_id)
727
m3 = Merge3(base_lines, this_lines, other_lines)
728
start_marker = "!START OF MERGE CONFLICT!" + "I HOPE THIS IS UNIQUE"
729
if self.show_base is True:
730
base_marker = '|' * 7
734
def iter_merge3(retval):
735
retval["text_conflicts"] = False
736
for line in m3.merge_lines(name_a = "TREE",
737
name_b = "MERGE-SOURCE",
738
name_base = "BASE-REVISION",
739
start_marker=start_marker,
740
base_marker=base_marker,
741
reprocess=self.reprocess):
742
if line.startswith(start_marker):
743
retval["text_conflicts"] = True
744
yield line.replace(start_marker, '<' * 7)
748
merge3_iterator = iter_merge3(retval)
749
self.tt.create_file(merge3_iterator, trans_id)
750
if retval["text_conflicts"] is True:
751
self._raw_conflicts.append(('text conflict', trans_id))
752
name = self.tt.final_name(trans_id)
753
parent_id = self.tt.final_parent(trans_id)
754
file_group = self._dump_conflicts(name, parent_id, file_id,
755
this_lines, base_lines,
757
file_group.append(trans_id)
759
def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
760
base_lines=None, other_lines=None, set_version=False,
762
"""Emit conflict files.
763
If this_lines, base_lines, or other_lines are omitted, they will be
764
determined automatically. If set_version is true, the .OTHER, .THIS
765
or .BASE (in that order) will be created as versioned files.
767
data = [('OTHER', self.other_tree, other_lines),
768
('THIS', self.this_tree, this_lines)]
770
data.append(('BASE', self.base_tree, base_lines))
773
for suffix, tree, lines in data:
775
trans_id = self._conflict_file(name, parent_id, tree, file_id,
777
file_group.append(trans_id)
778
if set_version and not versioned:
779
self.tt.version_file(file_id, trans_id)
783
def _conflict_file(self, name, parent_id, tree, file_id, suffix,
785
"""Emit a single conflict file."""
786
name = name + '.' + suffix
787
trans_id = self.tt.create_path(name, parent_id)
788
entry = tree.inventory[file_id]
789
create_by_entry(self.tt, entry, tree, trans_id, lines)
792
def merge_executable(self, file_id, file_status):
793
"""Perform a merge on the execute bit."""
794
executable = [self.executable(t, file_id) for t in (self.base_tree,
795
self.other_tree, self.this_tree)]
796
self._merge_executable(file_id, executable, file_status)
798
def _merge_executable(self, file_id, executable, file_status):
799
"""Perform a merge on the execute bit."""
800
base_executable, other_executable, this_executable = executable
801
if file_status == "deleted":
803
trans_id = self.tt.trans_id_file_id(file_id)
805
if self.tt.final_kind(trans_id) != "file":
809
winner = self._three_way(*executable)
810
if winner == "conflict":
811
# There must be a None in here, if we have a conflict, but we
812
# need executability since file status was not deleted.
813
if self.executable(self.other_tree, file_id) is None:
818
if file_status == "modified":
819
executability = this_executable
820
if executability is not None:
821
trans_id = self.tt.trans_id_file_id(file_id)
822
self.tt.set_executability(executability, trans_id)
824
assert winner == "other"
825
if file_id in self.other_tree:
826
executability = other_executable
827
elif file_id in self.this_tree:
828
executability = this_executable
829
elif file_id in self.base_tree:
830
executability = base_executable
831
if executability is not None:
832
trans_id = self.tt.trans_id_file_id(file_id)
833
self.tt.set_executability(executability, trans_id)
835
def cook_conflicts(self, fs_conflicts):
836
"""Convert all conflicts into a form that doesn't depend on trans_id"""
837
from conflicts import Conflict
839
self.cooked_conflicts.extend(cook_conflicts(fs_conflicts, self.tt))
840
fp = FinalPaths(self.tt)
841
for conflict in self._raw_conflicts:
842
conflict_type = conflict[0]
843
if conflict_type in ('name conflict', 'parent conflict'):
844
trans_id = conflict[1]
845
conflict_args = conflict[2:]
846
if trans_id not in name_conflicts:
847
name_conflicts[trans_id] = {}
848
unique_add(name_conflicts[trans_id], conflict_type,
850
if conflict_type == 'contents conflict':
851
for trans_id in conflict[1]:
852
file_id = self.tt.final_file_id(trans_id)
853
if file_id is not None:
855
path = fp.get_path(trans_id)
856
for suffix in ('.BASE', '.THIS', '.OTHER'):
857
if path.endswith(suffix):
858
path = path[:-len(suffix)]
860
c = Conflict.factory(conflict_type, path=path, file_id=file_id)
861
self.cooked_conflicts.append(c)
862
if conflict_type == 'text conflict':
863
trans_id = conflict[1]
864
path = fp.get_path(trans_id)
865
file_id = self.tt.final_file_id(trans_id)
866
c = Conflict.factory(conflict_type, path=path, file_id=file_id)
867
self.cooked_conflicts.append(c)
869
for trans_id, conflicts in name_conflicts.iteritems():
871
this_parent, other_parent = conflicts['parent conflict']
872
assert this_parent != other_parent
874
this_parent = other_parent = \
875
self.tt.final_file_id(self.tt.final_parent(trans_id))
877
this_name, other_name = conflicts['name conflict']
878
assert this_name != other_name
880
this_name = other_name = self.tt.final_name(trans_id)
881
other_path = fp.get_path(trans_id)
882
if this_parent is not None and this_name is not None:
884
fp.get_path(self.tt.trans_id_file_id(this_parent))
885
this_path = pathjoin(this_parent_path, this_name)
887
this_path = "<deleted>"
888
file_id = self.tt.final_file_id(trans_id)
889
c = Conflict.factory('path conflict', path=this_path,
890
conflict_path=other_path, file_id=file_id)
891
self.cooked_conflicts.append(c)
892
self.cooked_conflicts.sort(key=Conflict.sort_key)
895
class WeaveMerger(Merge3Merger):
896
"""Three-way tree merger, text weave merger."""
897
supports_reprocess = True
898
supports_show_base = False
900
def __init__(self, working_tree, this_tree, base_tree, other_tree,
901
interesting_ids=None, pb=DummyProgress(), pp=None,
902
reprocess=False, change_reporter=None,
903
interesting_files=None):
904
self.this_revision_tree = self._get_revision_tree(this_tree)
905
self.other_revision_tree = self._get_revision_tree(other_tree)
906
super(WeaveMerger, self).__init__(working_tree, this_tree,
907
base_tree, other_tree,
908
interesting_ids=interesting_ids,
909
pb=pb, pp=pp, reprocess=reprocess,
910
change_reporter=change_reporter)
912
def _get_revision_tree(self, tree):
913
"""Return a revision tree related to this tree.
914
If the tree is a WorkingTree, the basis will be returned.
916
if getattr(tree, 'get_weave', False) is False:
917
# If we have a WorkingTree, try using the basis
918
return tree.branch.basis_tree()
922
def _check_file(self, file_id):
923
"""Check that the revision tree's version of the file matches."""
924
for tree, rt in ((self.this_tree, self.this_revision_tree),
925
(self.other_tree, self.other_revision_tree)):
928
if tree.get_file_sha1(file_id) != rt.get_file_sha1(file_id):
929
raise WorkingTreeNotRevision(self.this_tree)
931
def _merged_lines(self, file_id):
932
"""Generate the merged lines.
933
There is no distinction between lines that are meant to contain <<<<<<<
936
weave = self.this_revision_tree.get_weave(file_id)
937
this_revision_id = self.this_revision_tree.inventory[file_id].revision
938
other_revision_id = \
939
self.other_revision_tree.inventory[file_id].revision
940
wm = WeaveMerge(weave, this_revision_id, other_revision_id,
941
'<<<<<<< TREE\n', '>>>>>>> MERGE-SOURCE\n')
942
return wm.merge_lines(self.reprocess)
944
def text_merge(self, file_id, trans_id):
945
"""Perform a (weave) text merge for a given file and file-id.
946
If conflicts are encountered, .THIS and .OTHER files will be emitted,
947
and a conflict will be noted.
949
self._check_file(file_id)
950
lines, conflicts = self._merged_lines(file_id)
952
# Note we're checking whether the OUTPUT is binary in this case,
953
# because we don't want to get into weave merge guts.
954
check_text_lines(lines)
955
self.tt.create_file(lines, trans_id)
957
self._raw_conflicts.append(('text conflict', trans_id))
958
name = self.tt.final_name(trans_id)
959
parent_id = self.tt.final_parent(trans_id)
960
file_group = self._dump_conflicts(name, parent_id, file_id,
962
file_group.append(trans_id)
965
class Diff3Merger(Merge3Merger):
966
"""Three-way merger using external diff3 for text merging"""
968
def dump_file(self, temp_dir, name, tree, file_id):
969
out_path = pathjoin(temp_dir, name)
970
out_file = open(out_path, "wb")
972
in_file = tree.get_file(file_id)
979
def text_merge(self, file_id, trans_id):
980
"""Perform a diff3 merge using a specified file-id and trans-id.
981
If conflicts are encountered, .BASE, .THIS. and .OTHER conflict files
982
will be dumped, and a will be conflict noted.
985
temp_dir = osutils.mkdtemp(prefix="bzr-")
987
new_file = pathjoin(temp_dir, "new")
988
this = self.dump_file(temp_dir, "this", self.this_tree, file_id)
989
base = self.dump_file(temp_dir, "base", self.base_tree, file_id)
990
other = self.dump_file(temp_dir, "other", self.other_tree, file_id)
991
status = bzrlib.patch.diff3(new_file, this, base, other)
992
if status not in (0, 1):
993
raise BzrError("Unhandled diff3 exit code")
994
f = open(new_file, 'rb')
996
self.tt.create_file(f, trans_id)
1000
name = self.tt.final_name(trans_id)
1001
parent_id = self.tt.final_parent(trans_id)
1002
self._dump_conflicts(name, parent_id, file_id)
1003
self._raw_conflicts.append(('text conflict', trans_id))
1005
osutils.rmtree(temp_dir)
1008
def merge_inner(this_branch, other_tree, base_tree, ignore_zero=False,
1010
merge_type=Merge3Merger,
1011
interesting_ids=None,
1015
interesting_files=None,
1018
change_reporter=None):
1019
"""Primary interface for merging.
1021
typical use is probably
1022
'merge_inner(branch, branch.get_revision_tree(other_revision),
1023
branch.get_revision_tree(base_revision))'
1025
if this_tree is None:
1026
raise BzrError("bzrlib.merge.merge_inner requires a this_tree "
1027
"parameter as of bzrlib version 0.8.")
1028
merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1029
pb=pb, change_reporter=change_reporter)
1030
merger.backup_files = backup_files
1031
merger.merge_type = merge_type
1032
merger.interesting_ids = interesting_ids
1033
merger.ignore_zero = ignore_zero
1034
if interesting_files:
1035
assert not interesting_ids, ('Only supply interesting_ids'
1036
' or interesting_files')
1037
merger.interesting_files = interesting_files
1038
merger.show_base = show_base
1039
merger.reprocess = reprocess
1040
merger.other_rev_id = other_rev_id
1041
merger.other_basis = other_rev_id
1042
return merger.do_merge()
1044
def get_merge_type_registry():
1045
"""Merge type registry is in bzrlib.option to avoid circular imports.
1047
This method provides a sanctioned way to retrieve it.
1049
from bzrlib import option
1050
return option._merge_type_registry