~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge.py

  • Committer: John Ferlito
  • Date: 2009-05-25 10:59:42 UTC
  • mto: (4665.4.1 ppa-doc)
  • mto: This revision was merged to the branch mainline in revision 4693.
  • Revision ID: johnf@inodes.org-20090525105942-5xkcbe37m1u5lp5z
Update packaging scripts to make deployment a bit easier
Update documentation for deploying to PPA

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008 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
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
 
18
import errno
 
19
from itertools import chain
 
20
import os
 
21
import warnings
 
22
 
18
23
from bzrlib import (
19
 
    branch as _mod_branch,
20
 
    conflicts as _mod_conflicts,
21
24
    debug,
22
 
    decorators,
23
25
    errors,
24
26
    graph as _mod_graph,
25
 
    hooks,
26
 
    merge3,
27
27
    osutils,
28
28
    patiencediff,
29
 
    progress,
 
29
    registry,
30
30
    revision as _mod_revision,
31
 
    textfile,
32
 
    trace,
33
 
    transform,
34
31
    tree as _mod_tree,
35
32
    tsort,
36
 
    ui,
37
 
    versionedfile
38
 
    )
39
 
from bzrlib.symbol_versioning import (
40
 
    deprecated_in,
41
 
    deprecated_method,
42
 
    )
 
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_from_tree,
 
59
                              unique_add, ROOT_PARENT)
 
60
from bzrlib.versionedfile import PlanWeaveMerge
 
61
from bzrlib import ui
 
62
 
43
63
# TODO: Report back as changes are merged in
44
64
 
45
65
 
46
66
def transform_tree(from_tree, to_tree, interesting_ids=None):
47
 
    from_tree.lock_tree_write()
48
 
    try:
49
 
        merge_inner(from_tree.branch, to_tree, from_tree, ignore_zero=True,
50
 
                    interesting_ids=interesting_ids, this_tree=from_tree)
51
 
    finally:
52
 
        from_tree.unlock()
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
 
    :ivar affected_files: The configured file paths to merge.
103
 
    :cvar name_prefix: The prefix to use when looking up configuration
104
 
        details.
105
 
    :cvar default_files: The default file paths to merge when no configuration
106
 
        is present.
107
 
    """
108
 
 
109
 
    name_prefix = None
110
 
    default_files = None
111
 
 
112
 
    def __init__(self, merger):
113
 
        super(ConfigurableFileMerger, self).__init__(merger)
114
 
        self.affected_files = None
115
 
        self.default_files = self.__class__.default_files or []
116
 
        self.name_prefix = self.__class__.name_prefix
117
 
        if self.name_prefix is None:
118
 
            raise ValueError("name_prefix must be set.")
119
 
 
120
 
    def filename_matches_config(self, params):
121
 
        affected_files = self.affected_files
122
 
        if affected_files is None:
123
 
            config = self.merger.this_tree.branch.get_config()
124
 
            # Until bzr provides a better policy for caching the config, we
125
 
            # just add the part we're interested in to the params to avoid
126
 
            # reading the config files repeatedly (bazaar.conf, location.conf,
127
 
            # branch.conf).
128
 
            config_key = self.name_prefix + '_merge_files'
129
 
            affected_files = config.get_user_option_as_list(config_key)
130
 
            if affected_files is None:
131
 
                # If nothing was specified in the config, use the default.
132
 
                affected_files = self.default_files
133
 
            self.affected_files = affected_files
134
 
        if affected_files:
135
 
            filename = self.merger.this_tree.id2path(params.file_id)
136
 
            if filename in affected_files:
137
 
                return True
138
 
        return False
139
 
 
140
 
    def merge_contents(self, params):
141
 
        """Merge the contents of a single file."""
142
 
        # First, check whether this custom merge logic should be used.  We
143
 
        # expect most files should not be merged by this handler.
144
 
        if (
145
 
            # OTHER is a straight winner, rely on default merge.
146
 
            params.winner == 'other' or
147
 
            # THIS and OTHER aren't both files.
148
 
            not params.is_file_merge() or
149
 
            # The filename isn't listed in the 'NAME_merge_files' config
150
 
            # option.
151
 
            not self.filename_matches_config(params)):
152
 
            return 'not_applicable', None
153
 
        return self.merge_text(self, params)
154
 
 
155
 
    def merge_text(self, params):
156
 
        """Merge the byte contents of a single file.
157
 
 
158
 
        This is called after checking that the merge should be performed in
159
 
        merge_contents, and it should behave as per
160
 
        ``bzrlib.merge.AbstractPerFileMerger.merge_contents``.
161
 
        """
162
 
        raise NotImplementedError(self.merge_text)
163
 
 
164
 
 
165
 
class MergeHookParams(object):
166
 
    """Object holding parameters passed to merge_file_content hooks.
167
 
 
168
 
    There are some fields hooks can access:
169
 
 
170
 
    :ivar file_id: the file ID of the file being merged
171
 
    :ivar trans_id: the transform ID for the merge of this file
172
 
    :ivar this_kind: kind of file_id in 'this' tree
173
 
    :ivar other_kind: kind of file_id in 'other' tree
174
 
    :ivar winner: one of 'this', 'other', 'conflict'
175
 
    """
176
 
 
177
 
    def __init__(self, merger, file_id, trans_id, this_kind, other_kind,
178
 
            winner):
179
 
        self._merger = merger
180
 
        self.file_id = file_id
181
 
        self.trans_id = trans_id
182
 
        self.this_kind = this_kind
183
 
        self.other_kind = other_kind
184
 
        self.winner = winner
185
 
 
186
 
    def is_file_merge(self):
187
 
        """True if this_kind and other_kind are both 'file'."""
188
 
        return self.this_kind == 'file' and self.other_kind == 'file'
189
 
 
190
 
    @decorators.cachedproperty
191
 
    def base_lines(self):
192
 
        """The lines of the 'base' version of the file."""
193
 
        return self._merger.get_lines(self._merger.base_tree, self.file_id)
194
 
 
195
 
    @decorators.cachedproperty
196
 
    def this_lines(self):
197
 
        """The lines of the 'this' version of the file."""
198
 
        return self._merger.get_lines(self._merger.this_tree, self.file_id)
199
 
 
200
 
    @decorators.cachedproperty
201
 
    def other_lines(self):
202
 
        """The lines of the 'other' version of the file."""
203
 
        return self._merger.get_lines(self._merger.other_tree, self.file_id)
 
67
    merge_inner(from_tree.branch, to_tree, from_tree, ignore_zero=True,
 
68
                interesting_ids=interesting_ids, this_tree=from_tree)
204
69
 
205
70
 
206
71
class Merger(object):
207
 
 
208
 
    hooks = MergeHooks()
209
 
 
210
72
    def __init__(self, this_branch, other_tree=None, base_tree=None,
211
73
                 this_tree=None, pb=None, change_reporter=None,
212
74
                 recurse='down', revision_graph=None):
228
90
        self.show_base = False
229
91
        self.reprocess = False
230
92
        if pb is None:
231
 
            pb = progress.DummyProgress()
 
93
            pb = DummyProgress()
232
94
        self._pb = pb
233
95
        self.pp = None
234
96
        self.recurse = recurse
240
102
        self._is_criss_cross = None
241
103
        self._lca_trees = None
242
104
 
243
 
    def cache_trees_with_revision_ids(self, trees):
244
 
        """Cache any tree in trees if it has a revision_id."""
245
 
        for maybe_tree in trees:
246
 
            if maybe_tree is None:
247
 
                continue
248
 
            try:
249
 
                rev_id = maybe_tree.get_revision_id()
250
 
            except AttributeError:
251
 
                continue
252
 
            self._cached_trees[rev_id] = maybe_tree
253
 
 
254
105
    @property
255
106
    def revision_graph(self):
256
107
        if self._revision_graph is None:
318
169
                base_revision_id, tree.branch.last_revision())):
319
170
                base_revision_id = None
320
171
            else:
321
 
                trace.warning('Performing cherrypick')
 
172
                warning('Performing cherrypick')
322
173
        merger = klass.from_revision_ids(pb, tree, other_revision_id,
323
174
                                         base_revision_id, revision_graph=
324
175
                                         revision_graph)
376
227
        if revno is None:
377
228
            tree = workingtree.WorkingTree.open_containing(location)[0]
378
229
            return tree.branch, tree
379
 
        branch = _mod_branch.Branch.open_containing(
380
 
            location, possible_transports)[0]
 
230
        branch = Branch.open_containing(location, possible_transports)[0]
381
231
        if revno == -1:
382
232
            revision_id = branch.last_revision()
383
233
        else:
384
234
            revision_id = branch.get_rev_id(revno)
385
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
235
        revision_id = ensure_null(revision_id)
386
236
        return branch, self.revision_tree(revision_id, branch)
387
237
 
388
 
    @deprecated_method(deprecated_in((2, 1, 0)))
389
238
    def ensure_revision_trees(self):
390
239
        if self.this_revision_tree is None:
391
240
            self.this_basis_tree = self.revision_tree(self.this_basis)
394
243
 
395
244
        if self.other_rev_id is None:
396
245
            other_basis_tree = self.revision_tree(self.other_basis)
397
 
            if other_basis_tree.has_changes(self.other_tree):
398
 
                raise errors.WorkingTreeNotRevision(self.this_tree)
 
246
            changes = other_basis_tree.changes_from(self.other_tree)
 
247
            if changes.has_changed():
 
248
                raise WorkingTreeNotRevision(self.this_tree)
399
249
            other_rev_id = self.other_basis
400
250
            self.other_tree = other_basis_tree
401
251
 
402
 
    @deprecated_method(deprecated_in((2, 1, 0)))
403
252
    def file_revisions(self, file_id):
404
253
        self.ensure_revision_trees()
405
254
        def get_id(tree, file_id):
408
257
        if self.this_rev_id is None:
409
258
            if self.this_basis_tree.get_file_sha1(file_id) != \
410
259
                self.this_tree.get_file_sha1(file_id):
411
 
                raise errors.WorkingTreeNotRevision(self.this_tree)
 
260
                raise WorkingTreeNotRevision(self.this_tree)
412
261
 
413
262
        trees = (self.this_basis_tree, self.other_tree)
414
263
        return [get_id(tree, file_id) for tree in trees]
415
264
 
416
 
    @deprecated_method(deprecated_in((2, 1, 0)))
417
265
    def check_basis(self, check_clean, require_commits=True):
418
266
        if self.this_basis is None and require_commits is True:
419
 
            raise errors.BzrCommandError(
420
 
                "This branch has no commits."
421
 
                " (perhaps you would prefer 'bzr pull')")
 
267
            raise BzrCommandError("This branch has no commits."
 
268
                                  " (perhaps you would prefer 'bzr pull')")
422
269
        if check_clean:
423
270
            self.compare_basis()
424
271
            if self.this_basis != self.this_rev_id:
425
272
                raise errors.UncommittedChanges(self.this_tree)
426
273
 
427
 
    @deprecated_method(deprecated_in((2, 1, 0)))
428
274
    def compare_basis(self):
429
275
        try:
430
276
            basis_tree = self.revision_tree(self.this_tree.last_revision())
431
277
        except errors.NoSuchRevision:
432
278
            basis_tree = self.this_tree.basis_tree()
433
 
        if not self.this_tree.has_changes(basis_tree):
 
279
        changes = self.this_tree.changes_from(basis_tree)
 
280
        if not changes.has_changed():
434
281
            self.this_rev_id = self.this_basis
435
282
 
436
283
    def set_interesting_files(self, file_list):
437
284
        self.interesting_files = file_list
438
285
 
439
286
    def set_pending(self):
440
 
        if (not self.base_is_ancestor or not self.base_is_other_ancestor
441
 
            or self.other_rev_id is None):
 
287
        if not self.base_is_ancestor or not self.base_is_other_ancestor or self.other_rev_id is None:
442
288
            return
443
289
        self._add_parent()
444
290
 
474
320
            self.other_rev_id = _mod_revision.ensure_null(
475
321
                self.other_branch.last_revision())
476
322
            if _mod_revision.is_null(self.other_rev_id):
477
 
                raise errors.NoCommits(self.other_branch)
 
323
                raise NoCommits(self.other_branch)
478
324
            self.other_basis = self.other_rev_id
479
325
        elif other_revision[1] is not None:
480
326
            self.other_rev_id = self.other_branch.get_rev_id(other_revision[1])
483
329
            self.other_rev_id = None
484
330
            self.other_basis = self.other_branch.last_revision()
485
331
            if self.other_basis is None:
486
 
                raise errors.NoCommits(self.other_branch)
 
332
                raise NoCommits(self.other_branch)
487
333
        if self.other_rev_id is not None:
488
334
            self._cached_trees[self.other_rev_id] = self.other_tree
489
335
        self._maybe_fetch(self.other_branch,self.this_branch, self.other_basis)
516
362
            target.fetch(source, revision_id)
517
363
 
518
364
    def find_base(self):
519
 
        revisions = [_mod_revision.ensure_null(self.this_basis),
520
 
                     _mod_revision.ensure_null(self.other_basis)]
521
 
        if _mod_revision.NULL_REVISION in revisions:
522
 
            self.base_rev_id = _mod_revision.NULL_REVISION
 
365
        revisions = [ensure_null(self.this_basis),
 
366
                     ensure_null(self.other_basis)]
 
367
        if NULL_REVISION in revisions:
 
368
            self.base_rev_id = NULL_REVISION
523
369
            self.base_tree = self.revision_tree(self.base_rev_id)
524
370
            self._is_criss_cross = False
525
371
        else:
526
372
            lcas = self.revision_graph.find_lca(revisions[0], revisions[1])
527
373
            self._is_criss_cross = False
528
374
            if len(lcas) == 0:
529
 
                self.base_rev_id = _mod_revision.NULL_REVISION
 
375
                self.base_rev_id = NULL_REVISION
530
376
            elif len(lcas) == 1:
531
377
                self.base_rev_id = list(lcas)[0]
532
378
            else: # len(lcas) > 1
541
387
                    self.base_rev_id = self.revision_graph.find_unique_lca(
542
388
                                            *lcas)
543
389
                self._is_criss_cross = True
544
 
            if self.base_rev_id == _mod_revision.NULL_REVISION:
545
 
                raise errors.UnrelatedBranches()
 
390
            if self.base_rev_id == NULL_REVISION:
 
391
                raise UnrelatedBranches()
546
392
            if self._is_criss_cross:
547
 
                trace.warning('Warning: criss-cross merge encountered.  See bzr'
548
 
                              ' help criss-cross.')
549
 
                trace.mutter('Criss-cross lcas: %r' % lcas)
 
393
                warning('Warning: criss-cross merge encountered.  See bzr'
 
394
                        ' help criss-cross.')
 
395
                mutter('Criss-cross lcas: %r' % lcas)
550
396
                interesting_revision_ids = [self.base_rev_id]
551
397
                interesting_revision_ids.extend(lcas)
552
398
                interesting_trees = dict((t.get_revision_id(), t)
562
408
                self.base_tree = self.revision_tree(self.base_rev_id)
563
409
        self.base_is_ancestor = True
564
410
        self.base_is_other_ancestor = True
565
 
        trace.mutter('Base revid: %r' % self.base_rev_id)
 
411
        mutter('Base revid: %r' % self.base_rev_id)
566
412
 
567
413
    def set_base(self, base_revision):
568
414
        """Set the base revision to use for the merge.
569
415
 
570
416
        :param base_revision: A 2-list containing a path and revision number.
571
417
        """
572
 
        trace.mutter("doing merge() with no base_revision specified")
 
418
        mutter("doing merge() with no base_revision specified")
573
419
        if base_revision == [None, None]:
574
420
            self.find_base()
575
421
        else:
588
434
                  'other_tree': self.other_tree,
589
435
                  'interesting_ids': self.interesting_ids,
590
436
                  'interesting_files': self.interesting_files,
591
 
                  'pp': self.pp, 'this_branch': self.this_branch,
 
437
                  'pp': self.pp,
592
438
                  'do_merge': False}
593
439
        if self.merge_type.requires_base:
594
440
            kwargs['base_tree'] = self.base_tree
595
441
        if self.merge_type.supports_reprocess:
596
442
            kwargs['reprocess'] = self.reprocess
597
443
        elif self.reprocess:
598
 
            raise errors.BzrError(
599
 
                "Conflict reduction is not supported for merge"
600
 
                " type %s." % self.merge_type)
 
444
            raise BzrError("Conflict reduction is not supported for merge"
 
445
                                  " type %s." % self.merge_type)
601
446
        if self.merge_type.supports_show_base:
602
447
            kwargs['show_base'] = self.show_base
603
448
        elif self.show_base:
604
 
            raise errors.BzrError("Showing base is not supported for this"
605
 
                                  " merge type. %s" % self.merge_type)
 
449
            raise BzrError("Showing base is not supported for this"
 
450
                           " merge type. %s" % self.merge_type)
606
451
        if (not getattr(self.merge_type, 'supports_reverse_cherrypick', True)
607
452
            and not self.base_is_other_ancestor):
608
453
            raise errors.CannotReverseCherrypick()
657
502
        finally:
658
503
            self.this_tree.unlock()
659
504
        if len(merge.cooked_conflicts) == 0:
660
 
            if not self.ignore_zero and not trace.is_quiet():
661
 
                trace.note("All changes applied successfully.")
 
505
            if not self.ignore_zero and not is_quiet():
 
506
                note("All changes applied successfully.")
662
507
        else:
663
 
            trace.note("%d conflicts encountered."
664
 
                       % len(merge.cooked_conflicts))
 
508
            note("%d conflicts encountered." % len(merge.cooked_conflicts))
665
509
 
666
510
        return len(merge.cooked_conflicts)
667
511
 
696
540
 
697
541
    def __init__(self, working_tree, this_tree, base_tree, other_tree,
698
542
                 interesting_ids=None, reprocess=False, show_base=False,
699
 
                 pb=progress.DummyProgress(), pp=None, change_reporter=None,
 
543
                 pb=DummyProgress(), pp=None, change_reporter=None,
700
544
                 interesting_files=None, do_merge=True,
701
 
                 cherrypick=False, lca_trees=None, this_branch=None):
 
545
                 cherrypick=False, lca_trees=None):
702
546
        """Initialize the merger object and perform the merge.
703
547
 
704
548
        :param working_tree: The working tree to apply the merge to
705
549
        :param this_tree: The local tree in the merge operation
706
550
        :param base_tree: The common tree in the merge operation
707
551
        :param other_tree: The other tree to merge changes from
708
 
        :param this_branch: The branch associated with this_tree
709
552
        :param interesting_ids: The file_ids of files that should be
710
553
            participate in the merge.  May not be combined with
711
554
            interesting_files.
734
577
        self.this_tree = working_tree
735
578
        self.base_tree = base_tree
736
579
        self.other_tree = other_tree
737
 
        self.this_branch = this_branch
738
580
        self._raw_conflicts = []
739
581
        self.cooked_conflicts = []
740
582
        self.reprocess = reprocess
750
592
        self.change_reporter = change_reporter
751
593
        self.cherrypick = cherrypick
752
594
        if self.pp is None:
753
 
            self.pp = progress.ProgressPhase("Merge phase", 3, self.pb)
 
595
            self.pp = ProgressPhase("Merge phase", 3, self.pb)
754
596
        if do_merge:
755
597
            self.do_merge()
756
598
 
758
600
        self.this_tree.lock_tree_write()
759
601
        self.base_tree.lock_read()
760
602
        self.other_tree.lock_read()
 
603
        self.tt = TreeTransform(self.this_tree, self.pb)
761
604
        try:
762
 
            self.tt = transform.TreeTransform(self.this_tree, self.pb)
 
605
            self.pp.next_phase()
 
606
            self._compute_transform()
 
607
            self.pp.next_phase()
 
608
            results = self.tt.apply(no_conflicts=True)
 
609
            self.write_modified(results)
763
610
            try:
764
 
                self.pp.next_phase()
765
 
                self._compute_transform()
766
 
                self.pp.next_phase()
767
 
                results = self.tt.apply(no_conflicts=True)
768
 
                self.write_modified(results)
769
 
                try:
770
 
                    self.this_tree.add_conflicts(self.cooked_conflicts)
771
 
                except errors.UnsupportedOperation:
772
 
                    pass
773
 
            finally:
774
 
                self.tt.finalize()
 
611
                self.this_tree.add_conflicts(self.cooked_conflicts)
 
612
            except UnsupportedOperation:
 
613
                pass
775
614
        finally:
 
615
            self.tt.finalize()
776
616
            self.other_tree.unlock()
777
617
            self.base_tree.unlock()
778
618
            self.this_tree.unlock()
781
621
    def make_preview_transform(self):
782
622
        self.base_tree.lock_read()
783
623
        self.other_tree.lock_read()
784
 
        self.tt = transform.TransformPreview(self.this_tree)
 
624
        self.tt = TransformPreview(self.this_tree)
785
625
        try:
786
626
            self.pp.next_phase()
787
627
            self._compute_transform()
801
641
            resolver = self._lca_multi_way
802
642
        child_pb = ui.ui_factory.nested_progress_bar()
803
643
        try:
804
 
            factories = Merger.hooks['merge_file_content']
805
 
            hooks = [factory(self) for factory in factories] + [self]
806
 
            self.active_hooks = [hook for hook in hooks if hook is not None]
807
644
            for num, (file_id, changed, parents3, names3,
808
645
                      executable3) in enumerate(entries):
809
646
                child_pb.update('Preparing file merge', num, len(entries))
810
647
                self._merge_names(file_id, parents3, names3, resolver=resolver)
811
648
                if changed:
812
 
                    file_status = self._do_merge_contents(file_id)
 
649
                    file_status = self.merge_contents(file_id)
813
650
                else:
814
651
                    file_status = 'unmodified'
815
652
                self._merge_executable(file_id,
820
657
        self.pp.next_phase()
821
658
        child_pb = ui.ui_factory.nested_progress_bar()
822
659
        try:
823
 
            fs_conflicts = transform.resolve_conflicts(self.tt, child_pb,
824
 
                lambda t, c: transform.conflict_pass(t, c, self.other_tree))
 
660
            fs_conflicts = resolve_conflicts(self.tt, child_pb,
 
661
                lambda t, c: conflict_pass(t, c, self.other_tree))
825
662
        finally:
826
663
            child_pb.finished()
827
664
        if self.change_reporter is not None:
830
667
                self.tt.iter_changes(), self.change_reporter)
831
668
        self.cook_conflicts(fs_conflicts)
832
669
        for conflict in self.cooked_conflicts:
833
 
            trace.warning(conflict)
 
670
            warning(conflict)
834
671
 
835
672
    def _entries3(self):
836
673
        """Gather data about files modified between three trees.
1038
875
    def fix_root(self):
1039
876
        try:
1040
877
            self.tt.final_kind(self.tt.root)
1041
 
        except errors.NoSuchFile:
 
878
        except NoSuchFile:
1042
879
            self.tt.cancel_deletion(self.tt.root)
1043
880
        if self.tt.final_file_id(self.tt.root) is None:
1044
881
            self.tt.version_file(self.tt.tree_file_id(self.tt.root),
1051
888
            return
1052
889
        try:
1053
890
            self.tt.final_kind(other_root)
1054
 
        except errors.NoSuchFile:
 
891
        except NoSuchFile:
1055
892
            return
1056
 
        if self.this_tree.has_id(self.other_tree.inventory.root.file_id):
 
893
        if self.other_tree.inventory.root.file_id in self.this_tree.inventory:
1057
894
            # the other tree's root is a non-root in the current tree
1058
895
            return
1059
896
        self.reparent_children(self.other_tree.inventory.root, self.tt.root)
1101
938
    @staticmethod
1102
939
    def executable(tree, file_id):
1103
940
        """Determine the executability of a file-id (used as a key method)."""
1104
 
        if not tree.has_id(file_id):
 
941
        if file_id not in tree:
1105
942
            return None
1106
943
        if tree.kind(file_id) != "file":
1107
944
            return False
1110
947
    @staticmethod
1111
948
    def kind(tree, file_id):
1112
949
        """Determine the kind of a file-id (used as a key method)."""
1113
 
        if not tree.has_id(file_id):
 
950
        if file_id not in tree:
1114
951
            return None
1115
952
        return tree.kind(file_id)
1116
953
 
1199
1036
 
1200
1037
    def merge_names(self, file_id):
1201
1038
        def get_entry(tree):
1202
 
            if tree.has_id(file_id):
 
1039
            if file_id in tree.inventory:
1203
1040
                return tree.inventory[file_id]
1204
1041
            else:
1205
1042
                return None
1254
1091
            self.tt.adjust_path(names[self.winner_idx[name_winner]],
1255
1092
                                parent_trans_id, trans_id)
1256
1093
 
1257
 
    def _do_merge_contents(self, file_id):
 
1094
    def merge_contents(self, file_id):
1258
1095
        """Performs a merge on file_id contents."""
1259
1096
        def contents_pair(tree):
1260
1097
            if file_id not in tree:
1268
1105
                contents = None
1269
1106
            return kind, contents
1270
1107
 
 
1108
        def contents_conflict():
 
1109
            trans_id = self.tt.trans_id_file_id(file_id)
 
1110
            name = self.tt.final_name(trans_id)
 
1111
            parent_id = self.tt.final_parent(trans_id)
 
1112
            if file_id in self.this_tree.inventory:
 
1113
                self.tt.unversion_file(trans_id)
 
1114
                if file_id in self.this_tree:
 
1115
                    self.tt.delete_contents(trans_id)
 
1116
            file_group = self._dump_conflicts(name, parent_id, file_id,
 
1117
                                              set_version=True)
 
1118
            self._raw_conflicts.append(('contents conflict', file_group))
 
1119
 
1271
1120
        # See SPOT run.  run, SPOT, run.
1272
1121
        # So we're not QUITE repeating ourselves; we do tricky things with
1273
1122
        # file kind...
1289
1138
        if winner == 'this':
1290
1139
            # No interesting changes introduced by OTHER
1291
1140
            return "unmodified"
1292
 
        # We have a hypothetical conflict, but if we have files, then we
1293
 
        # can try to merge the content
1294
1141
        trans_id = self.tt.trans_id_file_id(file_id)
1295
 
        params = MergeHookParams(self, file_id, trans_id, this_pair[0],
1296
 
            other_pair[0], winner)
1297
 
        hooks = self.active_hooks
1298
 
        hook_status = 'not_applicable'
1299
 
        for hook in hooks:
1300
 
            hook_status, lines = hook.merge_contents(params)
1301
 
            if hook_status != 'not_applicable':
1302
 
                # Don't try any more hooks, this one applies.
1303
 
                break
1304
 
        result = "modified"
1305
 
        if hook_status == 'not_applicable':
1306
 
            # This is a contents conflict, because none of the available
1307
 
            # functions could merge it.
1308
 
            result = None
1309
 
            name = self.tt.final_name(trans_id)
1310
 
            parent_id = self.tt.final_parent(trans_id)
1311
 
            if self.this_tree.has_id(file_id):
1312
 
                self.tt.unversion_file(trans_id)
1313
 
            file_group = self._dump_conflicts(name, parent_id, file_id,
1314
 
                                              set_version=True)
1315
 
            self._raw_conflicts.append(('contents conflict', file_group))
1316
 
        elif hook_status == 'success':
1317
 
            self.tt.create_file(lines, trans_id)
1318
 
        elif hook_status == 'conflicted':
1319
 
            # XXX: perhaps the hook should be able to provide
1320
 
            # the BASE/THIS/OTHER files?
1321
 
            self.tt.create_file(lines, trans_id)
1322
 
            self._raw_conflicts.append(('text conflict', trans_id))
1323
 
            name = self.tt.final_name(trans_id)
1324
 
            parent_id = self.tt.final_parent(trans_id)
1325
 
            self._dump_conflicts(name, parent_id, file_id)
1326
 
        elif hook_status == 'delete':
1327
 
            self.tt.unversion_file(trans_id)
1328
 
            result = "deleted"
1329
 
        elif hook_status == 'done':
1330
 
            # The hook function did whatever it needs to do directly, no
1331
 
            # further action needed here.
1332
 
            pass
1333
 
        else:
1334
 
            raise AssertionError('unknown hook_status: %r' % (hook_status,))
1335
 
        if not self.this_tree.has_id(file_id) and result == "modified":
1336
 
            self.tt.version_file(file_id, trans_id)
1337
 
        # The merge has been performed, so the old contents should not be
1338
 
        # retained.
1339
 
        try:
1340
 
            self.tt.delete_contents(trans_id)
1341
 
        except errors.NoSuchFile:
1342
 
            pass
1343
 
        return result
1344
 
 
1345
 
    def _default_other_winner_merge(self, merge_hook_params):
1346
 
        """Replace this contents with other."""
1347
 
        file_id = merge_hook_params.file_id
1348
 
        trans_id = merge_hook_params.trans_id
1349
 
        file_in_this = self.this_tree.has_id(file_id)
1350
 
        if self.other_tree.has_id(file_id):
1351
 
            # OTHER changed the file
1352
 
            wt = self.this_tree
1353
 
            if wt.supports_content_filtering():
1354
 
                # We get the path from the working tree if it exists.
1355
 
                # That fails though when OTHER is adding a file, so
1356
 
                # we fall back to the other tree to find the path if
1357
 
                # it doesn't exist locally.
1358
 
                try:
1359
 
                    filter_tree_path = wt.id2path(file_id)
1360
 
                except errors.NoSuchId:
1361
 
                    filter_tree_path = self.other_tree.id2path(file_id)
1362
 
            else:
1363
 
                # Skip the id2path lookup for older formats
1364
 
                filter_tree_path = None
1365
 
            transform.create_from_tree(self.tt, trans_id,
1366
 
                             self.other_tree, file_id,
1367
 
                             filter_tree_path=filter_tree_path)
1368
 
            return 'done', None
1369
 
        elif file_in_this:
1370
 
            # OTHER deleted the file
1371
 
            return 'delete', None
1372
 
        else:
1373
 
            raise AssertionError(
1374
 
                'winner is OTHER, but file_id %r not in THIS or OTHER tree'
1375
 
                % (file_id,))
1376
 
 
1377
 
    def merge_contents(self, merge_hook_params):
1378
 
        """Fallback merge logic after user installed hooks."""
1379
 
        # This function is used in merge hooks as the fallback instance.
1380
 
        # Perhaps making this function and the functions it calls be a 
1381
 
        # a separate class would be better.
1382
 
        if merge_hook_params.winner == 'other':
 
1142
        if winner == 'other':
1383
1143
            # OTHER is a straight winner, so replace this contents with other
1384
 
            return self._default_other_winner_merge(merge_hook_params)
1385
 
        elif merge_hook_params.is_file_merge():
1386
 
            # THIS and OTHER are both files, so text merge.  Either
1387
 
            # BASE is a file, or both converted to files, so at least we
1388
 
            # have agreement that output should be a file.
1389
 
            try:
1390
 
                self.text_merge(merge_hook_params.file_id,
1391
 
                    merge_hook_params.trans_id)
1392
 
            except errors.BinaryFile:
1393
 
                return 'not_applicable', None
1394
 
            return 'done', None
 
1144
            file_in_this = file_id in self.this_tree
 
1145
            if file_in_this:
 
1146
                # Remove any existing contents
 
1147
                self.tt.delete_contents(trans_id)
 
1148
            if file_id in self.other_tree:
 
1149
                # OTHER changed the file
 
1150
                create_from_tree(self.tt, trans_id,
 
1151
                                 self.other_tree, file_id)
 
1152
                if not file_in_this:
 
1153
                    self.tt.version_file(file_id, trans_id)
 
1154
                return "modified"
 
1155
            elif file_in_this:
 
1156
                # OTHER deleted the file
 
1157
                self.tt.unversion_file(trans_id)
 
1158
                return "deleted"
1395
1159
        else:
1396
 
            return 'not_applicable', None
 
1160
            # We have a hypothetical conflict, but if we have files, then we
 
1161
            # can try to merge the content
 
1162
            if this_pair[0] == 'file' and other_pair[0] == 'file':
 
1163
                # THIS and OTHER are both files, so text merge.  Either
 
1164
                # BASE is a file, or both converted to files, so at least we
 
1165
                # have agreement that output should be a file.
 
1166
                try:
 
1167
                    self.text_merge(file_id, trans_id)
 
1168
                except BinaryFile:
 
1169
                    return contents_conflict()
 
1170
                if file_id not in self.this_tree:
 
1171
                    self.tt.version_file(file_id, trans_id)
 
1172
                try:
 
1173
                    self.tt.tree_kind(trans_id)
 
1174
                    self.tt.delete_contents(trans_id)
 
1175
                except NoSuchFile:
 
1176
                    pass
 
1177
                return "modified"
 
1178
            else:
 
1179
                return contents_conflict()
1397
1180
 
1398
1181
    def get_lines(self, tree, file_id):
1399
1182
        """Return the lines in a file, or an empty list."""
1400
 
        if tree.has_id(file_id):
 
1183
        if file_id in tree:
1401
1184
            return tree.get_file(file_id).readlines()
1402
1185
        else:
1403
1186
            return []
1406
1189
        """Perform a three-way text merge on a file_id"""
1407
1190
        # it's possible that we got here with base as a different type.
1408
1191
        # if so, we just want two-way text conflicts.
1409
 
        if self.base_tree.has_id(file_id) and \
 
1192
        if file_id in self.base_tree and \
1410
1193
            self.base_tree.kind(file_id) == "file":
1411
1194
            base_lines = self.get_lines(self.base_tree, file_id)
1412
1195
        else:
1413
1196
            base_lines = []
1414
1197
        other_lines = self.get_lines(self.other_tree, file_id)
1415
1198
        this_lines = self.get_lines(self.this_tree, file_id)
1416
 
        m3 = merge3.Merge3(base_lines, this_lines, other_lines,
1417
 
                           is_cherrypick=self.cherrypick)
 
1199
        m3 = Merge3(base_lines, this_lines, other_lines,
 
1200
                    is_cherrypick=self.cherrypick)
1418
1201
        start_marker = "!START OF MERGE CONFLICT!" + "I HOPE THIS IS UNIQUE"
1419
1202
        if self.show_base is True:
1420
1203
            base_marker = '|' * 7
1458
1241
                ('THIS', self.this_tree, this_lines)]
1459
1242
        if not no_base:
1460
1243
            data.append(('BASE', self.base_tree, base_lines))
1461
 
 
1462
 
        # We need to use the actual path in the working tree of the file here,
1463
 
        # ignoring the conflict suffixes
1464
 
        wt = self.this_tree
1465
 
        if wt.supports_content_filtering():
1466
 
            try:
1467
 
                filter_tree_path = wt.id2path(file_id)
1468
 
            except errors.NoSuchId:
1469
 
                # file has been deleted
1470
 
                filter_tree_path = None
1471
 
        else:
1472
 
            # Skip the id2path lookup for older formats
1473
 
            filter_tree_path = None
1474
 
 
1475
1244
        versioned = False
1476
1245
        file_group = []
1477
1246
        for suffix, tree, lines in data:
1478
 
            if tree.has_id(file_id):
 
1247
            if file_id in tree:
1479
1248
                trans_id = self._conflict_file(name, parent_id, tree, file_id,
1480
 
                                               suffix, lines, filter_tree_path)
 
1249
                                               suffix, lines)
1481
1250
                file_group.append(trans_id)
1482
1251
                if set_version and not versioned:
1483
1252
                    self.tt.version_file(file_id, trans_id)
1485
1254
        return file_group
1486
1255
 
1487
1256
    def _conflict_file(self, name, parent_id, tree, file_id, suffix,
1488
 
                       lines=None, filter_tree_path=None):
 
1257
                       lines=None):
1489
1258
        """Emit a single conflict file."""
1490
1259
        name = name + '.' + suffix
1491
1260
        trans_id = self.tt.create_path(name, parent_id)
1492
 
        transform.create_from_tree(self.tt, trans_id, tree, file_id, lines,
1493
 
            filter_tree_path)
 
1261
        create_from_tree(self.tt, trans_id, tree, file_id, lines)
1494
1262
        return trans_id
1495
1263
 
1496
1264
    def merge_executable(self, file_id, file_status):
1520
1288
        try:
1521
1289
            if self.tt.final_kind(trans_id) != "file":
1522
1290
                return
1523
 
        except errors.NoSuchFile:
 
1291
        except NoSuchFile:
1524
1292
            return
1525
1293
        if winner == "this":
1526
1294
            executability = this_executable
1527
1295
        else:
1528
 
            if self.other_tree.has_id(file_id):
 
1296
            if file_id in self.other_tree:
1529
1297
                executability = other_executable
1530
 
            elif self.this_tree.has_id(file_id):
 
1298
            elif file_id in self.this_tree:
1531
1299
                executability = this_executable
1532
 
            elif self.base_tree_has_id(file_id):
 
1300
            elif file_id in self.base_tree:
1533
1301
                executability = base_executable
1534
1302
        if executability is not None:
1535
1303
            trans_id = self.tt.trans_id_file_id(file_id)
1537
1305
 
1538
1306
    def cook_conflicts(self, fs_conflicts):
1539
1307
        """Convert all conflicts into a form that doesn't depend on trans_id"""
 
1308
        from conflicts import Conflict
1540
1309
        name_conflicts = {}
1541
 
        self.cooked_conflicts.extend(transform.cook_conflicts(
1542
 
                fs_conflicts, self.tt))
1543
 
        fp = transform.FinalPaths(self.tt)
 
1310
        self.cooked_conflicts.extend(cook_conflicts(fs_conflicts, self.tt))
 
1311
        fp = FinalPaths(self.tt)
1544
1312
        for conflict in self._raw_conflicts:
1545
1313
            conflict_type = conflict[0]
1546
1314
            if conflict_type in ('name conflict', 'parent conflict'):
1548
1316
                conflict_args = conflict[2:]
1549
1317
                if trans_id not in name_conflicts:
1550
1318
                    name_conflicts[trans_id] = {}
1551
 
                transform.unique_add(name_conflicts[trans_id], conflict_type,
1552
 
                                     conflict_args)
 
1319
                unique_add(name_conflicts[trans_id], conflict_type,
 
1320
                           conflict_args)
1553
1321
            if conflict_type == 'contents conflict':
1554
1322
                for trans_id in conflict[1]:
1555
1323
                    file_id = self.tt.final_file_id(trans_id)
1560
1328
                    if path.endswith(suffix):
1561
1329
                        path = path[:-len(suffix)]
1562
1330
                        break
1563
 
                c = _mod_conflicts.Conflict.factory(conflict_type,
1564
 
                                                    path=path, file_id=file_id)
 
1331
                c = Conflict.factory(conflict_type, path=path, file_id=file_id)
1565
1332
                self.cooked_conflicts.append(c)
1566
1333
            if conflict_type == 'text conflict':
1567
1334
                trans_id = conflict[1]
1568
1335
                path = fp.get_path(trans_id)
1569
1336
                file_id = self.tt.final_file_id(trans_id)
1570
 
                c = _mod_conflicts.Conflict.factory(conflict_type,
1571
 
                                                    path=path, file_id=file_id)
 
1337
                c = Conflict.factory(conflict_type, path=path, file_id=file_id)
1572
1338
                self.cooked_conflicts.append(c)
1573
1339
 
1574
1340
        for trans_id, conflicts in name_conflicts.iteritems():
1589
1355
            if this_parent is not None and this_name is not None:
1590
1356
                this_parent_path = \
1591
1357
                    fp.get_path(self.tt.trans_id_file_id(this_parent))
1592
 
                this_path = osutils.pathjoin(this_parent_path, this_name)
 
1358
                this_path = pathjoin(this_parent_path, this_name)
1593
1359
            else:
1594
1360
                this_path = "<deleted>"
1595
1361
            file_id = self.tt.final_file_id(trans_id)
1596
 
            c = _mod_conflicts.Conflict.factory('path conflict', path=this_path,
1597
 
                                                conflict_path=other_path,
1598
 
                                                file_id=file_id)
 
1362
            c = Conflict.factory('path conflict', path=this_path,
 
1363
                                 conflict_path=other_path, file_id=file_id)
1599
1364
            self.cooked_conflicts.append(c)
1600
 
        self.cooked_conflicts.sort(key=_mod_conflicts.Conflict.sort_key)
 
1365
        self.cooked_conflicts.sort(key=Conflict.sort_key)
1601
1366
 
1602
1367
 
1603
1368
class WeaveMerger(Merge3Merger):
1607
1372
    supports_reverse_cherrypick = False
1608
1373
    history_based = True
1609
1374
 
1610
 
    def _generate_merge_plan(self, file_id, base):
1611
 
        return self.this_tree.plan_file_merge(file_id, self.other_tree,
 
1375
    def _merged_lines(self, file_id):
 
1376
        """Generate the merged lines.
 
1377
        There is no distinction between lines that are meant to contain <<<<<<<
 
1378
        and conflicts.
 
1379
        """
 
1380
        if self.cherrypick:
 
1381
            base = self.base_tree
 
1382
        else:
 
1383
            base = None
 
1384
        plan = self.this_tree.plan_file_merge(file_id, self.other_tree,
1612
1385
                                              base=base)
1613
 
 
1614
 
    def _merged_lines(self, file_id):
1615
 
        """Generate the merged lines.
1616
 
        There is no distinction between lines that are meant to contain <<<<<<<
1617
 
        and conflicts.
1618
 
        """
1619
 
        if self.cherrypick:
1620
 
            base = self.base_tree
1621
 
        else:
1622
 
            base = None
1623
 
        plan = self._generate_merge_plan(file_id, base)
1624
1386
        if 'merge' in debug.debug_flags:
1625
1387
            plan = list(plan)
1626
1388
            trans_id = self.tt.trans_id_file_id(file_id)
1627
1389
            name = self.tt.final_name(trans_id) + '.plan'
1628
 
            contents = ('%11s|%s' % l for l in plan)
 
1390
            contents = ('%10s|%s' % l for l in plan)
1629
1391
            self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
1630
 
        textmerge = versionedfile.PlanWeaveMerge(plan, '<<<<<<< TREE\n',
1631
 
                                                 '>>>>>>> MERGE-SOURCE\n')
1632
 
        lines, conflicts = textmerge.merge_lines(self.reprocess)
1633
 
        if conflicts:
1634
 
            base_lines = textmerge.base_from_plan()
1635
 
        else:
1636
 
            base_lines = None
1637
 
        return lines, base_lines
 
1392
        textmerge = PlanWeaveMerge(plan, '<<<<<<< TREE\n',
 
1393
            '>>>>>>> MERGE-SOURCE\n')
 
1394
        return textmerge.merge_lines(self.reprocess)
1638
1395
 
1639
1396
    def text_merge(self, file_id, trans_id):
1640
1397
        """Perform a (weave) text merge for a given file and file-id.
1641
1398
        If conflicts are encountered, .THIS and .OTHER files will be emitted,
1642
1399
        and a conflict will be noted.
1643
1400
        """
1644
 
        lines, base_lines = self._merged_lines(file_id)
 
1401
        lines, conflicts = self._merged_lines(file_id)
1645
1402
        lines = list(lines)
1646
1403
        # Note we're checking whether the OUTPUT is binary in this case,
1647
1404
        # because we don't want to get into weave merge guts.
1648
 
        textfile.check_text_lines(lines)
 
1405
        check_text_lines(lines)
1649
1406
        self.tt.create_file(lines, trans_id)
1650
 
        if base_lines is not None:
1651
 
            # Conflict
 
1407
        if conflicts:
1652
1408
            self._raw_conflicts.append(('text conflict', trans_id))
1653
1409
            name = self.tt.final_name(trans_id)
1654
1410
            parent_id = self.tt.final_parent(trans_id)
1655
1411
            file_group = self._dump_conflicts(name, parent_id, file_id,
1656
 
                                              no_base=False,
1657
 
                                              base_lines=base_lines)
 
1412
                                              no_base=True)
1658
1413
            file_group.append(trans_id)
1659
1414
 
1660
1415
 
1661
1416
class LCAMerger(WeaveMerger):
1662
1417
 
1663
 
    def _generate_merge_plan(self, file_id, base):
1664
 
        return self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
 
1418
    def _merged_lines(self, file_id):
 
1419
        """Generate the merged lines.
 
1420
        There is no distinction between lines that are meant to contain <<<<<<<
 
1421
        and conflicts.
 
1422
        """
 
1423
        if self.cherrypick:
 
1424
            base = self.base_tree
 
1425
        else:
 
1426
            base = None
 
1427
        plan = self.this_tree.plan_file_lca_merge(file_id, self.other_tree,
1665
1428
                                                  base=base)
 
1429
        if 'merge' in debug.debug_flags:
 
1430
            plan = list(plan)
 
1431
            trans_id = self.tt.trans_id_file_id(file_id)
 
1432
            name = self.tt.final_name(trans_id) + '.plan'
 
1433
            contents = ('%10s|%s' % l for l in plan)
 
1434
            self.tt.new_file(name, self.tt.final_parent(trans_id), contents)
 
1435
        textmerge = PlanWeaveMerge(plan, '<<<<<<< TREE\n',
 
1436
            '>>>>>>> MERGE-SOURCE\n')
 
1437
        return textmerge.merge_lines(self.reprocess)
 
1438
 
1666
1439
 
1667
1440
class Diff3Merger(Merge3Merger):
1668
1441
    """Three-way merger using external diff3 for text merging"""
1669
1442
 
1670
1443
    def dump_file(self, temp_dir, name, tree, file_id):
1671
 
        out_path = osutils.pathjoin(temp_dir, name)
 
1444
        out_path = pathjoin(temp_dir, name)
1672
1445
        out_file = open(out_path, "wb")
1673
1446
        try:
1674
1447
            in_file = tree.get_file(file_id)
1686
1459
        import bzrlib.patch
1687
1460
        temp_dir = osutils.mkdtemp(prefix="bzr-")
1688
1461
        try:
1689
 
            new_file = osutils.pathjoin(temp_dir, "new")
 
1462
            new_file = pathjoin(temp_dir, "new")
1690
1463
            this = self.dump_file(temp_dir, "this", self.this_tree, file_id)
1691
1464
            base = self.dump_file(temp_dir, "base", self.base_tree, file_id)
1692
1465
            other = self.dump_file(temp_dir, "other", self.other_tree, file_id)
1693
1466
            status = bzrlib.patch.diff3(new_file, this, base, other)
1694
1467
            if status not in (0, 1):
1695
 
                raise errors.BzrError("Unhandled diff3 exit code")
 
1468
                raise BzrError("Unhandled diff3 exit code")
1696
1469
            f = open(new_file, 'rb')
1697
1470
            try:
1698
1471
                self.tt.create_file(f, trans_id)
1716
1489
                other_rev_id=None,
1717
1490
                interesting_files=None,
1718
1491
                this_tree=None,
1719
 
                pb=progress.DummyProgress(),
 
1492
                pb=DummyProgress(),
1720
1493
                change_reporter=None):
1721
1494
    """Primary interface for merging.
1722
1495
 
1725
1498
                     branch.get_revision_tree(base_revision))'
1726
1499
        """
1727
1500
    if this_tree is None:
1728
 
        raise errors.BzrError("bzrlib.merge.merge_inner requires a this_tree "
1729
 
                              "parameter as of bzrlib version 0.8.")
 
1501
        raise BzrError("bzrlib.merge.merge_inner requires a this_tree "
 
1502
            "parameter as of bzrlib version 0.8.")
1730
1503
    merger = Merger(this_branch, other_tree, base_tree, this_tree=this_tree,
1731
1504
                    pb=pb, change_reporter=change_reporter)
1732
1505
    merger.backup_files = backup_files
1745
1518
    get_revision_id = getattr(base_tree, 'get_revision_id', None)
1746
1519
    if get_revision_id is None:
1747
1520
        get_revision_id = base_tree.last_revision
1748
 
    merger.cache_trees_with_revision_ids([other_tree, base_tree, this_tree])
1749
1521
    merger.set_base_revision(get_revision_id(), this_branch)
1750
1522
    return merger.do_merge()
1751
1523
 
1950
1722
        super(_PlanMerge, self).__init__(a_rev, b_rev, vf, key_prefix)
1951
1723
        self.a_key = self._key_prefix + (self.a_rev,)
1952
1724
        self.b_key = self._key_prefix + (self.b_rev,)
1953
 
        self.graph = _mod_graph.Graph(self.vf)
 
1725
        self.graph = Graph(self.vf)
1954
1726
        heads = self.graph.heads((self.a_key, self.b_key))
1955
1727
        if len(heads) == 1:
1956
1728
            # one side dominates, so we can just return its values, yay for
1961
1733
                other = b_rev
1962
1734
            else:
1963
1735
                other = a_rev
1964
 
            trace.mutter('found dominating revision for %s\n%s > %s', self.vf,
1965
 
                         self._head_key[-1], other)
 
1736
            mutter('found dominating revision for %s\n%s > %s', self.vf,
 
1737
                   self._head_key[-1], other)
1966
1738
            self._weave = None
1967
1739
        else:
1968
1740
            self._head_key = None
1982
1754
        while True:
1983
1755
            next_lcas = self.graph.find_lca(*cur_ancestors)
1984
1756
            # Map a plain NULL_REVISION to a simple no-ancestors
1985
 
            if next_lcas == set([_mod_revision.NULL_REVISION]):
 
1757
            if next_lcas == set([NULL_REVISION]):
1986
1758
                next_lcas = ()
1987
1759
            # Order the lca's based on when they were merged into the tip
1988
1760
            # While the actual merge portion of weave merge uses a set() of
2000
1772
            elif len(next_lcas) > 2:
2001
1773
                # More than 2 lca's, fall back to grabbing all nodes between
2002
1774
                # this and the unique lca.
2003
 
                trace.mutter('More than 2 LCAs, falling back to all nodes for:'
2004
 
                             ' %s, %s\n=> %s',
2005
 
                             self.a_key, self.b_key, cur_ancestors)
 
1775
                mutter('More than 2 LCAs, falling back to all nodes for:'
 
1776
                       ' %s, %s\n=> %s', self.a_key, self.b_key, cur_ancestors)
2006
1777
                cur_lcas = next_lcas
2007
1778
                while len(cur_lcas) > 1:
2008
1779
                    cur_lcas = self.graph.find_lca(*cur_lcas)
2011
1782
                    unique_lca = None
2012
1783
                else:
2013
1784
                    unique_lca = list(cur_lcas)[0]
2014
 
                    if unique_lca == _mod_revision.NULL_REVISION:
 
1785
                    if unique_lca == NULL_REVISION:
2015
1786
                        # find_lca will return a plain 'NULL_REVISION' rather
2016
1787
                        # than a key tuple when there is no common ancestor, we
2017
1788
                        # prefer to just use None, because it doesn't confuse
2040
1811
            # We remove NULL_REVISION because it isn't a proper tuple key, and
2041
1812
            # thus confuses things like _get_interesting_texts, and our logic
2042
1813
            # to add the texts into the memory weave.
2043
 
            if _mod_revision.NULL_REVISION in parent_map:
2044
 
                parent_map.pop(_mod_revision.NULL_REVISION)
 
1814
            if NULL_REVISION in parent_map:
 
1815
                parent_map.pop(NULL_REVISION)
2045
1816
        else:
2046
1817
            interesting = set()
2047
1818
            for tip in tip_keys:
2199
1970
        lcas = graph.find_lca(key_prefix + (a_rev,), key_prefix + (b_rev,))
2200
1971
        self.lcas = set()
2201
1972
        for lca in lcas:
2202
 
            if lca == _mod_revision.NULL_REVISION:
 
1973
            if lca == NULL_REVISION:
2203
1974
                self.lcas.add(lca)
2204
1975
            else:
2205
1976
                self.lcas.add(lca[-1])