/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: Martin von Gagern
  • Date: 2010-04-20 08:47:38 UTC
  • mfrom: (5167 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5195.
  • Revision ID: martin.vgagern@gmx.net-20100420084738-ygymnqmdllzrhpfn
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
16
 
 
17
 
 
18
 
import errno
19
 
from itertools import chain
20
 
import os
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
21
17
import warnings
22
18
 
23
19
from bzrlib import (
 
20
    branch as _mod_branch,
 
21
    conflicts as _mod_conflicts,
24
22
    debug,
 
23
    decorators,
25
24
    errors,
26
25
    graph as _mod_graph,
 
26
    hooks,
 
27
    merge3,
27
28
    osutils,
28
29
    patiencediff,
29
 
    registry,
30
30
    revision as _mod_revision,
 
31
    textfile,
 
32
    trace,
 
33
    transform,
31
34
    tree as _mod_tree,
32
35
    tsort,
33
 
    )
34
 
from bzrlib.branch import Branch
35
 
from bzrlib.conflicts import ConflictList, Conflict
36
 
from bzrlib.errors import (BzrCommandError,
37
 
                           BzrError,
38
 
                           NoCommonAncestor,
39
 
                           NoCommits,
40
 
                           NoSuchRevision,
41
 
                           NoSuchFile,
42
 
                           NotBranchError,
43
 
                           NotVersionedError,
44
 
                           UnrelatedBranches,
45
 
                           UnsupportedOperation,
46
 
                           WorkingTreeNotRevision,
47
 
                           BinaryFile,
48
 
                           )
49
 
from bzrlib.graph import Graph
50
 
from bzrlib.merge3 import Merge3
51
 
from bzrlib.osutils import rename, pathjoin
52
 
from progress import DummyProgress, ProgressPhase
53
 
from bzrlib.revision import (NULL_REVISION, ensure_null)
54
 
from bzrlib.textfile import check_text_lines
55
 
from bzrlib.trace import mutter, warning, note, is_quiet
56
 
from bzrlib.transform import (TransformPreview, TreeTransform,
57
 
                              resolve_conflicts, cook_conflicts,
58
 
                              conflict_pass, FinalPaths, create_by_entry,
59
 
                              unique_add, ROOT_PARENT)
60
 
from bzrlib.versionedfile import PlanWeaveMerge
61
 
from bzrlib import ui
62
 
 
 
36
    ui,
 
37
    versionedfile
 
38
    )
 
39
from bzrlib.cleanup import OperationWithCleanups
 
40
from bzrlib.symbol_versioning import (
 
41
    deprecated_in,
 
42
    deprecated_method,
 
43
    )
63
44
# TODO: Report back as changes are merged in
64
45
 
65
46
 
66
47
def transform_tree(from_tree, to_tree, interesting_ids=None):
67
 
    merge_inner(from_tree.branch, to_tree, from_tree, ignore_zero=True,
68
 
                interesting_ids=interesting_ids, this_tree=from_tree)
 
48
    from_tree.lock_tree_write()
 
49
    operation = OperationWithCleanups(merge_inner)
 
50
    operation.add_cleanup(from_tree.unlock)
 
51
    operation.run_simple(from_tree.branch, to_tree, from_tree,
 
52
        ignore_zero=True, interesting_ids=interesting_ids, this_tree=from_tree)
 
53
 
 
54
 
 
55
class MergeHooks(hooks.Hooks):
 
56
 
 
57
    def __init__(self):
 
58
        hooks.Hooks.__init__(self)
 
59
        self.create_hook(hooks.HookPoint('merge_file_content',
 
60
            "Called with a bzrlib.merge.Merger object to create a per file "
 
61
            "merge object when starting a merge. "
 
62
            "Should return either None or a subclass of "
 
63
            "``bzrlib.merge.AbstractPerFileMerger``. "
 
64
            "Such objects will then be called per file "
 
65
            "that needs to be merged (including when one "
 
66
            "side has deleted the file and the other has changed it). "
 
67
            "See the AbstractPerFileMerger API docs for details on how it is "
 
68
            "used by merge.",
 
69
            (2, 1), None))
 
70
 
 
71
 
 
72
class AbstractPerFileMerger(object):
 
73
    """PerFileMerger objects are used by plugins extending merge for bzrlib.
 
74
 
 
75
    See ``bzrlib.plugins.news_merge.news_merge`` for an example concrete class.
 
76
    
 
77
    :ivar merger: The Merge3Merger performing the merge.
 
78
    """
 
79
 
 
80
    def __init__(self, merger):
 
81
        """Create a PerFileMerger for use with merger."""
 
82
        self.merger = merger
 
83
 
 
84
    def merge_contents(self, merge_params):
 
85
        """Attempt to merge the contents of a single file.
 
86
        
 
87
        :param merge_params: A bzrlib.merge.MergeHookParams
 
88
        :return : A tuple of (status, chunks), where status is one of
 
89
            'not_applicable', 'success', 'conflicted', or 'delete'.  If status
 
90
            is 'success' or 'conflicted', then chunks should be an iterable of
 
91
            strings for the new file contents.
 
92
        """
 
93
        return ('not applicable', None)
 
94
 
 
95
 
 
96
class ConfigurableFileMerger(AbstractPerFileMerger):
 
97
    """Merge individual files when configured via a .conf file.
 
98
 
 
99
    This is a base class for concrete custom file merging logic. Concrete
 
100
    classes should implement ``merge_text``.
 
101
 
 
102
    See ``bzrlib.plugins.news_merge.news_merge`` for an example concrete class.
 
103
    
 
104
    :ivar affected_files: The configured file paths to merge.
 
105
 
 
106
    :cvar name_prefix: The prefix to use when looking up configuration
 
107
        details. <name_prefix>_merge_files describes the files targeted by the
 
108
        hook for example.
 
109
        
 
110
    :cvar default_files: The default file paths to merge when no configuration
 
111
        is present.
 
112
    """
 
113
 
 
114
    name_prefix = None
 
115
    default_files = None
 
116
 
 
117
    def __init__(self, merger):
 
118
        super(ConfigurableFileMerger, self).__init__(merger)
 
119
        self.affected_files = None
 
120
        self.default_files = self.__class__.default_files or []
 
121
        self.name_prefix = self.__class__.name_prefix
 
122
        if self.name_prefix is None:
 
123
            raise ValueError("name_prefix must be set.")
 
124
 
 
125
    def filename_matches_config(self, params):
 
126
        """Check whether the file should call the merge hook.
 
127
 
 
128
        <name_prefix>_merge_files configuration variable is a list of files
 
129
        that should use the hook.
 
130
        """
 
131
        affected_files = self.affected_files
 
132
        if affected_files is None:
 
133
            config = self.merger.this_branch.get_config()
 
134
            # Until bzr provides a better policy for caching the config, we
 
135
            # just add the part we're interested in to the params to avoid
 
136
            # reading the config files repeatedly (bazaar.conf, location.conf,
 
137
            # branch.conf).
 
138
            config_key = self.name_prefix + '_merge_files'
 
139
            affected_files = config.get_user_option_as_list(config_key)
 
140
            if affected_files is None:
 
141
                # If nothing was specified in the config, use the default.
 
142
                affected_files = self.default_files
 
143
            self.affected_files = affected_files
 
144
        if affected_files:
 
145
            filename = self.merger.this_tree.id2path(params.file_id)
 
146
            if filename in affected_files:
 
147
                return True
 
148
        return False
 
149
 
 
150
    def merge_contents(self, params):
 
151
        """Merge the contents of a single file."""
 
152
        # First, check whether this custom merge logic should be used.  We
 
153
        # expect most files should not be merged by this handler.
 
154
        if (
 
155
            # OTHER is a straight winner, rely on default merge.
 
156
            params.winner == 'other' or
 
157
            # THIS and OTHER aren't both files.
 
158
            not params.is_file_merge() or
 
159
            # The filename isn't listed in the 'NAME_merge_files' config
 
160
            # option.
 
161
            not self.filename_matches_config(params)):
 
162
            return 'not_applicable', None
 
163
        return self.merge_text(params)
 
164
 
 
165
    def merge_text(self, params):
 
166
        """Merge the byte contents of a single file.
 
167
 
 
168
        This is called after checking that the merge should be performed in
 
169
        merge_contents, and it should behave as per
 
170
        ``bzrlib.merge.AbstractPerFileMerger.merge_contents``.
 
171
        """
 
172
        raise NotImplementedError(self.merge_text)
 
173
 
 
174
 
 
175
class MergeHookParams(object):
 
176
    """Object holding parameters passed to merge_file_content hooks.
 
177
 
 
178
    There are some fields hooks can access:
 
179
 
 
180
    :ivar file_id: the file ID of the file being merged
 
181
    :ivar trans_id: the transform ID for the merge of this file
 
182
    :ivar this_kind: kind of file_id in 'this' tree
 
183
    :ivar other_kind: kind of file_id in 'other' tree
 
184
    :ivar winner: one of 'this', 'other', 'conflict'
 
185
    """
 
186
 
 
187
    def __init__(self, merger, file_id, trans_id, this_kind, other_kind,
 
188
            winner):
 
189
        self._merger = merger
 
190
        self.file_id = file_id
 
191
        self.trans_id = trans_id
 
192
        self.this_kind = this_kind
 
193
        self.other_kind = other_kind
 
194
        self.winner = winner
 
195
 
 
196
    def is_file_merge(self):
 
197
        """True if this_kind and other_kind are both 'file'."""
 
198
        return self.this_kind == 'file' and self.other_kind == 'file'
 
199
 
 
200
    @decorators.cachedproperty
 
201
    def base_lines(self):
 
202
        """The lines of the 'base' version of the file."""
 
203
        return self._merger.get_lines(self._merger.base_tree, self.file_id)
 
204
 
 
205
    @decorators.cachedproperty
 
206
    def this_lines(self):
 
207
        """The lines of the 'this' version of the file."""
 
208
        return self._merger.get_lines(self._merger.this_tree, self.file_id)
 
209
 
 
210
    @decorators.cachedproperty
 
211
    def other_lines(self):
 
212
        """The lines of the 'other' version of the file."""
 
213
        return self._merger.get_lines(self._merger.other_tree, self.file_id)
69
214
 
70
215
 
71
216
class Merger(object):
 
217
 
 
218
    hooks = MergeHooks()
 
219
 
72
220
    def __init__(self, this_branch, other_tree=None, base_tree=None,
73
 
                 this_tree=None, pb=DummyProgress(), change_reporter=None,
 
221
                 this_tree=None, pb=None, change_reporter=None,
74
222
                 recurse='down', revision_graph=None):
75
223
        object.__init__(self)
76
224
        self.this_branch = this_branch
89
237
        self.interesting_files = None
90
238
        self.show_base = False
91
239
        self.reprocess = False
92
 
        self._pb = pb
 
240
        if pb is not None:
 
241
            warnings.warn("pb parameter to Merger() is deprecated and ignored")
93
242
        self.pp = None
94
243
        self.recurse = recurse
95
244
        self.change_reporter = change_reporter
100
249
        self._is_criss_cross = None
101
250
        self._lca_trees = None
102
251
 
 
252
    def cache_trees_with_revision_ids(self, trees):
 
253
        """Cache any tree in trees if it has a revision_id."""
 
254
        for maybe_tree in trees:
 
255
            if maybe_tree is None:
 
256
                continue
 
257
            try:
 
258
                rev_id = maybe_tree.get_revision_id()
 
259
            except AttributeError:
 
260
                continue
 
261
            self._cached_trees[rev_id] = maybe_tree
 
262
 
103
263
    @property
104
264
    def revision_graph(self):
105
265
        if self._revision_graph is None:
132
292
                                      _set_base_is_other_ancestor)
133
293
 
134
294
    @staticmethod
135
 
    def from_uncommitted(tree, other_tree, pb):
 
295
    def from_uncommitted(tree, other_tree, pb=None, base_tree=None):
136
296
        """Return a Merger for uncommitted changes in other_tree.
137
297
 
138
298
        :param tree: The tree to merge into
139
299
        :param other_tree: The tree to get uncommitted changes from
140
300
        :param pb: A progress indicator
 
301
        :param base_tree: The basis to use for the merge.  If unspecified,
 
302
            other_tree.basis_tree() will be used.
141
303
        """
142
 
        merger = Merger(tree.branch, other_tree, other_tree.basis_tree(), tree,
143
 
                        pb)
 
304
        if base_tree is None:
 
305
            base_tree = other_tree.basis_tree()
 
306
        merger = Merger(tree.branch, other_tree, base_tree, tree, pb)
144
307
        merger.base_rev_id = merger.base_tree.get_revision_id()
145
308
        merger.other_rev_id = None
146
309
        merger.other_basis = merger.base_rev_id
164
327
                base_revision_id, tree.branch.last_revision())):
165
328
                base_revision_id = None
166
329
            else:
167
 
                warning('Performing cherrypick')
 
330
                trace.warning('Performing cherrypick')
168
331
        merger = klass.from_revision_ids(pb, tree, other_revision_id,
169
332
                                         base_revision_id, revision_graph=
170
333
                                         revision_graph)
172
335
 
173
336
    @staticmethod
174
337
    def from_revision_ids(pb, tree, other, base=None, other_branch=None,
175
 
                          base_branch=None, revision_graph=None):
 
338
                          base_branch=None, revision_graph=None,
 
339
                          tree_branch=None):
176
340
        """Return a Merger for revision-ids.
177
341
 
 
342
        :param pb: A progress indicator
178
343
        :param tree: The tree to merge changes into
179
344
        :param other: The revision-id to use as OTHER
180
345
        :param base: The revision-id to use as BASE.  If not specified, will
185
350
            not supplied, other_branch or tree.branch will be used.
186
351
        :param revision_graph: If you have a revision_graph precomputed, pass
187
352
            it in, otherwise it will be created for you.
188
 
        :param pb: A progress indicator
 
353
        :param tree_branch: The branch associated with tree.  If not supplied,
 
354
            tree.branch will be used.
189
355
        """
190
 
        merger = Merger(tree.branch, this_tree=tree, pb=pb,
 
356
        if tree_branch is None:
 
357
            tree_branch = tree.branch
 
358
        merger = Merger(tree_branch, this_tree=tree, pb=pb,
191
359
                        revision_graph=revision_graph)
192
360
        if other_branch is None:
193
361
            other_branch = tree.branch
217
385
        if revno is None:
218
386
            tree = workingtree.WorkingTree.open_containing(location)[0]
219
387
            return tree.branch, tree
220
 
        branch = Branch.open_containing(location, possible_transports)[0]
 
388
        branch = _mod_branch.Branch.open_containing(
 
389
            location, possible_transports)[0]
221
390
        if revno == -1:
222
391
            revision_id = branch.last_revision()
223
392
        else:
224
393
            revision_id = branch.get_rev_id(revno)
225
 
        revision_id = ensure_null(revision_id)
 
394
        revision_id = _mod_revision.ensure_null(revision_id)
226
395
        return branch, self.revision_tree(revision_id, branch)
227
396
 
 
397
    @deprecated_method(deprecated_in((2, 1, 0)))
228
398
    def ensure_revision_trees(self):
229
399
        if self.this_revision_tree is None:
230
400
            self.this_basis_tree = self.revision_tree(self.this_basis)
233
403
 
234
404
        if self.other_rev_id is None:
235
405
            other_basis_tree = self.revision_tree(self.other_basis)
236
 
            changes = other_basis_tree.changes_from(self.other_tree)
237
 
            if changes.has_changed():
238
 
                raise WorkingTreeNotRevision(self.this_tree)
 
406
            if other_basis_tree.has_changes(self.other_tree):
 
407
                raise errors.WorkingTreeNotRevision(self.this_tree)
239
408
            other_rev_id = self.other_basis
240
409
            self.other_tree = other_basis_tree
241
410
 
 
411
    @deprecated_method(deprecated_in((2, 1, 0)))
242
412
    def file_revisions(self, file_id):
243
413
        self.ensure_revision_trees()
244
414
        def get_id(tree, file_id):
247
417
        if self.this_rev_id is None:
248
418
            if self.this_basis_tree.get_file_sha1(file_id) != \
249
419
                self.this_tree.get_file_sha1(file_id):
250
 
                raise WorkingTreeNotRevision(self.this_tree)
 
420
                raise errors.WorkingTreeNotRevision(self.this_tree)
251
421
 
252
422
        trees = (self.this_basis_tree, self.other_tree)
253
423
        return [get_id(tree, file_id) for tree in trees]
254
424
 
 
425
    @deprecated_method(deprecated_in((2, 1, 0)))
255
426
    def check_basis(self, check_clean, require_commits=True):
256
427
        if self.this_basis is None and require_commits is True:
257
 
            raise BzrCommandError("This branch has no commits."
258
 
                                  " (perhaps you would prefer 'bzr pull')")
 
428
            raise errors.BzrCommandError(
 
429
                "This branch has no commits."
 
430
                " (perhaps you would prefer 'bzr pull')")
259
431
        if check_clean:
260
432
            self.compare_basis()
261
433
            if self.this_basis != self.this_rev_id:
262
434
                raise errors.UncommittedChanges(self.this_tree)
263
435
 
 
436
    @deprecated_method(deprecated_in((2, 1, 0)))
264
437
    def compare_basis(self):
265
438
        try:
266
439
            basis_tree = self.revision_tree(self.this_tree.last_revision())
267
440
        except errors.NoSuchRevision:
268
441
            basis_tree = self.this_tree.basis_tree()
269
 
        changes = self.this_tree.changes_from(basis_tree)
270
 
        if not changes.has_changed():
 
442
        if not self.this_tree.has_changes(basis_tree):
271
443
            self.this_rev_id = self.this_basis
272
444
 
273
445
    def set_interesting_files(self, file_list):
274
446
        self.interesting_files = file_list
275
447
 
276
448
    def set_pending(self):
277
 
        if not self.base_is_ancestor or not self.base_is_other_ancestor or self.other_rev_id is None:
 
449
        if (not self.base_is_ancestor or not self.base_is_other_ancestor
 
450
            or self.other_rev_id is None):
278
451
            return
279
452
        self._add_parent()
280
453
 
281
454
    def _add_parent(self):
282
455
        new_parents = self.this_tree.get_parent_ids() + [self.other_rev_id]
283
456
        new_parent_trees = []
 
457
        operation = OperationWithCleanups(self.this_tree.set_parent_trees)
284
458
        for revision_id in new_parents:
285
459
            try:
286
460
                tree = self.revision_tree(revision_id)
288
462
                tree = None
289
463
            else:
290
464
                tree.lock_read()
 
465
                operation.add_cleanup(tree.unlock)
291
466
            new_parent_trees.append((revision_id, tree))
292
 
        try:
293
 
            self.this_tree.set_parent_trees(new_parent_trees,
294
 
                                            allow_leftmost_as_ghost=True)
295
 
        finally:
296
 
            for _revision_id, tree in new_parent_trees:
297
 
                if tree is not None:
298
 
                    tree.unlock()
 
467
        operation.run_simple(new_parent_trees, allow_leftmost_as_ghost=True)
299
468
 
300
469
    def set_other(self, other_revision, possible_transports=None):
301
470
        """Set the revision and tree to merge from.
310
479
            self.other_rev_id = _mod_revision.ensure_null(
311
480
                self.other_branch.last_revision())
312
481
            if _mod_revision.is_null(self.other_rev_id):
313
 
                raise NoCommits(self.other_branch)
 
482
                raise errors.NoCommits(self.other_branch)
314
483
            self.other_basis = self.other_rev_id
315
484
        elif other_revision[1] is not None:
316
485
            self.other_rev_id = self.other_branch.get_rev_id(other_revision[1])
319
488
            self.other_rev_id = None
320
489
            self.other_basis = self.other_branch.last_revision()
321
490
            if self.other_basis is None:
322
 
                raise NoCommits(self.other_branch)
 
491
                raise errors.NoCommits(self.other_branch)
323
492
        if self.other_rev_id is not None:
324
493
            self._cached_trees[self.other_rev_id] = self.other_tree
325
494
        self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
352
521
            target.fetch(source, revision_id)
353
522
 
354
523
    def find_base(self):
355
 
        revisions = [ensure_null(self.this_basis),
356
 
                     ensure_null(self.other_basis)]
357
 
        if NULL_REVISION in revisions:
358
 
            self.base_rev_id = NULL_REVISION
 
524
        revisions = [_mod_revision.ensure_null(self.this_basis),
 
525
                     _mod_revision.ensure_null(self.other_basis)]
 
526
        if _mod_revision.NULL_REVISION in revisions:
 
527
            self.base_rev_id = _mod_revision.NULL_REVISION
359
528
            self.base_tree = self.revision_tree(self.base_rev_id)
360
529
            self._is_criss_cross = False
361
530
        else:
362
531
            lcas = self.revision_graph.find_lca(revisions[0], revisions[1])
363
532
            self._is_criss_cross = False
364
533
            if len(lcas) == 0:
365
 
                self.base_rev_id = NULL_REVISION
 
534
                self.base_rev_id = _mod_revision.NULL_REVISION
366
535
            elif len(lcas) == 1:
367
536
                self.base_rev_id = list(lcas)[0]
368
537
            else: # len(lcas) > 1
377
546
                    self.base_rev_id = self.revision_graph.find_unique_lca(
378
547
                                            *lcas)
379
548
                self._is_criss_cross = True
380
 
            if self.base_rev_id == NULL_REVISION:
381
 
                raise UnrelatedBranches()
 
549
            if self.base_rev_id == _mod_revision.NULL_REVISION:
 
550
                raise errors.UnrelatedBranches()
382
551
            if self._is_criss_cross:
383
 
                warning('Warning: criss-cross merge encountered.  See bzr'
384
 
                        ' help criss-cross.')
 
552
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
 
553
                              ' help criss-cross.')
 
554
                trace.mutter('Criss-cross lcas: %r' % lcas)
385
555
                interesting_revision_ids = [self.base_rev_id]
386
556
                interesting_revision_ids.extend(lcas)
387
557
                interesting_trees = dict((t.get_revision_id(), t)
397
567
                self.base_tree = self.revision_tree(self.base_rev_id)
398
568
        self.base_is_ancestor = True
399
569
        self.base_is_other_ancestor = True
 
570
        trace.mutter('Base revid: %r' % self.base_rev_id)
400
571
 
401
572
    def set_base(self, base_revision):
402
573
        """Set the base revision to use for the merge.
403
574
 
404
575
        :param base_revision: A 2-list containing a path and revision number.
405
576
        """
406
 
        mutter("doing merge() with no base_revision specified")
 
577
        trace.mutter("doing merge() with no base_revision specified")
407
578
        if base_revision == [None, None]:
408
579
            self.find_base()
409
580
        else:
422
593
                  'other_tree': self.other_tree,
423
594
                  'interesting_ids': self.interesting_ids,
424
595
                  'interesting_files': self.interesting_files,
425
 
                  'pp': self.pp,
 
596
                  'this_branch': self.this_branch,
426
597
                  'do_merge': False}
427
598
        if self.merge_type.requires_base:
428
599
            kwargs['base_tree'] = self.base_tree
429
600
        if self.merge_type.supports_reprocess:
430
601
            kwargs['reprocess'] = self.reprocess
431
602
        elif self.reprocess:
432
 
            raise BzrError("Conflict reduction is not supported for merge"
433
 
                                  " type %s." % self.merge_type)
 
603
            raise errors.BzrError(
 
604
                "Conflict reduction is not supported for merge"
 
605
                " type %s." % self.merge_type)
434
606
        if self.merge_type.supports_show_base:
435
607
            kwargs['show_base'] = self.show_base
436
608
        elif self.show_base:
437
 
            raise BzrError("Showing base is not supported for this"
438
 
                           " merge type. %s" % self.merge_type)
 
609
            raise errors.BzrError("Showing base is not supported for this"
 
610
                                  " merge type. %s" % self.merge_type)
439
611
        if (not getattr(self.merge_type, 'supports_reverse_cherrypick', True)
440
612
            and not self.base_is_other_ancestor):
441
613
            raise errors.CannotReverseCherrypick()
445
617
        if self._is_criss_cross and getattr(self.merge_type,
446
618
                                            'supports_lca_trees', False):
447
619
            kwargs['lca_trees'] = self._lca_trees
448
 
        return self.merge_type(pb=self._pb,
 
620
        return self.merge_type(pb=None,
449
621
                               change_reporter=self.change_reporter,
450
622
                               **kwargs)
451
623
 
452
 
    def _do_merge_to(self, merge):
 
624
    def _do_merge_to(self):
 
625
        merge = self.make_merger()
 
626
        if self.other_branch is not None:
 
627
            self.other_branch.update_references(self.this_branch)
453
628
        merge.do_merge()
454
629
        if self.recurse == 'down':
455
630
            for relpath, file_id in self.this_tree.iter_references():
467
642
                    sub_tree.branch.repository.revision_tree(base_revision)
468
643
                sub_merge.base_rev_id = base_revision
469
644
                sub_merge.do_merge()
470
 
        
 
645
        return merge
 
646
 
471
647
    def do_merge(self):
 
648
        operation = OperationWithCleanups(self._do_merge_to)
472
649
        self.this_tree.lock_tree_write()
473
 
        try:
474
 
            if self.base_tree is not None:
475
 
                self.base_tree.lock_read()
476
 
            try:
477
 
                if self.other_tree is not None:
478
 
                    self.other_tree.lock_read()
479
 
                try:
480
 
                    merge = self.make_merger()
481
 
                    self._do_merge_to(merge)
482
 
                finally:
483
 
                    if self.other_tree is not None:
484
 
                        self.other_tree.unlock()
485
 
            finally:
486
 
                if self.base_tree is not None:
487
 
                    self.base_tree.unlock()
488
 
        finally:
489
 
            self.this_tree.unlock()
 
650
        operation.add_cleanup(self.this_tree.unlock)
 
651
        if self.base_tree is not None:
 
652
            self.base_tree.lock_read()
 
653
            operation.add_cleanup(self.base_tree.unlock)
 
654
        if self.other_tree is not None:
 
655
            self.other_tree.lock_read()
 
656
            operation.add_cleanup(self.other_tree.unlock)
 
657
        merge = operation.run_simple()
490
658
        if len(merge.cooked_conflicts) == 0:
491
 
            if not self.ignore_zero and not is_quiet():
492
 
                note("All changes applied successfully.")
 
659
            if not self.ignore_zero and not trace.is_quiet():
 
660
                trace.note("All changes applied successfully.")
493
661
        else:
494
 
            note("%d conflicts encountered." % len(merge.cooked_conflicts))
 
662
            trace.note("%d conflicts encountered."
 
663
                       % len(merge.cooked_conflicts))
495
664
 
496
665
        return len(merge.cooked_conflicts)
497
666
 
524
693
    winner_idx = {"this": 2, "other": 1, "conflict": 1}
525
694
    supports_lca_trees = True
526
695
 
527
 
    def __init__(self, working_tree, this_tree, base_tree, other_tree, 
 
696
    def __init__(self, working_tree, this_tree, base_tree, other_tree,
528
697
                 interesting_ids=None, reprocess=False, show_base=False,
529
 
                 pb=DummyProgress(), pp=None, change_reporter=None,
 
698
                 pb=None, pp=None, change_reporter=None,
530
699
                 interesting_files=None, do_merge=True,
531
 
                 cherrypick=False, lca_trees=None):
 
700
                 cherrypick=False, lca_trees=None, this_branch=None):
532
701
        """Initialize the merger object and perform the merge.
533
702
 
534
703
        :param working_tree: The working tree to apply the merge to
535
704
        :param this_tree: The local tree in the merge operation
536
705
        :param base_tree: The common tree in the merge operation
537
 
        :param other_tree: The other other tree to merge changes from
 
706
        :param other_tree: The other tree to merge changes from
 
707
        :param this_branch: The branch associated with this_tree
538
708
        :param interesting_ids: The file_ids of files that should be
539
709
            participate in the merge.  May not be combined with
540
710
            interesting_files.
541
711
        :param: reprocess If True, perform conflict-reduction processing.
542
712
        :param show_base: If True, show the base revision in text conflicts.
543
713
            (incompatible with reprocess)
544
 
        :param pb: A Progress bar
 
714
        :param pb: ignored
545
715
        :param pp: A ProgressPhase object
546
716
        :param change_reporter: An object that should report changes made
547
717
        :param interesting_files: The tree-relative paths of files that should
563
733
        self.this_tree = working_tree
564
734
        self.base_tree = base_tree
565
735
        self.other_tree = other_tree
 
736
        self.this_branch = this_branch
566
737
        self._raw_conflicts = []
567
738
        self.cooked_conflicts = []
568
739
        self.reprocess = reprocess
573
744
        # making sure we haven't missed any corner cases.
574
745
        # if lca_trees is None:
575
746
        #     self._lca_trees = [self.base_tree]
576
 
        self.pb = pb
577
 
        self.pp = pp
578
747
        self.change_reporter = change_reporter
579
748
        self.cherrypick = cherrypick
580
 
        if self.pp is None:
581
 
            self.pp = ProgressPhase("Merge phase", 3, self.pb)
582
749
        if do_merge:
583
750
            self.do_merge()
 
751
        if pp is not None:
 
752
            warnings.warn("pp argument to Merge3Merger is deprecated")
 
753
        if pb is not None:
 
754
            warnings.warn("pb argument to Merge3Merger is deprecated")
584
755
 
585
756
    def do_merge(self):
 
757
        operation = OperationWithCleanups(self._do_merge)
586
758
        self.this_tree.lock_tree_write()
 
759
        operation.add_cleanup(self.this_tree.unlock)
587
760
        self.base_tree.lock_read()
 
761
        operation.add_cleanup(self.base_tree.unlock)
588
762
        self.other_tree.lock_read()
589
 
        self.tt = TreeTransform(self.this_tree, self.pb)
 
763
        operation.add_cleanup(self.other_tree.unlock)
 
764
        operation.run()
 
765
 
 
766
    def _do_merge(self, operation):
 
767
        self.tt = transform.TreeTransform(self.this_tree, None)
 
768
        operation.add_cleanup(self.tt.finalize)
 
769
        self._compute_transform()
 
770
        results = self.tt.apply(no_conflicts=True)
 
771
        self.write_modified(results)
590
772
        try:
591
 
            self.pp.next_phase()
592
 
            self._compute_transform()
593
 
            self.pp.next_phase()
594
 
            results = self.tt.apply(no_conflicts=True)
595
 
            self.write_modified(results)
596
 
            try:
597
 
                self.this_tree.add_conflicts(self.cooked_conflicts)
598
 
            except UnsupportedOperation:
599
 
                pass
600
 
        finally:
601
 
            self.tt.finalize()
602
 
            self.other_tree.unlock()
603
 
            self.base_tree.unlock()
604
 
            self.this_tree.unlock()
605
 
            self.pb.clear()
 
773
            self.this_tree.add_conflicts(self.cooked_conflicts)
 
774
        except errors.UnsupportedOperation:
 
775
            pass
606
776
 
607
777
    def make_preview_transform(self):
 
778
        operation = OperationWithCleanups(self._make_preview_transform)
608
779
        self.base_tree.lock_read()
 
780
        operation.add_cleanup(self.base_tree.unlock)
609
781
        self.other_tree.lock_read()
610
 
        self.tt = TransformPreview(self.this_tree)
611
 
        try:
612
 
            self.pp.next_phase()
613
 
            self._compute_transform()
614
 
            self.pp.next_phase()
615
 
        finally:
616
 
            self.other_tree.unlock()
617
 
            self.base_tree.unlock()
618
 
            self.pb.clear()
 
782
        operation.add_cleanup(self.other_tree.unlock)
 
783
        return operation.run_simple()
 
784
 
 
785
    def _make_preview_transform(self):
 
786
        self.tt = transform.TransformPreview(self.this_tree)
 
787
        self._compute_transform()
619
788
        return self.tt
620
789
 
621
790
    def _compute_transform(self):
627
796
            resolver = self._lca_multi_way
628
797
        child_pb = ui.ui_factory.nested_progress_bar()
629
798
        try:
 
799
            factories = Merger.hooks['merge_file_content']
 
800
            hooks = [factory(self) for factory in factories] + [self]
 
801
            self.active_hooks = [hook for hook in hooks if hook is not None]
630
802
            for num, (file_id, changed, parents3, names3,
631
803
                      executable3) in enumerate(entries):
632
804
                child_pb.update('Preparing file merge', num, len(entries))
633
805
                self._merge_names(file_id, parents3, names3, resolver=resolver)
634
806
                if changed:
635
 
                    file_status = self.merge_contents(file_id)
 
807
                    file_status = self._do_merge_contents(file_id)
636
808
                else:
637
809
                    file_status = 'unmodified'
638
810
                self._merge_executable(file_id,
640
812
        finally:
641
813
            child_pb.finished()
642
814
        self.fix_root()
643
 
        self.pp.next_phase()
644
815
        child_pb = ui.ui_factory.nested_progress_bar()
645
816
        try:
646
 
            fs_conflicts = resolve_conflicts(self.tt, child_pb,
647
 
                lambda t, c: conflict_pass(t, c, self.other_tree))
 
817
            fs_conflicts = transform.resolve_conflicts(self.tt, child_pb,
 
818
                lambda t, c: transform.conflict_pass(t, c, self.other_tree))
648
819
        finally:
649
820
            child_pb.finished()
650
821
        if self.change_reporter is not None:
653
824
                self.tt.iter_changes(), self.change_reporter)
654
825
        self.cook_conflicts(fs_conflicts)
655
826
        for conflict in self.cooked_conflicts:
656
 
            warning(conflict)
 
827
            trace.warning(conflict)
657
828
 
658
829
    def _entries3(self):
659
830
        """Gather data about files modified between three trees.
668
839
        iterator = self.other_tree.iter_changes(self.base_tree,
669
840
                include_unchanged=True, specific_files=self.interesting_files,
670
841
                extra_trees=[self.this_tree])
 
842
        this_entries = dict((e.file_id, e) for p, e in
 
843
                            self.this_tree.iter_entries_by_dir(
 
844
                            self.interesting_ids))
671
845
        for (file_id, paths, changed, versioned, parents, names, kind,
672
846
             executable) in iterator:
673
847
            if (self.interesting_ids is not None and
674
848
                file_id not in self.interesting_ids):
675
849
                continue
676
 
            if file_id in self.this_tree.inventory:
677
 
                entry = self.this_tree.inventory[file_id]
 
850
            entry = this_entries.get(file_id)
 
851
            if entry is not None:
678
852
                this_name = entry.name
679
853
                this_parent = entry.parent_id
680
854
                this_executable = entry.executable
783
957
            content_changed = True
784
958
            if kind_winner == 'this':
785
959
                # No kind change in OTHER, see if there are *any* changes
786
 
                if other_ie.kind == None:
787
 
                    # No content and 'this' wins the kind, so skip this?
788
 
                    # continue
789
 
                    pass
790
 
                elif other_ie.kind == 'directory':
 
960
                if other_ie.kind == 'directory':
791
961
                    if parent_id_winner == 'this' and name_winner == 'this':
792
962
                        # No change for this directory in OTHER, skip
793
963
                        continue
794
964
                    content_changed = False
795
 
                elif other_ie.kind == 'file':
 
965
                elif other_ie.kind is None or other_ie.kind == 'file':
796
966
                    def get_sha1(ie, tree):
797
967
                        if ie.kind != 'file':
798
968
                            return None
845
1015
                        continue
846
1016
                else:
847
1017
                    raise AssertionError('unhandled kind: %s' % other_ie.kind)
848
 
                # XXX: We need to handle kind == 'symlink'
849
1018
 
850
1019
            # If we have gotten this far, that means something has changed
851
1020
            result.append((file_id, content_changed,
862
1031
    def fix_root(self):
863
1032
        try:
864
1033
            self.tt.final_kind(self.tt.root)
865
 
        except NoSuchFile:
 
1034
        except errors.NoSuchFile:
866
1035
            self.tt.cancel_deletion(self.tt.root)
867
1036
        if self.tt.final_file_id(self.tt.root) is None:
868
 
            self.tt.version_file(self.tt.tree_file_id(self.tt.root), 
 
1037
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
869
1038
                                 self.tt.root)
870
 
        if self.other_tree.inventory.root is None:
871
 
            return
872
1039
        other_root_file_id = self.other_tree.get_root_id()
 
1040
        if other_root_file_id is None:
 
1041
            return
873
1042
        other_root = self.tt.trans_id_file_id(other_root_file_id)
874
1043
        if other_root == self.tt.root:
875
1044
            return
 
1045
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
 
1046
            # the other tree's root is a non-root in the current tree (as when
 
1047
            # a previously unrelated branch is merged into another)
 
1048
            return
876
1049
        try:
877
1050
            self.tt.final_kind(other_root)
878
 
        except NoSuchFile:
879
 
            return
880
 
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
881
 
            # the other tree's root is a non-root in the current tree
882
 
            return
883
 
        self.reparent_children(self.other_tree.inventory.root, self.tt.root)
884
 
        self.tt.cancel_creation(other_root)
885
 
        self.tt.cancel_versioning(other_root)
886
 
 
887
 
    def reparent_children(self, ie, target):
888
 
        for thing, child in ie.children.iteritems():
 
1051
            other_root_is_present = True
 
1052
        except errors.NoSuchFile:
 
1053
            # other_root doesn't have a physical representation. We still need
 
1054
            # to move any references to the actual root of the tree.
 
1055
            other_root_is_present = False
 
1056
        # 'other_tree.inventory.root' is not present in this tree. We are
 
1057
        # calling adjust_path for children which *want* to be present with a
 
1058
        # correct place to go.
 
1059
        for thing, child in self.other_tree.inventory.root.children.iteritems():
889
1060
            trans_id = self.tt.trans_id_file_id(child.file_id)
890
 
            self.tt.adjust_path(self.tt.final_name(trans_id), target, trans_id)
 
1061
            if not other_root_is_present:
 
1062
                # FIXME: Make final_kind returns None instead of raising
 
1063
                # NoSuchFile to avoid the ugly construct below -- vila 20100402
 
1064
                try:
 
1065
                    self.tt.final_kind(trans_id)
 
1066
                    # The item exist in the final tree and has a defined place
 
1067
                    # to go already.
 
1068
                    continue
 
1069
                except errors.NoSuchFile, e:
 
1070
                    pass
 
1071
            # Move the item into the root
 
1072
            self.tt.adjust_path(self.tt.final_name(trans_id),
 
1073
                                self.tt.root, trans_id)
 
1074
        if other_root_is_present:
 
1075
            self.tt.cancel_creation(other_root)
 
1076
            self.tt.cancel_versioning(other_root)
891
1077
 
892
1078
    def write_modified(self, results):
893
1079
        modified_hashes = {}
914
1100
        if entry is None:
915
1101
            return None
916
1102
        return entry.name
917
 
    
 
1103
 
918
1104
    @staticmethod
919
1105
    def contents_sha1(tree, file_id):
920
1106
        """Determine the sha1 of the file contents (used as a key method)."""
925
1111
    @staticmethod
926
1112
    def executable(tree, file_id):
927
1113
        """Determine the executability of a file-id (used as a key method)."""
928
 
        if file_id not in tree:
 
1114
        if not tree.has_id(file_id):
929
1115
            return None
930
1116
        if tree.kind(file_id) != "file":
931
1117
            return False
934
1120
    @staticmethod
935
1121
    def kind(tree, file_id):
936
1122
        """Determine the kind of a file-id (used as a key method)."""
937
 
        if file_id not in tree:
 
1123
        if not tree.has_id(file_id):
938
1124
            return None
939
1125
        return tree.kind(file_id)
940
1126
 
941
1127
    @staticmethod
942
1128
    def _three_way(base, other, this):
943
 
        #if base == other, either they all agree, or only THIS has changed.
944
1129
        if base == other:
 
1130
            # if 'base == other', either they all agree, or only 'this' has
 
1131
            # changed.
945
1132
            return 'this'
946
1133
        elif this not in (base, other):
 
1134
            # 'this' is neither 'base' nor 'other', so both sides changed
947
1135
            return 'conflict'
948
 
        # "Ambiguous clean merge" -- both sides have made the same change.
949
1136
        elif this == other:
 
1137
            # "Ambiguous clean merge" -- both sides have made the same change.
950
1138
            return "this"
951
 
        # this == base: only other has changed.
952
1139
        else:
 
1140
            # this == base: only other has changed.
953
1141
            return "other"
954
1142
 
955
1143
    @staticmethod
968
1156
        :return: 'this', 'other', or 'conflict' depending on whether an entry
969
1157
            changed or not.
970
1158
        """
971
 
        # See doc/developers/lca_merge_resolution.txt for details about this
 
1159
        # See doc/developers/lca_tree_merging.txt for details about this
972
1160
        # algorithm.
973
1161
        if other == this:
974
1162
            # Either Ambiguously clean, or nothing was actually changed. We
999
1187
                # only has an lca value
1000
1188
                return 'other'
1001
1189
 
1002
 
        # At this point, the lcas disagree, and the tips disagree
 
1190
        # At this point, the lcas disagree, and the tip disagree
1003
1191
        return 'conflict'
1004
1192
 
1005
1193
    @staticmethod
 
1194
    @deprecated_method(deprecated_in((2, 2, 0)))
1006
1195
    def scalar_three_way(this_tree, base_tree, other_tree, file_id, key):
1007
1196
        """Do a three-way test on a scalar.
1008
1197
        Return "this", "other" or "conflict", depending whether a value wins.
1023
1212
 
1024
1213
    def merge_names(self, file_id):
1025
1214
        def get_entry(tree):
1026
 
            if file_id in tree.inventory:
 
1215
            if tree.has_id(file_id):
1027
1216
                return tree.inventory[file_id]
1028
1217
            else:
1029
1218
                return None
1058
1247
                parent_id_winner = "other"
1059
1248
        if name_winner == "this" and parent_id_winner == "this":
1060
1249
            return
1061
 
        if name_winner == "conflict":
1062
 
            trans_id = self.tt.trans_id_file_id(file_id)
1063
 
            self._raw_conflicts.append(('name conflict', trans_id, 
1064
 
                                        this_name, other_name))
1065
 
        if parent_id_winner == "conflict":
1066
 
            trans_id = self.tt.trans_id_file_id(file_id)
1067
 
            self._raw_conflicts.append(('parent conflict', trans_id, 
1068
 
                                        this_parent, other_parent))
 
1250
        if name_winner == 'conflict' or parent_id_winner == 'conflict':
 
1251
            # Creating helpers (.OTHER or .THIS) here cause problems down the
 
1252
            # road if a ContentConflict needs to be created so we should not do
 
1253
            # that
 
1254
            trans_id = self.tt.trans_id_file_id(file_id)
 
1255
            self._raw_conflicts.append(('path conflict', trans_id, file_id,
 
1256
                                        this_parent, this_name,
 
1257
                                        other_parent, other_name))
1069
1258
        if other_name is None:
1070
 
            # it doesn't matter whether the result was 'other' or 
 
1259
            # it doesn't matter whether the result was 'other' or
1071
1260
            # 'conflict'-- if there's no 'other', we leave it alone.
1072
1261
            return
1073
 
        # if we get here, name_winner and parent_winner are set to safe values.
1074
 
        trans_id = self.tt.trans_id_file_id(file_id)
1075
1262
        parent_id = parents[self.winner_idx[parent_id_winner]]
1076
1263
        if parent_id is not None:
1077
 
            parent_trans_id = self.tt.trans_id_file_id(parent_id)
 
1264
            # if we get here, name_winner and parent_winner are set to safe
 
1265
            # values.
1078
1266
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1079
 
                                parent_trans_id, trans_id)
 
1267
                                self.tt.trans_id_file_id(parent_id),
 
1268
                                self.tt.trans_id_file_id(file_id))
1080
1269
 
1081
 
    def merge_contents(self, file_id):
1082
 
        """Performa a merge on file_id contents."""
 
1270
    def _do_merge_contents(self, file_id):
 
1271
        """Performs a merge on file_id contents."""
1083
1272
        def contents_pair(tree):
1084
1273
            if file_id not in tree:
1085
1274
                return (None, None)
1092
1281
                contents = None
1093
1282
            return kind, contents
1094
1283
 
1095
 
        def contents_conflict():
1096
 
            trans_id = self.tt.trans_id_file_id(file_id)
1097
 
            name = self.tt.final_name(trans_id)
1098
 
            parent_id = self.tt.final_parent(trans_id)
1099
 
            if file_id in self.this_tree.inventory:
1100
 
                self.tt.unversion_file(trans_id)
1101
 
                if file_id in self.this_tree:
1102
 
                    self.tt.delete_contents(trans_id)
1103
 
            file_group = self._dump_conflicts(name, parent_id, file_id, 
1104
 
                                              set_version=True)
1105
 
            self._raw_conflicts.append(('contents conflict', file_group))
1106
 
 
1107
1284
        # See SPOT run.  run, SPOT, run.
1108
1285
        # So we're not QUITE repeating ourselves; we do tricky things with
1109
1286
        # file kind...
1110
1287
        base_pair = contents_pair(self.base_tree)
1111
1288
        other_pair = contents_pair(self.other_tree)
1112
 
        if base_pair == other_pair:
1113
 
            # OTHER introduced no changes
1114
 
            return "unmodified"
1115
 
        this_pair = contents_pair(self.this_tree)
1116
 
        if this_pair == other_pair:
1117
 
            # THIS and OTHER introduced the same changes
1118
 
            return "unmodified"
1119
 
        else:
1120
 
            trans_id = self.tt.trans_id_file_id(file_id)
1121
 
            if this_pair == base_pair:
1122
 
                # only OTHER introduced changes
1123
 
                if file_id in self.this_tree:
1124
 
                    # Remove any existing contents
1125
 
                    self.tt.delete_contents(trans_id)
1126
 
                if file_id in self.other_tree:
1127
 
                    # OTHER changed the file
1128
 
                    create_by_entry(self.tt, 
1129
 
                                    self.other_tree.inventory[file_id], 
1130
 
                                    self.other_tree, trans_id)
1131
 
                    if file_id not in self.this_tree.inventory:
1132
 
                        self.tt.version_file(file_id, trans_id)
1133
 
                    return "modified"
1134
 
                elif file_id in self.this_tree.inventory:
1135
 
                    # OTHER deleted the file
1136
 
                    self.tt.unversion_file(trans_id)
1137
 
                    return "deleted"
1138
 
            #BOTH THIS and OTHER introduced changes; scalar conflict
1139
 
            elif this_pair[0] == "file" and other_pair[0] == "file":
1140
 
                # THIS and OTHER are both files, so text merge.  Either
1141
 
                # BASE is a file, or both converted to files, so at least we
1142
 
                # have agreement that output should be a file.
1143
 
                try:
1144
 
                    self.text_merge(file_id, trans_id)
1145
 
                except BinaryFile:
1146
 
                    return contents_conflict()
1147
 
                if file_id not in self.this_tree.inventory:
1148
 
                    self.tt.version_file(file_id, trans_id)
1149
 
                try:
1150
 
                    self.tt.tree_kind(trans_id)
1151
 
                    self.tt.delete_contents(trans_id)
1152
 
                except NoSuchFile:
1153
 
                    pass
1154
 
                return "modified"
1155
 
            else:
1156
 
                # Scalar conflict, can't text merge.  Dump conflicts
1157
 
                return contents_conflict()
 
1289
        if self._lca_trees:
 
1290
            this_pair = contents_pair(self.this_tree)
 
1291
            lca_pairs = [contents_pair(tree) for tree in self._lca_trees]
 
1292
            winner = self._lca_multi_way((base_pair, lca_pairs), other_pair,
 
1293
                                         this_pair, allow_overriding_lca=False)
 
1294
        else:
 
1295
            if base_pair == other_pair:
 
1296
                winner = 'this'
 
1297
            else:
 
1298
                # We delayed evaluating this_pair as long as we can to avoid
 
1299
                # unnecessary sha1 calculation
 
1300
                this_pair = contents_pair(self.this_tree)
 
1301
                winner = self._three_way(base_pair, other_pair, this_pair)
 
1302
        if winner == 'this':
 
1303
            # No interesting changes introduced by OTHER
 
1304
            return "unmodified"
 
1305
        # We have a hypothetical conflict, but if we have files, then we
 
1306
        # can try to merge the content
 
1307
        trans_id = self.tt.trans_id_file_id(file_id)
 
1308
        params = MergeHookParams(self, file_id, trans_id, this_pair[0],
 
1309
            other_pair[0], winner)
 
1310
        hooks = self.active_hooks
 
1311
        hook_status = 'not_applicable'
 
1312
        for hook in hooks:
 
1313
            hook_status, lines = hook.merge_contents(params)
 
1314
            if hook_status != 'not_applicable':
 
1315
                # Don't try any more hooks, this one applies.
 
1316
                break
 
1317
        result = "modified"
 
1318
        if hook_status == 'not_applicable':
 
1319
            # This is a contents conflict, because none of the available
 
1320
            # functions could merge it.
 
1321
            result = None
 
1322
            name = self.tt.final_name(trans_id)
 
1323
            parent_id = self.tt.final_parent(trans_id)
 
1324
            if self.this_tree.has_id(file_id):
 
1325
                self.tt.unversion_file(trans_id)
 
1326
            file_group = self._dump_conflicts(name, parent_id, file_id,
 
1327
                                              set_version=True)
 
1328
            self._raw_conflicts.append(('contents conflict', file_group))
 
1329
        elif hook_status == 'success':
 
1330
            self.tt.create_file(lines, trans_id)
 
1331
        elif hook_status == 'conflicted':
 
1332
            # XXX: perhaps the hook should be able to provide
 
1333
            # the BASE/THIS/OTHER files?
 
1334
            self.tt.create_file(lines, trans_id)
 
1335
            self._raw_conflicts.append(('text conflict', trans_id))
 
1336
            name = self.tt.final_name(trans_id)
 
1337
            parent_id = self.tt.final_parent(trans_id)
 
1338
            self._dump_conflicts(name, parent_id, file_id)
 
1339
        elif hook_status == 'delete':
 
1340
            self.tt.unversion_file(trans_id)
 
1341
            result = "deleted"
 
1342
        elif hook_status == 'done':
 
1343
            # The hook function did whatever it needs to do directly, no
 
1344
            # further action needed here.
 
1345
            pass
 
1346
        else:
 
1347
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
 
1348
        if not self.this_tree.has_id(file_id) and result == "modified":
 
1349
            self.tt.version_file(file_id, trans_id)
 
1350
        # The merge has been performed, so the old contents should not be
 
1351
        # retained.
 
1352
        try:
 
1353
            self.tt.delete_contents(trans_id)
 
1354
        except errors.NoSuchFile:
 
1355
            pass
 
1356
        return result
 
1357
 
 
1358
    def _default_other_winner_merge(self, merge_hook_params):
 
1359
        """Replace this contents with other."""
 
1360
        file_id = merge_hook_params.file_id
 
1361
        trans_id = merge_hook_params.trans_id
 
1362
        file_in_this = self.this_tree.has_id(file_id)
 
1363
        if self.other_tree.has_id(file_id):
 
1364
            # OTHER changed the file
 
1365
            wt = self.this_tree
 
1366
            if wt.supports_content_filtering():
 
1367
                # We get the path from the working tree if it exists.
 
1368
                # That fails though when OTHER is adding a file, so
 
1369
                # we fall back to the other tree to find the path if
 
1370
                # it doesn't exist locally.
 
1371
                try:
 
1372
                    filter_tree_path = wt.id2path(file_id)
 
1373
                except errors.NoSuchId:
 
1374
                    filter_tree_path = self.other_tree.id2path(file_id)
 
1375
            else:
 
1376
                # Skip the id2path lookup for older formats
 
1377
                filter_tree_path = None
 
1378
            transform.create_from_tree(self.tt, trans_id,
 
1379
                             self.other_tree, file_id,
 
1380
                             filter_tree_path=filter_tree_path)
 
1381
            return 'done', None
 
1382
        elif file_in_this:
 
1383
            # OTHER deleted the file
 
1384
            return 'delete', None
 
1385
        else:
 
1386
            raise AssertionError(
 
1387
                'winner is OTHER, but file_id %r not in THIS or OTHER tree'
 
1388
                % (file_id,))
 
1389
 
 
1390
    def merge_contents(self, merge_hook_params):
 
1391
        """Fallback merge logic after user installed hooks."""
 
1392
        # This function is used in merge hooks as the fallback instance.
 
1393
        # Perhaps making this function and the functions it calls be a 
 
1394
        # a separate class would be better.
 
1395
        if merge_hook_params.winner == 'other':
 
1396
            # OTHER is a straight winner, so replace this contents with other
 
1397
            return self._default_other_winner_merge(merge_hook_params)
 
1398
        elif merge_hook_params.is_file_merge():
 
1399
            # THIS and OTHER are both files, so text merge.  Either
 
1400
            # BASE is a file, or both converted to files, so at least we
 
1401
            # have agreement that output should be a file.
 
1402
            try:
 
1403
                self.text_merge(merge_hook_params.file_id,
 
1404
                    merge_hook_params.trans_id)
 
1405
            except errors.BinaryFile:
 
1406
                return 'not_applicable', None
 
1407
            return 'done', None
 
1408
        else:
 
1409
            return 'not_applicable', None
1158
1410
 
1159
1411
    def get_lines(self, tree, file_id):
1160
1412
        """Return the lines in a file, or an empty list."""
1161
 
        if file_id in tree:
 
1413
        if tree.has_id(file_id):
1162
1414
            return tree.get_file(file_id).readlines()
1163
1415
        else:
1164
1416
            return []
1167
1419
        """Perform a three-way text merge on a file_id"""
1168
1420
        # it's possible that we got here with base as a different type.
1169
1421
        # if so, we just want two-way text conflicts.
1170
 
        if file_id in self.base_tree and \
 
1422
        if self.base_tree.has_id(file_id) and \
1171
1423
            self.base_tree.kind(file_id) == "file":
1172
1424
            base_lines = self.get_lines(self.base_tree, file_id)
1173
1425
        else:
1174
1426
            base_lines = []
1175
1427
        other_lines = self.get_lines(self.other_tree, file_id)
1176
1428
        this_lines = self.get_lines(self.this_tree, file_id)
1177
 
        m3 = Merge3(base_lines, this_lines, other_lines,
1178
 
                    is_cherrypick=self.cherrypick)
 
1429
        m3 = merge3.Merge3(base_lines, this_lines, other_lines,
 
1430
                           is_cherrypick=self.cherrypick)
1179
1431
        start_marker = "!START OF MERGE CONFLICT!" + "I HOPE THIS IS UNIQUE"
1180
1432
        if self.show_base is True:
1181
1433
            base_marker = '|' * 7
1184
1436
 
1185
1437
        def iter_merge3(retval):
1186
1438
            retval["text_conflicts"] = False
1187
 
            for line in m3.merge_lines(name_a = "TREE", 
1188
 
                                       name_b = "MERGE-SOURCE", 
 
1439
            for line in m3.merge_lines(name_a = "TREE",
 
1440
                                       name_b = "MERGE-SOURCE",
1189
1441
                                       name_base = "BASE-REVISION",
1190
 
                                       start_marker=start_marker, 
 
1442
                                       start_marker=start_marker,
1191
1443
                                       base_marker=base_marker,
1192
1444
                                       reprocess=self.reprocess):
1193
1445
                if line.startswith(start_marker):
1202
1454
            self._raw_conflicts.append(('text conflict', trans_id))
1203
1455
            name = self.tt.final_name(trans_id)
1204
1456
            parent_id = self.tt.final_parent(trans_id)
1205
 
            file_group = self._dump_conflicts(name, parent_id, file_id, 
 
1457
            file_group = self._dump_conflicts(name, parent_id, file_id,
1206
1458
                                              this_lines, base_lines,
1207
1459
                                              other_lines)
1208
1460
            file_group.append(trans_id)
1209
1461
 
1210
 
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None, 
 
1462
    def _dump_conflicts(self, name, parent_id, file_id, this_lines=None,
1211
1463
                        base_lines=None, other_lines=None, set_version=False,
1212
1464
                        no_base=False):
1213
1465
        """Emit conflict files.
1215
1467
        determined automatically.  If set_version is true, the .OTHER, .THIS
1216
1468
        or .BASE (in that order) will be created as versioned files.
1217
1469
        """
1218
 
        data = [('OTHER', self.other_tree, other_lines), 
 
1470
        data = [('OTHER', self.other_tree, other_lines),
1219
1471
                ('THIS', self.this_tree, this_lines)]
1220
1472
        if not no_base:
1221
1473
            data.append(('BASE', self.base_tree, base_lines))
 
1474
 
 
1475
        # We need to use the actual path in the working tree of the file here,
 
1476
        # ignoring the conflict suffixes
 
1477
        wt = self.this_tree
 
1478
        if wt.supports_content_filtering():
 
1479
            try:
 
1480
                filter_tree_path = wt.id2path(file_id)
 
1481
            except errors.NoSuchId:
 
1482
                # file has been deleted
 
1483
                filter_tree_path = None
 
1484
        else:
 
1485
            # Skip the id2path lookup for older formats
 
1486
            filter_tree_path = None
 
1487
 
1222
1488
        versioned = False
1223
1489
        file_group = []
1224
1490
        for suffix, tree, lines in data:
1225
 
            if file_id in tree:
 
1491
            if tree.has_id(file_id):
1226
1492
                trans_id = self._conflict_file(name, parent_id, tree, file_id,
1227
 
                                               suffix, lines)
 
1493
                                               suffix, lines, filter_tree_path)
1228
1494
                file_group.append(trans_id)
1229
1495
                if set_version and not versioned:
1230
1496
                    self.tt.version_file(file_id, trans_id)
1231
1497
                    versioned = True
1232
1498
        return file_group
1233
 
           
1234
 
    def _conflict_file(self, name, parent_id, tree, file_id, suffix, 
1235
 
                       lines=None):
 
1499
 
 
1500
    def _conflict_file(self, name, parent_id, tree, file_id, suffix,
 
1501
                       lines=None, filter_tree_path=None):
1236
1502
        """Emit a single conflict file."""
1237
1503
        name = name + '.' + suffix
1238
1504
        trans_id = self.tt.create_path(name, parent_id)
1239
 
        entry = tree.inventory[file_id]
1240
 
        create_by_entry(self.tt, entry, tree, trans_id, lines)
 
1505
        transform.create_from_tree(self.tt, trans_id, tree, file_id, lines,
 
1506
            filter_tree_path)
1241
1507
        return trans_id
1242
1508
 
1243
1509
    def merge_executable(self, file_id, file_status):
1267
1533
        try:
1268
1534
            if self.tt.final_kind(trans_id) != "file":
1269
1535
                return
1270
 
        except NoSuchFile:
 
1536
        except errors.NoSuchFile:
1271
1537
            return
1272
1538
        if winner == "this":
1273
1539
            executability = this_executable
1274
1540
        else:
1275
 
            if file_id in self.other_tree:
 
1541
            if self.other_tree.has_id(file_id):
1276
1542
                executability = other_executable
1277
 
            elif file_id in self.this_tree:
 
1543
            elif self.this_tree.has_id(file_id):
1278
1544
                executability = this_executable
1279
 
            elif file_id in self.base_tree:
 
1545
            elif self.base_tree_has_id(file_id):
1280
1546
                executability = base_executable
1281
1547
        if executability is not None:
1282
1548
            trans_id = self.tt.trans_id_file_id(file_id)
1284
1550
 
1285
1551
    def cook_conflicts(self, fs_conflicts):
1286
1552
        """Convert all conflicts into a form that doesn't depend on trans_id"""
1287
 
        from conflicts import Conflict
1288
 
        name_conflicts = {}
1289
 
        self.cooked_conflicts.extend(cook_conflicts(fs_conflicts, self.tt))
1290
 
        fp = FinalPaths(self.tt)
 
1553
        self.cooked_conflicts.extend(transform.cook_conflicts(
 
1554
                fs_conflicts, self.tt))
 
1555
        fp = transform.FinalPaths(self.tt)
1291
1556
        for conflict in self._raw_conflicts:
1292
1557
            conflict_type = conflict[0]
1293
 
            if conflict_type in ('name conflict', 'parent conflict'):
1294
 
                trans_id = conflict[1]
1295
 
                conflict_args = conflict[2:]
1296
 
                if trans_id not in name_conflicts:
1297
 
                    name_conflicts[trans_id] = {}
1298
 
                unique_add(name_conflicts[trans_id], conflict_type, 
1299
 
                           conflict_args)
1300
 
            if conflict_type == 'contents conflict':
 
1558
            if conflict_type == 'path conflict':
 
1559
                (trans_id, file_id,
 
1560
                this_parent, this_name,
 
1561
                other_parent, other_name) = conflict[1:]
 
1562
                if this_parent is None or this_name is None:
 
1563
                    this_path = '<deleted>'
 
1564
                else:
 
1565
                    parent_path =  fp.get_path(
 
1566
                        self.tt.trans_id_file_id(this_parent))
 
1567
                    this_path = osutils.pathjoin(parent_path, this_name)
 
1568
                if other_parent is None or other_name is None:
 
1569
                    other_path = '<deleted>'
 
1570
                else:
 
1571
                    parent_path =  fp.get_path(
 
1572
                        self.tt.trans_id_file_id(other_parent))
 
1573
                    other_path = osutils.pathjoin(parent_path, other_name)
 
1574
                c = _mod_conflicts.Conflict.factory(
 
1575
                    'path conflict', path=this_path,
 
1576
                    conflict_path=other_path,
 
1577
                    file_id=file_id)
 
1578
            elif conflict_type == 'contents conflict':
1301
1579
                for trans_id in conflict[1]:
1302
1580
                    file_id = self.tt.final_file_id(trans_id)
1303
1581
                    if file_id is not None:
1307
1585
                    if path.endswith(suffix):
1308
1586
                        path = path[:-len(suffix)]
1309
1587
                        break
1310
 
                c = Conflict.factory(conflict_type, path=path, file_id=file_id)
1311
 
                self.cooked_conflicts.append(c)
1312
 
            if conflict_type == 'text conflict':
 
1588
                c = _mod_conflicts.Conflict.factory(conflict_type,
 
1589
                                                    path=path, file_id=file_id)
 
1590
            elif conflict_type == 'text conflict':
1313
1591
                trans_id = conflict[1]
1314
1592
                path = fp.get_path(trans_id)
1315
1593
                file_id = self.tt.final_file_id(trans_id)
1316
 
                c = Conflict.factory(conflict_type, path=path, file_id=file_id)
1317
 
                self.cooked_conflicts.append(c)
1318
 
 
1319
 
        for trans_id, conflicts in name_conflicts.iteritems():
1320
 
            try:
1321
 
                this_parent, other_parent = conflicts['parent conflict']
1322
 
                if this_parent == other_parent:
1323
 
                    raise AssertionError()
1324
 
            except KeyError:
1325
 
                this_parent = other_parent = \
1326
 
                    self.tt.final_file_id(self.tt.final_parent(trans_id))
1327
 
            try:
1328
 
                this_name, other_name = conflicts['name conflict']
1329
 
                if this_name == other_name:
1330
 
                    raise AssertionError()
1331
 
            except KeyError:
1332
 
                this_name = other_name = self.tt.final_name(trans_id)
1333
 
            other_path = fp.get_path(trans_id)
1334
 
            if this_parent is not None and this_name is not None:
1335
 
                this_parent_path = \
1336
 
                    fp.get_path(self.tt.trans_id_file_id(this_parent))
1337
 
                this_path = pathjoin(this_parent_path, this_name)
 
1594
                c = _mod_conflicts.Conflict.factory(conflict_type,
 
1595
                                                    path=path, file_id=file_id)
1338
1596
            else:
1339
 
                this_path = "<deleted>"
1340
 
            file_id = self.tt.final_file_id(trans_id)
1341
 
            c = Conflict.factory('path conflict', path=this_path,
1342
 
                                 conflict_path=other_path, file_id=file_id)
 
1597
                raise AssertionError('bad conflict type: %r' % (conflict,))
1343
1598
            self.cooked_conflicts.append(c)
1344
 
        self.cooked_conflicts.sort(key=Conflict.sort_key)
 
1599
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
1345
1600
 
1346
1601
 
1347
1602
class WeaveMerger(Merge3Merger):
1351
1606
    supports_reverse_cherrypick = False
1352
1607
    history_based = True
1353
1608
 
1354
 
    def _merged_lines(self, file_id):
1355
 
        """Generate the merged lines.
1356
 
        There is no distinction between lines that are meant to contain <<<<<<<
1357
 
        and conflicts.
1358
 
        """
1359
 
        if self.cherrypick:
1360
 
            base = self.base_tree
1361
 
        else:
1362
 
            base = None
1363
 
        plan = self.this_tree.plan_file_merge(file_id, self.other_tree,
 
1609
    def _generate_merge_plan(self, file_id, base):
 
1610
        return self.this_tree.plan_file_merge(file_id, self.other_tree,
1364
1611
                                              base=base)
 
1612
 
 
1613
    def _merged_lines(self, file_id):
 
1614
        """Generate the merged lines.
 
1615
        There is no distinction between lines that are meant to contain <<<<<<<
 
1616
        and conflicts.
 
1617
        """
 
1618
        if self.cherrypick:
 
1619
            base = self.base_tree
 
1620
        else:
 
1621
            base = None
 
1622
        plan = self._generate_merge_plan(file_id, base)
1365
1623
        if 'merge' in debug.debug_flags:
1366
1624
            plan = list(plan)
1367
1625
            trans_id = self.tt.trans_id_file_id(file_id)
1368
1626
            name = self.tt.final_name(trans_id) + '.plan'
1369
 
            contents = ('%10s|%s' % l for l in plan)
 
1627
            contents = ('%11s|%s' % l for l in plan)
1370
1628
            self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
1371
 
        textmerge = PlanWeaveMerge(plan, '<<<<<<< TREE\n',
1372
 
            '>>>>>>> MERGE-SOURCE\n')
1373
 
        return textmerge.merge_lines(self.reprocess)
 
1629
        textmerge = versionedfile.PlanWeaveMerge(plan, '<<<<<<< TREE\n',
 
1630
                                                 '>>>>>>> MERGE-SOURCE\n')
 
1631
        lines, conflicts = textmerge.merge_lines(self.reprocess)
 
1632
        if conflicts:
 
1633
            base_lines = textmerge.base_from_plan()
 
1634
        else:
 
1635
            base_lines = None
 
1636
        return lines, base_lines
1374
1637
 
1375
1638
    def text_merge(self, file_id, trans_id):
1376
1639
        """Perform a (weave) text merge for a given file and file-id.
1377
1640
        If conflicts are encountered, .THIS and .OTHER files will be emitted,
1378
1641
        and a conflict will be noted.
1379
1642
        """
1380
 
        lines, conflicts = self._merged_lines(file_id)
 
1643
        lines, base_lines = self._merged_lines(file_id)
1381
1644
        lines = list(lines)
1382
 
        # Note we're checking whether the OUTPUT is binary in this case, 
 
1645
        # Note we're checking whether the OUTPUT is binary in this case,
1383
1646
        # because we don't want to get into weave merge guts.
1384
 
        check_text_lines(lines)
 
1647
        textfile.check_text_lines(lines)
1385
1648
        self.tt.create_file(lines, trans_id)
1386
 
        if conflicts:
 
1649
        if base_lines is not None:
 
1650
            # Conflict
1387
1651
            self._raw_conflicts.append(('text conflict', trans_id))
1388
1652
            name = self.tt.final_name(trans_id)
1389
1653
            parent_id = self.tt.final_parent(trans_id)
1390
 
            file_group = self._dump_conflicts(name, parent_id, file_id, 
1391
 
                                              no_base=True)
 
1654
            file_group = self._dump_conflicts(name, parent_id, file_id,
 
1655
                                              no_base=False,
 
1656
                                              base_lines=base_lines)
1392
1657
            file_group.append(trans_id)
1393
1658
 
1394
1659
 
1395
1660
class LCAMerger(WeaveMerger):
1396
1661
 
1397
 
    def _merged_lines(self, file_id):
1398
 
        """Generate the merged lines.
1399
 
        There is no distinction between lines that are meant to contain <<<<<<<
1400
 
        and conflicts.
1401
 
        """
1402
 
        if self.cherrypick:
1403
 
            base = self.base_tree
1404
 
        else:
1405
 
            base = None
1406
 
        plan = self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
 
1662
    def _generate_merge_plan(self, file_id, base):
 
1663
        return self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
1407
1664
                                                  base=base)
1408
 
        if 'merge' in debug.debug_flags:
1409
 
            plan = list(plan)
1410
 
            trans_id = self.tt.trans_id_file_id(file_id)
1411
 
            name = self.tt.final_name(trans_id) + '.plan'
1412
 
            contents = ('%10s|%s' % l for l in plan)
1413
 
            self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
1414
 
        textmerge = PlanWeaveMerge(plan, '<<<<<<< TREE\n',
1415
 
            '>>>>>>> MERGE-SOURCE\n')
1416
 
        return textmerge.merge_lines(self.reprocess)
1417
 
 
1418
1665
 
1419
1666
class Diff3Merger(Merge3Merger):
1420
1667
    """Three-way merger using external diff3 for text merging"""
1421
1668
 
1422
1669
    def dump_file(self, temp_dir, name, tree, file_id):
1423
 
        out_path = pathjoin(temp_dir, name)
 
1670
        out_path = osutils.pathjoin(temp_dir, name)
1424
1671
        out_file = open(out_path, "wb")
1425
1672
        try:
1426
1673
            in_file = tree.get_file(file_id)
1438
1685
        import bzrlib.patch
1439
1686
        temp_dir = osutils.mkdtemp(prefix="bzr-")
1440
1687
        try:
1441
 
            new_file = pathjoin(temp_dir, "new")
 
1688
            new_file = osutils.pathjoin(temp_dir, "new")
1442
1689
            this = self.dump_file(temp_dir, "this", self.this_tree, file_id)
1443
1690
            base = self.dump_file(temp_dir, "base", self.base_tree, file_id)
1444
1691
            other = self.dump_file(temp_dir, "other", self.other_tree, file_id)
1445
1692
            status = bzrlib.patch.diff3(new_file, this, base, other)
1446
1693
            if status not in (0, 1):
1447
 
                raise BzrError("Unhandled diff3 exit code")
 
1694
                raise errors.BzrError("Unhandled diff3 exit code")
1448
1695
            f = open(new_file, 'rb')
1449
1696
            try:
1450
1697
                self.tt.create_file(f, trans_id)
1468
1715
                other_rev_id=None,
1469
1716
                interesting_files=None,
1470
1717
                this_tree=None,
1471
 
                pb=DummyProgress(),
 
1718
                pb=None,
1472
1719
                change_reporter=None):
1473
 
    """Primary interface for merging. 
 
1720
    """Primary interface for merging.
1474
1721
 
1475
 
        typical use is probably 
 
1722
        typical use is probably
1476
1723
        'merge_inner(branch, branch.get_revision_tree(other_revision),
1477
1724
                     branch.get_revision_tree(base_revision))'
1478
1725
        """
1479
1726
    if this_tree is None:
1480
 
        raise BzrError("bzrlib.merge.merge_inner requires a this_tree "
1481
 
            "parameter as of bzrlib version 0.8.")
 
1727
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
 
1728
                              "parameter as of bzrlib version 0.8.")
1482
1729
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1483
1730
                    pb=pb, change_reporter=change_reporter)
1484
1731
    merger.backup_files = backup_files
1497
1744
    get_revision_id = getattr(base_tree, 'get_revision_id', None)
1498
1745
    if get_revision_id is None:
1499
1746
        get_revision_id = base_tree.last_revision
 
1747
    merger.cache_trees_with_revision_ids([other_tree, base_tree, this_tree])
1500
1748
    merger.set_base_revision(get_revision_id(), this_branch)
1501
1749
    return merger.do_merge()
1502
1750
 
1570
1818
 
1571
1819
    def get_lines(self, revisions):
1572
1820
        """Get lines for revisions from the backing VersionedFiles.
1573
 
        
 
1821
 
1574
1822
        :raises RevisionNotPresent: on absent texts.
1575
1823
        """
1576
1824
        keys = [(self._key_prefix + (rev,)) for rev in revisions]
1578
1826
        for record in self.vf.get_record_stream(keys, 'unordered', True):
1579
1827
            if record.storage_kind == 'absent':
1580
1828
                raise errors.RevisionNotPresent(record.key, self.vf)
1581
 
            result[record.key[-1]] = osutils.split_lines(
1582
 
                record.get_bytes_as('fulltext'))
 
1829
            result[record.key[-1]] = osutils.chunks_to_lines(
 
1830
                record.get_bytes_as('chunked'))
1583
1831
        return result
1584
1832
 
1585
1833
    def plan_merge(self):
1701
1949
        super(_PlanMerge, self).__init__(a_rev, b_rev, vf, key_prefix)
1702
1950
        self.a_key = self._key_prefix + (self.a_rev,)
1703
1951
        self.b_key = self._key_prefix + (self.b_rev,)
1704
 
        self.graph = Graph(self.vf)
 
1952
        self.graph = _mod_graph.Graph(self.vf)
1705
1953
        heads = self.graph.heads((self.a_key, self.b_key))
1706
1954
        if len(heads) == 1:
1707
1955
            # one side dominates, so we can just return its values, yay for
1712
1960
                other = b_rev
1713
1961
            else:
1714
1962
                other = a_rev
1715
 
            mutter('found dominating revision for %s\n%s > %s', self.vf,
1716
 
                   self._head_key[-1], other)
 
1963
            trace.mutter('found dominating revision for %s\n%s > %s', self.vf,
 
1964
                         self._head_key[-1], other)
1717
1965
            self._weave = None
1718
1966
        else:
1719
1967
            self._head_key = None
1733
1981
        while True:
1734
1982
            next_lcas = self.graph.find_lca(*cur_ancestors)
1735
1983
            # Map a plain NULL_REVISION to a simple no-ancestors
1736
 
            if next_lcas == set([NULL_REVISION]):
 
1984
            if next_lcas == set([_mod_revision.NULL_REVISION]):
1737
1985
                next_lcas = ()
1738
1986
            # Order the lca's based on when they were merged into the tip
1739
1987
            # While the actual merge portion of weave merge uses a set() of
1751
1999
            elif len(next_lcas) > 2:
1752
2000
                # More than 2 lca's, fall back to grabbing all nodes between
1753
2001
                # this and the unique lca.
1754
 
                mutter('More than 2 LCAs, falling back to all nodes for:'
1755
 
                       ' %s, %s\n=> %s', self.a_key, self.b_key, cur_ancestors)
 
2002
                trace.mutter('More than 2 LCAs, falling back to all nodes for:'
 
2003
                             ' %s, %s\n=> %s',
 
2004
                             self.a_key, self.b_key, cur_ancestors)
1756
2005
                cur_lcas = next_lcas
1757
2006
                while len(cur_lcas) > 1:
1758
2007
                    cur_lcas = self.graph.find_lca(*cur_lcas)
1761
2010
                    unique_lca = None
1762
2011
                else:
1763
2012
                    unique_lca = list(cur_lcas)[0]
1764
 
                    if unique_lca == NULL_REVISION:
 
2013
                    if unique_lca == _mod_revision.NULL_REVISION:
1765
2014
                        # find_lca will return a plain 'NULL_REVISION' rather
1766
2015
                        # than a key tuple when there is no common ancestor, we
1767
2016
                        # prefer to just use None, because it doesn't confuse
1775
2024
 
1776
2025
    def _find_unique_parents(self, tip_keys, base_key):
1777
2026
        """Find ancestors of tip that aren't ancestors of base.
1778
 
        
 
2027
 
1779
2028
        :param tip_keys: Nodes that are interesting
1780
2029
        :param base_key: Cull all ancestors of this node
1781
2030
        :return: The parent map for all revisions between tip_keys and
1790
2039
            # We remove NULL_REVISION because it isn't a proper tuple key, and
1791
2040
            # thus confuses things like _get_interesting_texts, and our logic
1792
2041
            # to add the texts into the memory weave.
1793
 
            if NULL_REVISION in parent_map:
1794
 
                parent_map.pop(NULL_REVISION)
 
2042
            if _mod_revision.NULL_REVISION in parent_map:
 
2043
                parent_map.pop(_mod_revision.NULL_REVISION)
1795
2044
        else:
1796
2045
            interesting = set()
1797
2046
            for tip in tip_keys:
1841
2090
    @staticmethod
1842
2091
    def _prune_tails(parent_map, child_map, tails_to_remove):
1843
2092
        """Remove tails from the parent map.
1844
 
        
 
2093
 
1845
2094
        This will remove the supplied revisions until no more children have 0
1846
2095
        parents.
1847
2096
 
1949
2198
        lcas = graph.find_lca(key_prefix + (a_rev,), key_prefix + (b_rev,))
1950
2199
        self.lcas = set()
1951
2200
        for lca in lcas:
1952
 
            if lca == NULL_REVISION:
 
2201
            if lca == _mod_revision.NULL_REVISION:
1953
2202
                self.lcas.add(lca)
1954
2203
            else:
1955
2204
                self.lcas.add(lca[-1])