1
from merge_core import merge_flex, ApplyMerge3, BackupBeforeChange
2
from changeset import generate_changeset, ExceptionConflictHandler
3
from changeset import Inventory, Diff3Merge
4
from bzrlib import find_branch
6
from bzrlib.errors import BzrCommandError
7
from bzrlib.diff import compare_trees
8
from trace import mutter, warning
14
class UnrelatedBranches(BzrCommandError):
16
msg = "Branches have no common ancestor, and no base revision"\
18
BzrCommandError.__init__(self, msg)
21
class MergeConflictHandler(ExceptionConflictHandler):
22
"""Handle conflicts encountered while merging"""
23
def __init__(self, dir, ignore_zero=False):
24
ExceptionConflictHandler.__init__(self, dir)
26
self.ignore_zero = ignore_zero
28
def copy(self, source, dest):
29
"""Copy the text and mode of a file
30
:param source: The path of the file to copy
31
:param dest: The distination file to create
33
s_file = file(source, "rb")
34
d_file = file(dest, "wb")
37
os.chmod(dest, 0777 & os.stat(source).st_mode)
39
def dump(self, lines, dest):
40
"""Copy the text and mode of a file
41
:param source: The path of the file to copy
42
:param dest: The distination file to create
44
d_file = file(dest, "wb")
48
def add_suffix(self, name, suffix, last_new_name=None):
49
"""Rename a file to append a suffix. If the new name exists, the
50
suffix is added repeatedly until a non-existant name is found
52
:param name: The path of the file
53
:param suffix: The suffix to append
54
:param last_new_name: (used for recursive calls) the last name tried
56
if last_new_name is None:
58
new_name = last_new_name+suffix
60
os.rename(name, new_name)
63
if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
65
return self.add_suffix(name, suffix, last_new_name=new_name)
67
def conflict(self, text):
72
def merge_conflict(self, new_file, this_path, base_lines, other_lines):
74
Handle diff3 conflicts by producing a .THIS, .BASE and .OTHER. The
75
main file will be a version with diff3 conflicts.
76
:param new_file: Path to the output file with diff3 markers
77
:param this_path: Path to the file text for the THIS tree
78
:param base_path: Path to the file text for the BASE tree
79
:param other_path: Path to the file text for the OTHER tree
81
self.add_suffix(this_path, ".THIS")
82
self.dump(base_lines, this_path+".BASE")
83
self.dump(other_lines, this_path+".OTHER")
84
os.rename(new_file, this_path)
85
self.conflict("Diff3 conflict encountered in %s" % this_path)
87
def target_exists(self, entry, target, old_path):
88
"""Handle the case when the target file or dir exists"""
89
moved_path = self.add_suffix(target, ".moved")
90
self.conflict("Moved existing %s to %s" % (target, moved_path))
92
def rmdir_non_empty(self, filename):
93
"""Handle the case where the dir to be removed still has contents"""
94
self.conflict("Directory %s not removed because it is not empty"\
99
if not self.ignore_zero:
100
print "%d conflicts encountered.\n" % self.conflicts
102
def get_tree(treespec, temp_root, label):
103
location, revno = treespec
104
branch = find_branch(location)
106
base_tree = branch.working_tree()
108
base_tree = branch.basis_tree()
110
base_tree = branch.revision_tree(branch.lookup_revision(revno))
111
temp_path = os.path.join(temp_root, label)
113
return branch, MergeTree(base_tree, temp_path)
116
def file_exists(tree, file_id):
117
return tree.has_filename(tree.id2path(file_id))
120
class MergeTree(object):
121
def __init__(self, tree, tempdir):
122
object.__init__(self)
123
if hasattr(tree, "basedir"):
124
self.root = tree.basedir
128
self.tempdir = tempdir
129
os.mkdir(os.path.join(self.tempdir, "texts"))
133
return self.tree.__iter__()
135
def __contains__(self, file_id):
136
return file_id in self.tree
138
def get_file(self, file_id):
139
return self.tree.get_file(file_id)
141
def get_file_sha1(self, id):
142
return self.tree.get_file_sha1(id)
144
def id2path(self, file_id):
145
return self.tree.id2path(file_id)
147
def has_id(self, file_id):
148
return self.tree.has_id(file_id)
150
def readonly_path(self, id):
151
if id not in self.tree:
153
if self.root is not None:
154
return self.tree.abspath(self.tree.id2path(id))
156
if self.tree.inventory[id].kind in ("directory", "root_directory"):
158
if not self.cached.has_key(id):
159
path = os.path.join(self.tempdir, "texts", id)
160
outfile = file(path, "wb")
161
outfile.write(self.tree.get_file(id).read())
162
assert(os.path.exists(path))
163
self.cached[id] = path
164
return self.cached[id]
168
def merge(other_revision, base_revision,
169
check_clean=True, ignore_zero=False,
170
this_dir=None, backup_files=False, merge_type=ApplyMerge3,
172
"""Merge changes into a tree.
175
Base for three-way merge.
177
Other revision for three-way merge.
179
Directory to merge changes into; '.' by default.
181
If true, this_dir must have no uncommitted changes before the
184
tempdir = tempfile.mkdtemp(prefix="bzr-")
188
this_branch = find_branch(this_dir)
190
changes = compare_trees(this_branch.working_tree(),
191
this_branch.basis_tree(), False)
192
if changes.has_changed():
193
raise BzrCommandError("Working tree has uncommitted changes.")
194
other_branch, other_tree = get_tree(other_revision, tempdir, "other")
195
if base_revision == [None, None]:
196
if other_revision[1] == -1:
199
o_revno = other_revision[1]
200
base_revno = this_branch.common_ancestor(other_branch,
201
other_revno=o_revno)[0]
202
if base_revno is None:
203
raise UnrelatedBranches()
204
base_revision = ['.', base_revno]
205
base_branch, base_tree = get_tree(base_revision, tempdir, "base")
206
if file_list is None:
207
interesting_ids = None
209
interesting_ids = set()
210
this_tree = this_branch.working_tree()
211
for fname in file_list:
212
path = this_branch.relpath(fname)
214
for tree in (this_tree, base_tree.tree, other_tree.tree):
215
file_id = tree.inventory.path2id(path)
216
if file_id is not None:
217
interesting_ids.add(file_id)
220
raise BzrCommandError("%s is not a source file in any"
222
merge_inner(this_branch, other_tree, base_tree, tempdir,
223
ignore_zero=ignore_zero, backup_files=backup_files,
224
merge_type=merge_type, interesting_ids=interesting_ids)
226
shutil.rmtree(tempdir)
229
def set_interesting(inventory_a, inventory_b, interesting_ids):
230
"""Mark files whose ids are in interesting_ids as interesting
232
for inventory in (inventory_a, inventory_b):
233
for path, source_file in inventory.iteritems():
234
source_file.interesting = source_file.id in interesting_ids
237
def generate_cset_optimized(tree_a, tree_b, interesting_ids=None):
238
"""Generate a changeset. If interesting_ids is supplied, only changes
239
to those files will be shown. Metadata changes are stripped.
241
cset = generate_changeset(tree_a, tree_b, interesting_ids)
242
for entry in cset.entries.itervalues():
243
entry.metadata_change = None
247
def merge_inner(this_branch, other_tree, base_tree, tempdir,
248
ignore_zero=False, merge_type=ApplyMerge3, backup_files=False,
249
interesting_ids=None):
251
def merge_factory(file_id, base, other):
252
contents_change = merge_type(file_id, base, other)
254
contents_change = BackupBeforeChange(contents_change)
255
return contents_change
257
this_tree = get_tree((this_branch.base, None), tempdir, "this")[1]
259
def get_inventory(tree):
260
return tree.tree.inventory
262
inv_changes = merge_flex(this_tree, base_tree, other_tree,
263
generate_cset_optimized, get_inventory,
264
MergeConflictHandler(base_tree.root,
265
ignore_zero=ignore_zero),
266
merge_factory=merge_factory,
267
interesting_ids=interesting_ids)
270
for id, path in inv_changes.iteritems():
275
assert path.startswith('./'), "path is %s" % path
277
adjust_ids.append((path, id))
278
if len(adjust_ids) > 0:
279
this_branch.set_inventory(regen_inventory(this_branch, this_tree.root,
283
def regen_inventory(this_branch, root, new_entries):
284
old_entries = this_branch.read_working_inventory()
288
for path, file_id in new_entries:
291
new_entries_map[file_id] = path
293
def id2path(file_id):
294
path = new_entries_map.get(file_id)
297
entry = old_entries[file_id]
298
if entry.parent_id is None:
300
return os.path.join(id2path(entry.parent_id), entry.name)
302
for file_id in old_entries:
303
entry = old_entries[file_id]
304
path = id2path(file_id)
305
new_inventory[file_id] = (path, file_id, entry.parent_id, entry.kind)
306
by_path[path] = file_id
311
for path, file_id in new_entries:
313
del new_inventory[file_id]
316
new_path_list.append((path, file_id))
317
if file_id not in old_entries:
319
# Ensure no file is added before its parent
321
for path, file_id in new_path_list:
325
parent = by_path[os.path.dirname(path)]
326
kind = bzrlib.osutils.file_kind(os.path.join(root, path))
327
new_inventory[file_id] = (path, file_id, parent, kind)
328
by_path[path] = file_id
330
# Get a list in insertion order
331
new_inventory_list = new_inventory.values()
332
mutter ("""Inventory regeneration:
333
old length: %i insertions: %i deletions: %i new_length: %i"""\
334
% (len(old_entries), insertions, deletions, len(new_inventory_list)))
335
assert len(new_inventory_list) == len(old_entries) + insertions - deletions
336
new_inventory_list.sort()
337
return new_inventory_list
339
merge_types = { "merge3": (ApplyMerge3, "Native diff3-style merge"),
340
"diff3": (Diff3Merge, "Merge using external diff3")