/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
493 by Martin Pool
- Merge aaron's merge command
1
from merge_core import merge_flex
2
from changeset import generate_changeset, ExceptionConflictHandler
974.1.3 by Aaron Bentley
Added merge_factory parameter to merge_flex
3
from changeset import Inventory, Diff3Merge
974.1.4 by Aaron Bentley
Implemented merge3 as the default text merge
4
from merge_core import ApplyMerge3
622 by Martin Pool
Updated merge patch from Aaron
5
from bzrlib import find_branch
493 by Martin Pool
- Merge aaron's merge command
6
import bzrlib.osutils
622 by Martin Pool
Updated merge patch from Aaron
7
from bzrlib.errors import BzrCommandError
8
from bzrlib.diff import compare_trees
9
from trace import mutter, warning
493 by Martin Pool
- Merge aaron's merge command
10
import os.path
11
import tempfile
12
import shutil
13
import errno
14
622 by Martin Pool
Updated merge patch from Aaron
15
class UnrelatedBranches(BzrCommandError):
16
    def __init__(self):
17
        msg = "Branches have no common ancestor, and no base revision"\
18
            " specified."
19
        BzrCommandError.__init__(self, msg)
20
21
493 by Martin Pool
- Merge aaron's merge command
22
class MergeConflictHandler(ExceptionConflictHandler):
23
    """Handle conflicts encountered while merging"""
622 by Martin Pool
Updated merge patch from Aaron
24
    def __init__(self, dir, ignore_zero=False):
25
        ExceptionConflictHandler.__init__(self, dir)
26
        self.conflicts = 0
27
        self.ignore_zero = ignore_zero
28
493 by Martin Pool
- Merge aaron's merge command
29
    def copy(self, source, dest):
30
        """Copy the text and mode of a file
31
        :param source: The path of the file to copy
32
        :param dest: The distination file to create
33
        """
34
        s_file = file(source, "rb")
35
        d_file = file(dest, "wb")
36
        for line in s_file:
37
            d_file.write(line)
38
        os.chmod(dest, 0777 & os.stat(source).st_mode)
39
40
    def add_suffix(self, name, suffix, last_new_name=None):
41
        """Rename a file to append a suffix.  If the new name exists, the
42
        suffix is added repeatedly until a non-existant name is found
43
44
        :param name: The path of the file
45
        :param suffix: The suffix to append
46
        :param last_new_name: (used for recursive calls) the last name tried
47
        """
48
        if last_new_name is None:
49
            last_new_name = name
50
        new_name = last_new_name+suffix
51
        try:
52
            os.rename(name, new_name)
622 by Martin Pool
Updated merge patch from Aaron
53
            return new_name
493 by Martin Pool
- Merge aaron's merge command
54
        except OSError, e:
55
            if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
56
                raise
622 by Martin Pool
Updated merge patch from Aaron
57
            return self.add_suffix(name, suffix, last_new_name=new_name)
58
59
    def conflict(self, text):
60
        warning(text)
61
        self.conflicts += 1
62
        
493 by Martin Pool
- Merge aaron's merge command
63
64
    def merge_conflict(self, new_file, this_path, base_path, other_path):
65
        """
66
        Handle diff3 conflicts by producing a .THIS, .BASE and .OTHER.  The
67
        main file will be a version with diff3 conflicts.
68
        :param new_file: Path to the output file with diff3 markers
69
        :param this_path: Path to the file text for the THIS tree
70
        :param base_path: Path to the file text for the BASE tree
71
        :param other_path: Path to the file text for the OTHER tree
72
        """
73
        self.add_suffix(this_path, ".THIS")
74
        self.copy(base_path, this_path+".BASE")
75
        self.copy(other_path, this_path+".OTHER")
76
        os.rename(new_file, this_path)
622 by Martin Pool
Updated merge patch from Aaron
77
        self.conflict("Diff3 conflict encountered in %s" % this_path)
493 by Martin Pool
- Merge aaron's merge command
78
79
    def target_exists(self, entry, target, old_path):
80
        """Handle the case when the target file or dir exists"""
622 by Martin Pool
Updated merge patch from Aaron
81
        moved_path = self.add_suffix(target, ".moved")
82
        self.conflict("Moved existing %s to %s" % (target, moved_path))
83
850 by Martin Pool
- Merge merge updates from aaron
84
    def rmdir_non_empty(self, filename):
85
        """Handle the case where the dir to be removed still has contents"""
86
        self.conflict("Directory %s not removed because it is not empty"\
87
            % filename)
88
        return "skip"
89
622 by Martin Pool
Updated merge patch from Aaron
90
    def finalize(self):
91
        if not self.ignore_zero:
92
            print "%d conflicts encountered.\n" % self.conflicts
493 by Martin Pool
- Merge aaron's merge command
93
            
558 by Martin Pool
- All top-level classes inherit from object
94
class SourceFile(object):
493 by Martin Pool
- Merge aaron's merge command
95
    def __init__(self, path, id, present=None, isdir=None):
96
        self.path = path
97
        self.id = id
98
        self.present = present
99
        self.isdir = isdir
100
        self.interesting = True
101
102
    def __repr__(self):
103
        return "SourceFile(%s, %s)" % (self.path, self.id)
104
105
def get_tree(treespec, temp_root, label):
622 by Martin Pool
Updated merge patch from Aaron
106
    location, revno = treespec
107
    branch = find_branch(location)
493 by Martin Pool
- Merge aaron's merge command
108
    if revno is None:
109
        base_tree = branch.working_tree()
110
    elif revno == -1:
111
        base_tree = branch.basis_tree()
112
    else:
113
        base_tree = branch.revision_tree(branch.lookup_revision(revno))
114
    temp_path = os.path.join(temp_root, label)
115
    os.mkdir(temp_path)
622 by Martin Pool
Updated merge patch from Aaron
116
    return branch, MergeTree(base_tree, temp_path)
493 by Martin Pool
- Merge aaron's merge command
117
118
119
def abspath(tree, file_id):
120
    path = tree.inventory.id2path(file_id)
121
    if path == "":
122
        return "./."
123
    return "./" + path
124
125
def file_exists(tree, file_id):
126
    return tree.has_filename(tree.id2path(file_id))
127
    
128
def inventory_map(tree):
129
    inventory = {}
130
    for file_id in tree.inventory:
131
        path = abspath(tree, file_id)
132
        inventory[path] = SourceFile(path, file_id)
133
    return inventory
134
135
136
class MergeTree(object):
137
    def __init__(self, tree, tempdir):
138
        object.__init__(self)
139
        if hasattr(tree, "basedir"):
140
            self.root = tree.basedir
141
        else:
142
            self.root = None
143
        self.inventory = inventory_map(tree)
144
        self.tree = tree
145
        self.tempdir = tempdir
146
        os.mkdir(os.path.join(self.tempdir, "texts"))
147
        self.cached = {}
148
149
    def readonly_path(self, id):
850 by Martin Pool
- Merge merge updates from aaron
150
        if id not in self.tree:
151
            return None
493 by Martin Pool
- Merge aaron's merge command
152
        if self.root is not None:
153
            return self.tree.abspath(self.tree.id2path(id))
154
        else:
155
            if self.tree.inventory[id].kind in ("directory", "root_directory"):
156
                return self.tempdir
157
            if not self.cached.has_key(id):
158
                path = os.path.join(self.tempdir, "texts", id)
159
                outfile = file(path, "wb")
160
                outfile.write(self.tree.get_file(id).read())
161
                assert(os.path.exists(path))
162
                self.cached[id] = path
163
            return self.cached[id]
164
628 by Martin Pool
- merge aaron's updated merge/pull code
165
166
167
def merge(other_revision, base_revision,
168
          check_clean=True, ignore_zero=False,
169
          this_dir=None):
170
    """Merge changes into a tree.
171
172
    base_revision
173
        Base for three-way merge.
174
    other_revision
175
        Other revision for three-way merge.
176
    this_dir
177
        Directory to merge changes into; '.' by default.
178
    check_clean
179
        If true, this_dir must have no uncommitted changes before the
180
        merge begins.
181
    """
493 by Martin Pool
- Merge aaron's merge command
182
    tempdir = tempfile.mkdtemp(prefix="bzr-")
183
    try:
628 by Martin Pool
- merge aaron's updated merge/pull code
184
        if this_dir is None:
185
            this_dir = '.'
186
        this_branch = find_branch(this_dir)
187
        if check_clean:
622 by Martin Pool
Updated merge patch from Aaron
188
            changes = compare_trees(this_branch.working_tree(), 
189
                                    this_branch.basis_tree(), False)
190
            if changes.has_changed():
191
                raise BzrCommandError("Working tree has uncommitted changes.")
192
        other_branch, other_tree = get_tree(other_revision, tempdir, "other")
193
        if base_revision == [None, None]:
194
            if other_revision[1] == -1:
195
                o_revno = None
196
            else:
197
                o_revno = other_revision[1]
198
            base_revno = this_branch.common_ancestor(other_branch, 
199
                                                     other_revno=o_revno)[0]
200
            if base_revno is None:
201
                raise UnrelatedBranches()
202
            base_revision = ['.', base_revno]
203
        base_branch, base_tree = get_tree(base_revision, tempdir, "base")
204
        merge_inner(this_branch, other_tree, base_tree, tempdir, 
205
                    ignore_zero=ignore_zero)
493 by Martin Pool
- Merge aaron's merge command
206
    finally:
207
        shutil.rmtree(tempdir)
208
209
210
def generate_cset_optimized(tree_a, tree_b, inventory_a, inventory_b):
211
    """Generate a changeset, using the text_id to mark really-changed files.
212
    This permits blazing comparisons when text_ids are present.  It also
213
    disables metadata comparison for files with identical texts.
214
    """ 
215
    for file_id in tree_a.tree.inventory:
216
        if file_id not in tree_b.tree.inventory:
217
            continue
218
        entry_a = tree_a.tree.inventory[file_id]
219
        entry_b = tree_b.tree.inventory[file_id]
220
        if (entry_a.kind, entry_b.kind) != ("file", "file"):
221
            continue
222
        if None in (entry_a.text_id, entry_b.text_id):
223
            continue
224
        if entry_a.text_id != entry_b.text_id:
225
            continue
226
        inventory_a[abspath(tree_a.tree, file_id)].interesting = False
227
        inventory_b[abspath(tree_b.tree, file_id)].interesting = False
228
    cset =  generate_changeset(tree_a, tree_b, inventory_a, inventory_b)
229
    for entry in cset.entries.itervalues():
230
        entry.metadata_change = None
231
    return cset
232
233
622 by Martin Pool
Updated merge patch from Aaron
234
def merge_inner(this_branch, other_tree, base_tree, tempdir, 
974.1.4 by Aaron Bentley
Implemented merge3 as the default text merge
235
                ignore_zero=False, merge_type="diff3"):
236
    merge_types = {"merge3": ApplyMerge3, 
237
                   "diff3": Diff3Merge}
238
239
    def merge_factory(base_file, other_file):
240
        return merge_types[merge_type](base_file, other_file)
241
628 by Martin Pool
- merge aaron's updated merge/pull code
242
    this_tree = get_tree((this_branch.base, None), tempdir, "this")[1]
493 by Martin Pool
- Merge aaron's merge command
243
244
    def get_inventory(tree):
245
        return tree.inventory
246
247
    inv_changes = merge_flex(this_tree, base_tree, other_tree,
248
                             generate_cset_optimized, get_inventory,
622 by Martin Pool
Updated merge patch from Aaron
249
                             MergeConflictHandler(base_tree.root,
974.1.3 by Aaron Bentley
Added merge_factory parameter to merge_flex
250
                                                  ignore_zero=ignore_zero),
974.1.4 by Aaron Bentley
Implemented merge3 as the default text merge
251
                             merge_factory=merge_factory)
493 by Martin Pool
- Merge aaron's merge command
252
253
    adjust_ids = []
254
    for id, path in inv_changes.iteritems():
255
        if path is not None:
256
            if path == '.':
257
                path = ''
258
            else:
259
                assert path.startswith('./')
260
            path = path[2:]
261
        adjust_ids.append((path, id))
262
    this_branch.set_inventory(regen_inventory(this_branch, this_tree.root, adjust_ids))
263
264
265
def regen_inventory(this_branch, root, new_entries):
266
    old_entries = this_branch.read_working_inventory()
267
    new_inventory = {}
268
    by_path = {}
269
    for file_id in old_entries:
270
        entry = old_entries[file_id]
271
        path = old_entries.id2path(file_id)
272
        new_inventory[file_id] = (path, file_id, entry.parent_id, entry.kind)
273
        by_path[path] = file_id
274
    
275
    deletions = 0
276
    insertions = 0
277
    new_path_list = []
278
    for path, file_id in new_entries:
279
        if path is None:
280
            del new_inventory[file_id]
281
            deletions += 1
282
        else:
283
            new_path_list.append((path, file_id))
284
            if file_id not in old_entries:
285
                insertions += 1
286
    # Ensure no file is added before its parent
287
    new_path_list.sort()
288
    for path, file_id in new_path_list:
289
        if path == '':
290
            parent = None
291
        else:
292
            parent = by_path[os.path.dirname(path)]
293
        kind = bzrlib.osutils.file_kind(os.path.join(root, path))
294
        new_inventory[file_id] = (path, file_id, parent, kind)
295
        by_path[path] = file_id 
296
297
    # Get a list in insertion order
298
    new_inventory_list = new_inventory.values()
299
    mutter ("""Inventory regeneration:
300
old length: %i insertions: %i deletions: %i new_length: %i"""\
301
        % (len(old_entries), insertions, deletions, len(new_inventory_list)))
302
    assert len(new_inventory_list) == len(old_entries) + insertions - deletions
303
    new_inventory_list.sort()
304
    return new_inventory_list