/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: Aaron Bentley
  • Date: 2005-08-11 19:54:55 UTC
  • mto: (1092.1.41) (1185.3.4) (974.1.47)
  • mto: This revision was merged to the branch mainline in revision 1110.
  • Revision ID: abentley@panoramicfeedback.com-20050811195455-91f52bb566728ac7
Fixed spurious new_contents_conflict

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
5
import bzrlib.osutils
 
6
from bzrlib.errors import BzrCommandError
 
7
from bzrlib.diff import compare_trees
 
8
from trace import mutter, warning
 
9
import os.path
 
10
import tempfile
 
11
import shutil
 
12
import errno
 
13
 
 
14
class UnrelatedBranches(BzrCommandError):
 
15
    def __init__(self):
 
16
        msg = "Branches have no common ancestor, and no base revision"\
 
17
            " specified."
 
18
        BzrCommandError.__init__(self, msg)
 
19
 
 
20
 
 
21
class MergeConflictHandler(ExceptionConflictHandler):
 
22
    """Handle conflicts encountered while merging"""
 
23
    def __init__(self, dir, ignore_zero=False):
 
24
        ExceptionConflictHandler.__init__(self, dir)
 
25
        self.conflicts = 0
 
26
        self.ignore_zero = ignore_zero
 
27
 
 
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
 
32
        """
 
33
        s_file = file(source, "rb")
 
34
        d_file = file(dest, "wb")
 
35
        for line in s_file:
 
36
            d_file.write(line)
 
37
        os.chmod(dest, 0777 & os.stat(source).st_mode)
 
38
 
 
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
 
43
        """
 
44
        d_file = file(dest, "wb")
 
45
        for line in lines:
 
46
            d_file.write(line)
 
47
 
 
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
 
51
 
 
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
 
55
        """
 
56
        if last_new_name is None:
 
57
            last_new_name = name
 
58
        new_name = last_new_name+suffix
 
59
        try:
 
60
            os.rename(name, new_name)
 
61
            return new_name
 
62
        except OSError, e:
 
63
            if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
 
64
                raise
 
65
            return self.add_suffix(name, suffix, last_new_name=new_name)
 
66
 
 
67
    def conflict(self, text):
 
68
        warning(text)
 
69
        self.conflicts += 1
 
70
        
 
71
 
 
72
    def merge_conflict(self, new_file, this_path, base_lines, other_lines):
 
73
        """
 
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
 
80
        """
 
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)
 
86
 
 
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))
 
91
 
 
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"\
 
95
            % filename)
 
96
        return "skip"
 
97
 
 
98
    def finalize(self):
 
99
        if not self.ignore_zero:
 
100
            print "%d conflicts encountered.\n" % self.conflicts
 
101
            
 
102
def get_tree(treespec, temp_root, label):
 
103
    location, revno = treespec
 
104
    branch = find_branch(location)
 
105
    if revno is None:
 
106
        base_tree = branch.working_tree()
 
107
    elif revno == -1:
 
108
        base_tree = branch.basis_tree()
 
109
    else:
 
110
        base_tree = branch.revision_tree(branch.lookup_revision(revno))
 
111
    temp_path = os.path.join(temp_root, label)
 
112
    os.mkdir(temp_path)
 
113
    return branch, MergeTree(base_tree, temp_path)
 
114
 
 
115
 
 
116
def file_exists(tree, file_id):
 
117
    return tree.has_filename(tree.id2path(file_id))
 
118
    
 
119
 
 
120
class MergeTree(object):
 
121
    def __init__(self, tree, tempdir):
 
122
        object.__init__(self)
 
123
        if hasattr(tree, "basedir"):
 
124
            self.root = tree.basedir
 
125
        else:
 
126
            self.root = None
 
127
        self.tree = tree
 
128
        self.tempdir = tempdir
 
129
        os.mkdir(os.path.join(self.tempdir, "texts"))
 
130
        self.cached = {}
 
131
 
 
132
    def __iter__(self):
 
133
        return self.tree.__iter__()
 
134
 
 
135
    def __contains__(self, file_id):
 
136
        return file_id in self.tree
 
137
 
 
138
    def get_file(self, file_id):
 
139
        return self.tree.get_file(file_id)
 
140
 
 
141
    def get_file_sha1(self, id):
 
142
        return self.tree.get_file_sha1(id)
 
143
 
 
144
    def id2path(self, file_id):
 
145
        return self.tree.id2path(file_id)
 
146
 
 
147
    def has_id(self, file_id):
 
148
        return self.tree.has_id(file_id)
 
149
 
 
150
    def readonly_path(self, id):
 
151
        if id not in self.tree:
 
152
            return None
 
153
        if self.root is not None:
 
154
            return self.tree.abspath(self.tree.id2path(id))
 
155
        else:
 
156
            if self.tree.inventory[id].kind in ("directory", "root_directory"):
 
157
                return self.tempdir
 
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]
 
165
 
 
166
 
 
167
 
 
168
def merge(other_revision, base_revision,
 
169
          check_clean=True, ignore_zero=False,
 
170
          this_dir=None, backup_files=False, merge_type=ApplyMerge3,
 
171
          file_list=None):
 
172
    """Merge changes into a tree.
 
173
 
 
174
    base_revision
 
175
        Base for three-way merge.
 
176
    other_revision
 
177
        Other revision for three-way merge.
 
178
    this_dir
 
179
        Directory to merge changes into; '.' by default.
 
180
    check_clean
 
181
        If true, this_dir must have no uncommitted changes before the
 
182
        merge begins.
 
183
    """
 
184
    tempdir = tempfile.mkdtemp(prefix="bzr-")
 
185
    try:
 
186
        if this_dir is None:
 
187
            this_dir = '.'
 
188
        this_branch = find_branch(this_dir)
 
189
        if check_clean:
 
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:
 
197
                o_revno = None
 
198
            else:
 
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
 
208
        else:
 
209
            interesting_ids = set()
 
210
            this_tree = this_branch.working_tree()
 
211
            for fname in file_list:
 
212
                path = this_branch.relpath(fname)
 
213
                found_id = False
 
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)
 
218
                        found_id = True
 
219
                if not found_id:
 
220
                    raise BzrCommandError("%s is not a source file in any"
 
221
                                          " tree." % fname)
 
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)
 
225
    finally:
 
226
        shutil.rmtree(tempdir)
 
227
 
 
228
 
 
229
def set_interesting(inventory_a, inventory_b, interesting_ids):
 
230
    """Mark files whose ids are in interesting_ids as interesting
 
231
    """
 
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
 
235
 
 
236
 
 
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.
 
240
    """ 
 
241
    cset =  generate_changeset(tree_a, tree_b, interesting_ids)
 
242
    for entry in cset.entries.itervalues():
 
243
        entry.metadata_change = None
 
244
    return cset
 
245
 
 
246
 
 
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):
 
250
 
 
251
    def merge_factory(file_id, base, other):
 
252
        contents_change = merge_type(file_id, base, other)
 
253
        if backup_files:
 
254
            contents_change = BackupBeforeChange(contents_change)
 
255
        return contents_change
 
256
 
 
257
    this_tree = get_tree((this_branch.base, None), tempdir, "this")[1]
 
258
 
 
259
    def get_inventory(tree):
 
260
        return tree.tree.inventory
 
261
 
 
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)
 
268
 
 
269
    adjust_ids = []
 
270
    for id, path in inv_changes.iteritems():
 
271
        if path is not None:
 
272
            if path == '.':
 
273
                path = ''
 
274
            else:
 
275
                assert path.startswith('./'), "path is %s" % path
 
276
            path = path[2:]
 
277
        adjust_ids.append((path, id))
 
278
    if len(adjust_ids) > 0:
 
279
        this_branch.set_inventory(regen_inventory(this_branch, this_tree.root,
 
280
                                                  adjust_ids))
 
281
 
 
282
 
 
283
def regen_inventory(this_branch, root, new_entries):
 
284
    old_entries = this_branch.read_working_inventory()
 
285
    new_inventory = {}
 
286
    by_path = {}
 
287
    new_entries_map = {} 
 
288
    for path, file_id in new_entries:
 
289
        if path is None:
 
290
            continue
 
291
        new_entries_map[file_id] = path
 
292
 
 
293
    def id2path(file_id):
 
294
        path = new_entries_map.get(file_id)
 
295
        if path is not None:
 
296
            return path
 
297
        entry = old_entries[file_id]
 
298
        if entry.parent_id is None:
 
299
            return entry.name
 
300
        return os.path.join(id2path(entry.parent_id), entry.name)
 
301
        
 
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
 
307
    
 
308
    deletions = 0
 
309
    insertions = 0
 
310
    new_path_list = []
 
311
    for path, file_id in new_entries:
 
312
        if path is None:
 
313
            del new_inventory[file_id]
 
314
            deletions += 1
 
315
        else:
 
316
            new_path_list.append((path, file_id))
 
317
            if file_id not in old_entries:
 
318
                insertions += 1
 
319
    # Ensure no file is added before its parent
 
320
    new_path_list.sort()
 
321
    for path, file_id in new_path_list:
 
322
        if path == '':
 
323
            parent = None
 
324
        else:
 
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 
 
329
 
 
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
 
338
 
 
339
merge_types = {     "merge3": (ApplyMerge3, "Native diff3-style merge"), 
 
340
                     "diff3": (Diff3Merge,  "Merge using external diff3")
 
341
              }
 
342