~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_merge.py

(vila) Fix test failures blocking package builds. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2012 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
18
18
from StringIO import StringIO
19
19
 
20
20
from bzrlib import (
 
21
    branch as _mod_branch,
 
22
    cleanup,
21
23
    conflicts,
22
24
    errors,
 
25
    inventory,
23
26
    knit,
24
27
    memorytree,
25
28
    merge as _mod_merge,
26
29
    option,
27
 
    progress,
 
30
    revision as _mod_revision,
28
31
    tests,
29
32
    transform,
30
33
    versionedfile,
31
34
    )
32
 
from bzrlib.branch import Branch
33
35
from bzrlib.conflicts import ConflictList, TextConflict
34
 
from bzrlib.errors import UnrelatedBranches, NoCommits, BzrCommandError
 
36
from bzrlib.errors import UnrelatedBranches, NoCommits
35
37
from bzrlib.merge import transform_tree, merge_inner, _PlanMerge
36
 
from bzrlib.osutils import pathjoin, file_kind
37
 
from bzrlib.tests import TestCaseWithTransport, TestCaseWithMemoryTransport
 
38
from bzrlib.osutils import basename, pathjoin, file_kind
 
39
from bzrlib.tests import (
 
40
    features,
 
41
    TestCaseWithMemoryTransport,
 
42
    TestCaseWithTransport,
 
43
    test_merge_core,
 
44
    )
38
45
from bzrlib.workingtree import WorkingTree
39
46
 
40
47
 
76
83
        tip = wt1.commit('empty commit')
77
84
        wt2 = self.make_branch_and_tree('branch2')
78
85
        wt2.pull(wt1.branch)
79
 
        file('branch1/foo', 'wb').write('foo')
80
 
        file('branch1/bar', 'wb').write('bar')
 
86
        with file('branch1/foo', 'wb') as f:
 
87
            f.write('foo')
 
88
        with file('branch1/bar', 'wb') as f:
 
89
            f.write('bar')
81
90
        wt1.add('foo')
82
91
        wt1.add('bar')
83
92
        wt1.commit('add foobar')
84
 
        os.chdir('branch2')
85
 
        self.run_bzr('merge ../branch1/baz', retcode=3)
86
 
        self.run_bzr('merge ../branch1/foo')
87
 
        self.failUnlessExists('foo')
88
 
        self.failIfExists('bar')
89
 
        wt2 = WorkingTree.open('.') # opens branch2
 
93
        self.run_bzr('merge ../branch1/baz', retcode=3, working_dir='branch2')
 
94
        self.run_bzr('merge ../branch1/foo', working_dir='branch2')
 
95
        self.assertPathExists('branch2/foo')
 
96
        self.assertPathDoesNotExist('branch2/bar')
 
97
        wt2 = WorkingTree.open('branch2')
90
98
        self.assertEqual([tip], wt2.get_parent_ids())
91
99
 
92
100
    def test_pending_with_null(self):
115
123
        finally:
116
124
            wt1.unlock()
117
125
 
 
126
    def test_merge_into_null_tree(self):
 
127
        wt = self.make_branch_and_tree('tree')
 
128
        null_tree = wt.basis_tree()
 
129
        self.build_tree(['tree/file'])
 
130
        wt.add('file')
 
131
        wt.commit('tree with root')
 
132
        merger = _mod_merge.Merge3Merger(null_tree, null_tree, null_tree, wt,
 
133
                                         this_branch=wt.branch,
 
134
                                         do_merge=False)
 
135
        with merger.make_preview_transform() as tt:
 
136
            self.assertEqual([], tt.find_conflicts())
 
137
            preview = tt.get_preview_tree()
 
138
            self.assertEqual(wt.get_root_id(), preview.get_root_id())
 
139
 
 
140
    def test_merge_unrelated_retains_root(self):
 
141
        wt = self.make_branch_and_tree('tree')
 
142
        other_tree = self.make_branch_and_tree('other')
 
143
        self.addCleanup(other_tree.lock_read().unlock)
 
144
        merger = _mod_merge.Merge3Merger(wt, wt, wt.basis_tree(), other_tree,
 
145
                                         this_branch=wt.branch,
 
146
                                         do_merge=False)
 
147
        with transform.TransformPreview(wt) as merger.tt:
 
148
            merger._compute_transform()
 
149
            new_root_id = merger.tt.final_file_id(merger.tt.root)
 
150
            self.assertEqual(wt.get_root_id(), new_root_id)
 
151
 
118
152
    def test_create_rename(self):
119
153
        """Rename an inventory entry while creating the file"""
120
 
        self.thisFailsStrictLockCheck()
121
154
        tree =self.make_branch_and_tree('.')
122
 
        file('name1', 'wb').write('Hello')
 
155
        with file('name1', 'wb') as f: f.write('Hello')
123
156
        tree.add('name1')
124
157
        tree.commit(message="hello")
125
158
        tree.rename_one('name1', 'name2')
128
161
 
129
162
    def test_layered_rename(self):
130
163
        """Rename both child and parent at same time"""
131
 
        self.thisFailsStrictLockCheck()
132
164
        tree =self.make_branch_and_tree('.')
133
165
        os.mkdir('dirname1')
134
166
        tree.add('dirname1')
135
167
        filename = pathjoin('dirname1', 'name1')
136
 
        file(filename, 'wb').write('Hello')
 
168
        with file(filename, 'wb') as f: f.write('Hello')
137
169
        tree.add(filename)
138
170
        tree.commit(message="hello")
139
171
        filename2 = pathjoin('dirname1', 'name2')
153
185
        log = StringIO()
154
186
        merge_inner(tree_b.branch, tree_a, tree_b.basis_tree(),
155
187
                    this_tree=tree_b, ignore_zero=True)
156
 
        log = self._get_log(keep_log_file=True)
157
 
        self.failUnless('All changes applied successfully.\n' not in log)
 
188
        self.assertTrue('All changes applied successfully.\n' not in
 
189
            self.get_log())
158
190
        tree_b.revert()
159
191
        merge_inner(tree_b.branch, tree_a, tree_b.basis_tree(),
160
192
                    this_tree=tree_b, ignore_zero=False)
161
 
        log = self._get_log(keep_log_file=True)
162
 
        self.failUnless('All changes applied successfully.\n' in log)
 
193
        self.assertTrue('All changes applied successfully.\n' in self.get_log())
163
194
 
164
195
    def test_merge_inner_conflicts(self):
165
196
        tree_a = self.make_branch_and_tree('a')
196
227
 
197
228
    def test_nested_merge(self):
198
229
        tree = self.make_branch_and_tree('tree',
199
 
            format='dirstate-with-subtree')
 
230
            format='development-subtree')
200
231
        sub_tree = self.make_branch_and_tree('tree/sub-tree',
201
 
            format='dirstate-with-subtree')
 
232
            format='development-subtree')
202
233
        sub_tree.set_root_id('sub-tree-root')
203
234
        self.build_tree_contents([('tree/sub-tree/file', 'text1')])
204
235
        sub_tree.add('file')
215
246
        self.assertFileEqual('text2', 'tree/sub-tree/file')
216
247
 
217
248
    def test_merge_with_missing(self):
218
 
        self.thisFailsStrictLockCheck()
219
249
        tree_a = self.make_branch_and_tree('tree_a')
220
250
        self.build_tree_contents([('tree_a/file', 'content_1')])
221
251
        tree_a.add('file')
222
252
        tree_a.commit('commit base')
223
253
        # basis_tree() is only guaranteed to be valid as long as it is actually
224
 
        # the basis tree. This mutates the tree after grabbing basis, so go to
225
 
        # the repository.
 
254
        # the basis tree. This test commits to the tree after grabbing basis,
 
255
        # so we go to the repository.
226
256
        base_tree = tree_a.branch.repository.revision_tree(tree_a.last_revision())
227
257
        tree_b = tree_a.bzrdir.sprout('tree_b').open_workingtree()
228
258
        self.build_tree_contents([('tree_a/file', 'content_2')])
229
259
        tree_a.commit('commit other')
230
260
        other_tree = tree_a.basis_tree()
 
261
        # 'file' is now missing but isn't altered in any commit in b so no
 
262
        # change should be applied.
231
263
        os.unlink('tree_b/file')
232
264
        merge_inner(tree_b.branch, other_tree, base_tree, this_tree=tree_b)
233
265
 
294
326
        tree_a.commit('commit 2')
295
327
        tree_b = tree_a.bzrdir.sprout('b').open_workingtree()
296
328
        tree_b.rename_one('file_1', 'renamed')
297
 
        merger = _mod_merge.Merger.from_uncommitted(tree_a, tree_b,
298
 
                                                    progress.DummyProgress())
 
329
        merger = _mod_merge.Merger.from_uncommitted(tree_a, tree_b)
299
330
        merger.merge_type = _mod_merge.Merge3Merger
300
331
        merger.do_merge()
301
332
        self.assertEqual(tree_a.get_parent_ids(), [tree_b.last_revision()])
309
340
        tree_a.commit('commit 2')
310
341
        tree_b = tree_a.bzrdir.sprout('b').open_workingtree()
311
342
        tree_b.rename_one('file_1', 'renamed')
312
 
        merger = _mod_merge.Merger.from_uncommitted(tree_a, tree_b,
313
 
                                                    progress.DummyProgress())
 
343
        merger = _mod_merge.Merger.from_uncommitted(tree_a, tree_b)
314
344
        merger.merge_type = _mod_merge.WeaveMerger
315
345
        merger.do_merge()
316
346
        self.assertEqual(tree_a.get_parent_ids(), [tree_b.last_revision()])
317
347
 
318
 
    def test_Merger_defaults_to_DummyProgress(self):
319
 
        branch = self.make_branch('branch')
320
 
        merger = _mod_merge.Merger(branch, pb=None)
321
 
        self.assertIsInstance(merger._pb, progress.DummyProgress)
322
 
 
323
348
    def prepare_cherrypick(self):
324
349
        """Prepare a pair of trees for cherrypicking tests.
325
350
 
346
371
 
347
372
    def test_weave_cherrypick(self):
348
373
        this_tree, other_tree = self.prepare_cherrypick()
349
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
374
        merger = _mod_merge.Merger.from_revision_ids(None,
350
375
            this_tree, 'rev3b', 'rev2b', other_tree.branch)
351
376
        merger.merge_type = _mod_merge.WeaveMerger
352
377
        merger.do_merge()
354
379
 
355
380
    def test_weave_cannot_reverse_cherrypick(self):
356
381
        this_tree, other_tree = self.prepare_cherrypick()
357
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
382
        merger = _mod_merge.Merger.from_revision_ids(None,
358
383
            this_tree, 'rev2b', 'rev3b', other_tree.branch)
359
384
        merger.merge_type = _mod_merge.WeaveMerger
360
385
        self.assertRaises(errors.CannotReverseCherrypick, merger.do_merge)
361
386
 
362
387
    def test_merge3_can_reverse_cherrypick(self):
363
388
        this_tree, other_tree = self.prepare_cherrypick()
364
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
389
        merger = _mod_merge.Merger.from_revision_ids(None,
365
390
            this_tree, 'rev2b', 'rev3b', other_tree.branch)
366
391
        merger.merge_type = _mod_merge.Merge3Merger
367
392
        merger.do_merge()
379
404
        this_tree.lock_write()
380
405
        self.addCleanup(this_tree.unlock)
381
406
 
382
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
407
        merger = _mod_merge.Merger.from_revision_ids(None,
383
408
            this_tree, 'rev3b', 'rev2b', other_tree.branch)
384
409
        merger.merge_type = _mod_merge.Merge3Merger
385
410
        merger.do_merge()
390
415
                             '>>>>>>> MERGE-SOURCE\n',
391
416
                             'this/file')
392
417
 
 
418
    def test_merge_reverse_revision_range(self):
 
419
        tree = self.make_branch_and_tree(".")
 
420
        tree.lock_write()
 
421
        self.addCleanup(tree.unlock)
 
422
        self.build_tree(['a'])
 
423
        tree.add('a')
 
424
        first_rev = tree.commit("added a")
 
425
        merger = _mod_merge.Merger.from_revision_ids(None, tree,
 
426
                                          _mod_revision.NULL_REVISION,
 
427
                                          first_rev)
 
428
        merger.merge_type = _mod_merge.Merge3Merger
 
429
        merger.interesting_files = 'a'
 
430
        conflict_count = merger.do_merge()
 
431
        self.assertEqual(0, conflict_count)
 
432
 
 
433
        self.assertPathDoesNotExist("a")
 
434
        tree.revert()
 
435
        self.assertPathExists("a")
 
436
 
393
437
    def test_make_merger(self):
394
438
        this_tree = self.make_branch_and_tree('this')
395
439
        this_tree.commit('rev1', rev_id='rev1')
398
442
        other_tree.commit('rev2', rev_id='rev2b')
399
443
        this_tree.lock_write()
400
444
        self.addCleanup(this_tree.unlock)
401
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress,
 
445
        merger = _mod_merge.Merger.from_revision_ids(None,
402
446
            this_tree, 'rev2b', other_branch=other_tree.branch)
403
447
        merger.merge_type = _mod_merge.Merge3Merger
404
448
        tree_merger = merger.make_merger()
405
449
        self.assertIs(_mod_merge.Merge3Merger, tree_merger.__class__)
406
 
        self.assertEqual('rev2b', tree_merger.other_tree.get_revision_id())
407
 
        self.assertEqual('rev1', tree_merger.base_tree.get_revision_id())
 
450
        self.assertEqual('rev2b',
 
451
            tree_merger.other_tree.get_revision_id())
 
452
        self.assertEqual('rev1',
 
453
            tree_merger.base_tree.get_revision_id())
 
454
        self.assertEqual(other_tree.branch, tree_merger.other_branch)
408
455
 
409
456
    def test_make_preview_transform(self):
410
457
        this_tree = self.make_branch_and_tree('this')
418
465
        other_tree.commit('rev2', rev_id='rev2b')
419
466
        this_tree.lock_write()
420
467
        self.addCleanup(this_tree.unlock)
421
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
468
        merger = _mod_merge.Merger.from_revision_ids(None,
422
469
            this_tree, 'rev2b', other_branch=other_tree.branch)
423
470
        merger.merge_type = _mod_merge.Merge3Merger
424
471
        tree_merger = merger.make_merger()
448
495
        other_tree.commit('rev2', rev_id='rev2b')
449
496
        this_tree.lock_write()
450
497
        self.addCleanup(this_tree.unlock)
451
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
498
        merger = _mod_merge.Merger.from_revision_ids(None,
452
499
            this_tree, 'rev2b', other_branch=other_tree.branch)
453
500
        merger.merge_type = _mod_merge.Merge3Merger
454
501
        tree_merger = merger.make_merger()
459
506
        finally:
460
507
            tree_file.close()
461
508
 
 
509
    def test_merge_require_tree_root(self):
 
510
        tree = self.make_branch_and_tree(".")
 
511
        tree.lock_write()
 
512
        self.addCleanup(tree.unlock)
 
513
        self.build_tree(['a'])
 
514
        tree.add('a')
 
515
        first_rev = tree.commit("added a")
 
516
        old_root_id = tree.get_root_id()
 
517
        merger = _mod_merge.Merger.from_revision_ids(None, tree,
 
518
                                          _mod_revision.NULL_REVISION,
 
519
                                          first_rev)
 
520
        merger.merge_type = _mod_merge.Merge3Merger
 
521
        conflict_count = merger.do_merge()
 
522
        self.assertEqual(0, conflict_count)
 
523
        self.assertEquals(set([old_root_id]), tree.all_file_ids())
 
524
        tree.set_parent_ids([])
 
525
 
462
526
    def test_merge_add_into_deleted_root(self):
463
527
        # Yes, people actually do this.  And report bugs if it breaks.
464
528
        source = self.make_branch_and_tree('source', format='rich-root-pack')
495
559
class TestPlanMerge(TestCaseWithMemoryTransport):
496
560
 
497
561
    def setUp(self):
498
 
        TestCaseWithMemoryTransport.setUp(self)
 
562
        super(TestPlanMerge, self).setUp()
499
563
        mapper = versionedfile.PrefixMapper()
500
564
        factory = knit.make_file_factory(True, mapper)
501
565
        self.vf = factory(self.get_transport())
525
589
        self.add_uncommitted_version(('root', 'C:'), [('root', 'A')], 'fabg')
526
590
        return _PlanMerge('B:', 'C:', self.plan_merge_vf, ('root',))
527
591
 
 
592
    def test_base_from_plan(self):
 
593
        self.setup_plan_merge()
 
594
        plan = self.plan_merge_vf.plan_merge('B', 'C')
 
595
        pwm = versionedfile.PlanWeaveMerge(plan)
 
596
        self.assertEqual(['a\n', 'b\n', 'c\n'], pwm.base_from_plan())
 
597
 
528
598
    def test_unique_lines(self):
529
599
        plan = self.setup_plan_merge()
530
600
        self.assertEqual(plan._unique_lines(
828
898
                          ('unchanged', 'f\n'),
829
899
                          ('unchanged', 'g\n')],
830
900
                         list(plan))
 
901
        plan = self.plan_merge_vf.plan_lca_merge('F', 'G')
 
902
        # This is one of the main differences between plan_merge and
 
903
        # plan_lca_merge. plan_lca_merge generates a conflict for 'x => z',
 
904
        # because 'x' was not present in one of the bases. However, in this
 
905
        # case it is spurious because 'x' does not exist in the global base A.
 
906
        self.assertEqual([
 
907
                          ('unchanged', 'h\n'),
 
908
                          ('unchanged', 'a\n'),
 
909
                          ('conflicted-a', 'x\n'),
 
910
                          ('new-b', 'z\n'),
 
911
                          ('unchanged', 'c\n'),
 
912
                          ('unchanged', 'd\n'),
 
913
                          ('unchanged', 'y\n'),
 
914
                          ('unchanged', 'f\n'),
 
915
                          ('unchanged', 'g\n')],
 
916
                         list(plan))
 
917
 
 
918
    def test_criss_cross_flip_flop(self):
 
919
        # This is specificly trying to trigger problems when using limited
 
920
        # ancestry and weaves. The ancestry graph looks like:
 
921
        #       XX      unused ancestor, should not show up in the weave
 
922
        #       |
 
923
        #       A       Unique LCA
 
924
        #      / \  
 
925
        #     B   C     B & C both introduce a new line
 
926
        #     |\ /|  
 
927
        #     | X |  
 
928
        #     |/ \| 
 
929
        #     D   E     B & C are both merged, so both are common ancestors
 
930
        #               In the process of merging, both sides order the new
 
931
        #               lines differently
 
932
        #
 
933
        self.add_rev('root', 'XX', [], 'qrs')
 
934
        self.add_rev('root', 'A', ['XX'], 'abcdef')
 
935
        self.add_rev('root', 'B', ['A'], 'abcdgef')
 
936
        self.add_rev('root', 'C', ['A'], 'abcdhef')
 
937
        self.add_rev('root', 'D', ['B', 'C'], 'abcdghef')
 
938
        self.add_rev('root', 'E', ['C', 'B'], 'abcdhgef')
 
939
        plan = list(self.plan_merge_vf.plan_merge('D', 'E'))
 
940
        self.assertEqual([
 
941
                          ('unchanged', 'a\n'),
 
942
                          ('unchanged', 'b\n'),
 
943
                          ('unchanged', 'c\n'),
 
944
                          ('unchanged', 'd\n'),
 
945
                          ('new-b', 'h\n'),
 
946
                          ('unchanged', 'g\n'),
 
947
                          ('killed-b', 'h\n'),
 
948
                          ('unchanged', 'e\n'),
 
949
                          ('unchanged', 'f\n'),
 
950
                         ], plan)
 
951
        pwm = versionedfile.PlanWeaveMerge(plan)
 
952
        self.assertEqualDiff('\n'.join('abcdghef') + '\n',
 
953
                             ''.join(pwm.base_from_plan()))
 
954
        # Reversing the order reverses the merge plan, and final order of 'hg'
 
955
        # => 'gh'
 
956
        plan = list(self.plan_merge_vf.plan_merge('E', 'D'))
 
957
        self.assertEqual([
 
958
                          ('unchanged', 'a\n'),
 
959
                          ('unchanged', 'b\n'),
 
960
                          ('unchanged', 'c\n'),
 
961
                          ('unchanged', 'd\n'),
 
962
                          ('new-b', 'g\n'),
 
963
                          ('unchanged', 'h\n'),
 
964
                          ('killed-b', 'g\n'),
 
965
                          ('unchanged', 'e\n'),
 
966
                          ('unchanged', 'f\n'),
 
967
                         ], plan)
 
968
        pwm = versionedfile.PlanWeaveMerge(plan)
 
969
        self.assertEqualDiff('\n'.join('abcdhgef') + '\n',
 
970
                             ''.join(pwm.base_from_plan()))
 
971
        # This is where lca differs, in that it (fairly correctly) determines
 
972
        # that there is a conflict because both sides resolved the merge
 
973
        # differently
 
974
        plan = list(self.plan_merge_vf.plan_lca_merge('D', 'E'))
 
975
        self.assertEqual([
 
976
                          ('unchanged', 'a\n'),
 
977
                          ('unchanged', 'b\n'),
 
978
                          ('unchanged', 'c\n'),
 
979
                          ('unchanged', 'd\n'),
 
980
                          ('conflicted-b', 'h\n'),
 
981
                          ('unchanged', 'g\n'),
 
982
                          ('conflicted-a', 'h\n'),
 
983
                          ('unchanged', 'e\n'),
 
984
                          ('unchanged', 'f\n'),
 
985
                         ], plan)
 
986
        pwm = versionedfile.PlanWeaveMerge(plan)
 
987
        self.assertEqualDiff('\n'.join('abcdgef') + '\n',
 
988
                             ''.join(pwm.base_from_plan()))
 
989
        # Reversing it changes what line is doubled, but still gives a
 
990
        # double-conflict
 
991
        plan = list(self.plan_merge_vf.plan_lca_merge('E', 'D'))
 
992
        self.assertEqual([
 
993
                          ('unchanged', 'a\n'),
 
994
                          ('unchanged', 'b\n'),
 
995
                          ('unchanged', 'c\n'),
 
996
                          ('unchanged', 'd\n'),
 
997
                          ('conflicted-b', 'g\n'),
 
998
                          ('unchanged', 'h\n'),
 
999
                          ('conflicted-a', 'g\n'),
 
1000
                          ('unchanged', 'e\n'),
 
1001
                          ('unchanged', 'f\n'),
 
1002
                         ], plan)
 
1003
        pwm = versionedfile.PlanWeaveMerge(plan)
 
1004
        self.assertEqualDiff('\n'.join('abcdhef') + '\n',
 
1005
                             ''.join(pwm.base_from_plan()))
831
1006
 
832
1007
    def assertRemoveExternalReferences(self, filtered_parent_map,
833
1008
                                       child_map, tails, parent_map):
1033
1208
                         ], list(plan))
1034
1209
 
1035
1210
 
1036
 
class TestMergeImplementation(object):
1037
 
 
1038
 
    def do_merge(self, target_tree, source_tree, **kwargs):
1039
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
1040
 
            target_tree, source_tree.last_revision(),
1041
 
            other_branch=source_tree.branch)
1042
 
        merger.merge_type=self.merge_type
1043
 
        for name, value in kwargs.items():
1044
 
            setattr(merger, name, value)
1045
 
        merger.do_merge()
1046
 
 
1047
 
    def test_merge_specific_file(self):
1048
 
        this_tree = self.make_branch_and_tree('this')
1049
 
        this_tree.lock_write()
1050
 
        self.addCleanup(this_tree.unlock)
1051
 
        self.build_tree_contents([
1052
 
            ('this/file1', 'a\nb\n'),
1053
 
            ('this/file2', 'a\nb\n')
1054
 
        ])
1055
 
        this_tree.add(['file1', 'file2'])
1056
 
        this_tree.commit('Added files')
1057
 
        other_tree = this_tree.bzrdir.sprout('other').open_workingtree()
1058
 
        self.build_tree_contents([
1059
 
            ('other/file1', 'a\nb\nc\n'),
1060
 
            ('other/file2', 'a\nb\nc\n')
1061
 
        ])
1062
 
        other_tree.commit('modified both')
1063
 
        self.build_tree_contents([
1064
 
            ('this/file1', 'd\na\nb\n'),
1065
 
            ('this/file2', 'd\na\nb\n')
1066
 
        ])
1067
 
        this_tree.commit('modified both')
1068
 
        self.do_merge(this_tree, other_tree, interesting_files=['file1'])
1069
 
        self.assertFileEqual('d\na\nb\nc\n', 'this/file1')
1070
 
        self.assertFileEqual('d\na\nb\n', 'this/file2')
1071
 
 
1072
 
    def test_merge_move_and_change(self):
1073
 
        this_tree = self.make_branch_and_tree('this')
1074
 
        this_tree.lock_write()
1075
 
        self.addCleanup(this_tree.unlock)
1076
 
        self.build_tree_contents([
1077
 
            ('this/file1', 'line 1\nline 2\nline 3\nline 4\n'),
1078
 
        ])
1079
 
        this_tree.add('file1',)
1080
 
        this_tree.commit('Added file')
1081
 
        other_tree = this_tree.bzrdir.sprout('other').open_workingtree()
1082
 
        self.build_tree_contents([
1083
 
            ('other/file1', 'line 1\nline 2 to 2.1\nline 3\nline 4\n'),
1084
 
        ])
1085
 
        other_tree.commit('Changed 2 to 2.1')
1086
 
        self.build_tree_contents([
1087
 
            ('this/file1', 'line 1\nline 3\nline 2\nline 4\n'),
1088
 
        ])
1089
 
        this_tree.commit('Swapped 2 & 3')
1090
 
        self.do_merge(this_tree, other_tree)
1091
 
        self.assertFileEqual('line 1\n'
1092
 
            '<<<<<<< TREE\n'
1093
 
            'line 3\n'
1094
 
            'line 2\n'
1095
 
            '=======\n'
1096
 
            'line 2 to 2.1\n'
1097
 
            'line 3\n'
1098
 
            '>>>>>>> MERGE-SOURCE\n'
1099
 
            'line 4\n', 'this/file1')
1100
 
 
1101
 
    def test_modify_conflicts_with_delete(self):
1102
 
        # If one side deletes a line, and the other modifies that line, then
1103
 
        # the modification should be considered a conflict
1104
 
        builder = self.make_branch_builder('test')
1105
 
        builder.start_series()
1106
 
        builder.build_snapshot('BASE-id', None,
1107
 
            [('add', ('', None, 'directory', None)),
1108
 
             ('add', ('foo', 'foo-id', 'file', 'a\nb\nc\nd\ne\n')),
1109
 
            ])
1110
 
        # Delete 'b\n'
1111
 
        builder.build_snapshot('OTHER-id', ['BASE-id'],
1112
 
            [('modify', ('foo-id', 'a\nc\nd\ne\n'))])
1113
 
        # Modify 'b\n', add 'X\n'
1114
 
        builder.build_snapshot('THIS-id', ['BASE-id'],
1115
 
            [('modify', ('foo-id', 'a\nb2\nc\nd\nX\ne\n'))])
1116
 
        builder.finish_series()
1117
 
        branch = builder.get_branch()
1118
 
        this_tree = branch.bzrdir.create_workingtree()
1119
 
        this_tree.lock_write()
1120
 
        self.addCleanup(this_tree.unlock)
1121
 
        other_tree = this_tree.bzrdir.sprout('other', 'OTHER-id').open_workingtree()
1122
 
        self.do_merge(this_tree, other_tree)
1123
 
        if self.merge_type is _mod_merge.LCAMerger:
1124
 
            self.expectFailure("lca merge doesn't track deleted lines",
1125
 
                self.assertFileEqual,
1126
 
                    'a\n'
1127
 
                    '<<<<<<< TREE\n'
1128
 
                    'b2\n'
1129
 
                    '=======\n'
1130
 
                    '>>>>>>> MERGE-SOURCE\n'
1131
 
                    'c\n'
1132
 
                    'd\n'
1133
 
                    'X\n'
1134
 
                    'e\n', 'test/foo')
1135
 
        else:
1136
 
            self.assertFileEqual(
1137
 
                'a\n'
1138
 
                '<<<<<<< TREE\n'
1139
 
                'b2\n'
1140
 
                '=======\n'
1141
 
                '>>>>>>> MERGE-SOURCE\n'
1142
 
                'c\n'
1143
 
                'd\n'
1144
 
                'X\n'
1145
 
                'e\n', 'test/foo')
1146
 
 
1147
 
 
1148
 
class TestMerge3Merge(TestCaseWithTransport, TestMergeImplementation):
1149
 
 
1150
 
    merge_type = _mod_merge.Merge3Merger
1151
 
 
1152
 
 
1153
 
class TestWeaveMerge(TestCaseWithTransport, TestMergeImplementation):
1154
 
 
1155
 
    merge_type = _mod_merge.WeaveMerger
1156
 
 
1157
 
 
1158
 
class TestLCAMerge(TestCaseWithTransport, TestMergeImplementation):
1159
 
 
1160
 
    merge_type = _mod_merge.LCAMerger
1161
 
 
1162
 
    def test_merge_move_and_change(self):
1163
 
        self.expectFailure("lca merge doesn't conflict for move and change",
1164
 
            super(TestLCAMerge, self).test_merge_move_and_change)
1165
 
 
1166
 
 
1167
1211
class LoggingMerger(object):
1168
1212
    # These seem to be the required attributes
1169
1213
    requires_base = False
1224
1268
        mem_tree = memorytree.MemoryTree.create_on_branch(builder.get_branch())
1225
1269
        mem_tree.lock_write()
1226
1270
        self.addCleanup(mem_tree.unlock)
1227
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
1271
        merger = _mod_merge.Merger.from_revision_ids(None,
1228
1272
            mem_tree, other_revision_id)
1229
1273
        merger.set_interesting_files(interesting_files)
1230
1274
        # It seems there is no matching function for set_interesting_ids
1235
1279
 
1236
1280
class TestMergerInMemory(TestMergerBase):
1237
1281
 
 
1282
    def test_cache_trees_with_revision_ids_None(self):
 
1283
        merger = self.make_Merger(self.setup_simple_graph(), 'C-id')
 
1284
        original_cache = dict(merger._cached_trees)
 
1285
        merger.cache_trees_with_revision_ids([None])
 
1286
        self.assertEqual(original_cache, merger._cached_trees)
 
1287
 
 
1288
    def test_cache_trees_with_revision_ids_no_revision_id(self):
 
1289
        merger = self.make_Merger(self.setup_simple_graph(), 'C-id')
 
1290
        original_cache = dict(merger._cached_trees)
 
1291
        tree = self.make_branch_and_memory_tree('tree')
 
1292
        merger.cache_trees_with_revision_ids([tree])
 
1293
        self.assertEqual(original_cache, merger._cached_trees)
 
1294
 
 
1295
    def test_cache_trees_with_revision_ids_having_revision_id(self):
 
1296
        merger = self.make_Merger(self.setup_simple_graph(), 'C-id')
 
1297
        original_cache = dict(merger._cached_trees)
 
1298
        tree = merger.this_branch.repository.revision_tree('B-id')
 
1299
        original_cache['B-id'] = tree
 
1300
        merger.cache_trees_with_revision_ids([tree])
 
1301
        self.assertEqual(original_cache, merger._cached_trees)
 
1302
 
1238
1303
    def test_find_base(self):
1239
1304
        merger = self.make_Merger(self.setup_simple_graph(), 'C-id')
1240
1305
        self.assertEqual('A-id', merger.base_rev_id)
1272
1337
        self.assertEqual(['B-id', 'C-id', 'F-id'],
1273
1338
                         [t.get_revision_id() for t in merger._lca_trees])
1274
1339
 
 
1340
    def test_find_base_new_root_criss_cross(self):
 
1341
        # A   B
 
1342
        # |\ /|
 
1343
        # | X |
 
1344
        # |/ \|
 
1345
        # C   D
 
1346
        
 
1347
        builder = self.get_builder()
 
1348
        builder.build_snapshot('A-id', None,
 
1349
            [('add', ('', None, 'directory', None))])
 
1350
        builder.build_snapshot('B-id', [],
 
1351
            [('add', ('', None, 'directory', None))])
 
1352
        builder.build_snapshot('D-id', ['A-id', 'B-id'], [])
 
1353
        builder.build_snapshot('C-id', ['A-id', 'B-id'], [])
 
1354
        merger = self.make_Merger(builder, 'D-id')
 
1355
        self.assertEqual('A-id', merger.base_rev_id)
 
1356
        self.assertTrue(merger._is_criss_cross)
 
1357
        self.assertEqual(['A-id', 'B-id'], [t.get_revision_id()
 
1358
                                            for t in merger._lca_trees])
 
1359
 
1275
1360
    def test_no_criss_cross_passed_to_merge_type(self):
1276
1361
        class LCATreesMerger(LoggingMerger):
1277
1362
            supports_lca_trees = True
1809
1894
        builder.build_snapshot('C-id', ['A-id'], [])
1810
1895
        builder.build_snapshot('E-id', ['C-id', 'B-id'],
1811
1896
            [('unversion', 'a-id'),
 
1897
             ('flush', None),
1812
1898
             ('add', (u'a', 'a-id', 'directory', None))])
1813
1899
        builder.build_snapshot('D-id', ['B-id', 'C-id'], [])
1814
1900
        merge_obj = self.make_merge_obj(builder, 'E-id')
1832
1918
        builder.build_snapshot('E-id', ['C-id', 'B-id'], [])
1833
1919
        builder.build_snapshot('D-id', ['B-id', 'C-id'],
1834
1920
            [('unversion', 'a-id'),
 
1921
             ('flush', None),
1835
1922
             ('add', (u'a', 'a-id', 'directory', None))])
1836
1923
        merge_obj = self.make_merge_obj(builder, 'E-id')
1837
1924
        entries = list(merge_obj._entries_lca())
1983
2070
 
1984
2071
    def do_merge(self, builder, other_revision_id):
1985
2072
        wt = self.get_wt_from_builder(builder)
1986
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2073
        merger = _mod_merge.Merger.from_revision_ids(None,
1987
2074
            wt, other_revision_id)
1988
2075
        merger.merge_type = _mod_merge.Merge3Merger
1989
2076
        return wt, merger.do_merge()
2100
2187
        self.assertTrue(wt.is_executable('foo-id'))
2101
2188
 
2102
2189
    def test_create_symlink(self):
2103
 
        self.requireFeature(tests.SymlinkFeature)
 
2190
        self.requireFeature(features.SymlinkFeature)
2104
2191
        #   A
2105
2192
        #  / \
2106
2193
        # B   C
2165
2252
                             wt.get_file_text('foo-id'))
2166
2253
 
2167
2254
    def test_modified_symlink(self):
2168
 
        self.requireFeature(tests.SymlinkFeature)
 
2255
        self.requireFeature(features.SymlinkFeature)
2169
2256
        #   A       Create symlink foo => bar
2170
2257
        #  / \
2171
2258
        # B   C     B relinks foo => baz
2210
2297
        self.assertEqual('bing', wt.get_symlink_target('foo-id'))
2211
2298
 
2212
2299
    def test_renamed_symlink(self):
2213
 
        self.requireFeature(tests.SymlinkFeature)
 
2300
        self.requireFeature(features.SymlinkFeature)
2214
2301
        #   A       Create symlink foo => bar
2215
2302
        #  / \
2216
2303
        # B   C     B renames foo => barry
2249
2336
        wt.commit('D merges B & C', rev_id='D-id')
2250
2337
        self.assertEqual('barry', wt.id2path('foo-id'))
2251
2338
        # Check the output of the Merger object directly
2252
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2339
        merger = _mod_merge.Merger.from_revision_ids(None,
2253
2340
            wt, 'F-id')
2254
2341
        merger.merge_type = _mod_merge.Merge3Merger
2255
2342
        merge_obj = merger.make_merger()
2266
2353
        self.assertEqual('blah', wt.id2path('foo-id'))
2267
2354
 
2268
2355
    def test_symlink_no_content_change(self):
2269
 
        self.requireFeature(tests.SymlinkFeature)
 
2356
        self.requireFeature(features.SymlinkFeature)
2270
2357
        #   A       Create symlink foo => bar
2271
2358
        #  / \
2272
2359
        # B   C     B relinks foo => baz
2305
2392
        wt.commit('F foo => bing', rev_id='F-id')
2306
2393
 
2307
2394
        # Check the output of the Merger object directly
2308
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2395
        merger = _mod_merge.Merger.from_revision_ids(None,
2309
2396
            wt, 'E-id')
2310
2397
        merger.merge_type = _mod_merge.Merge3Merger
2311
2398
        merge_obj = merger.make_merger()
2317
2404
        self.assertEqual('bing', wt.get_symlink_target('foo-id'))
2318
2405
 
2319
2406
    def test_symlink_this_changed_kind(self):
2320
 
        self.requireFeature(tests.SymlinkFeature)
 
2407
        self.requireFeature(features.SymlinkFeature)
2321
2408
        #   A       Nothing
2322
2409
        #  / \
2323
2410
        # B   C     B creates symlink foo => bar
2356
2443
        list(wt.iter_changes(wt.basis_tree()))
2357
2444
        wt.commit('D merges B & C, makes it a file', rev_id='D-id')
2358
2445
 
2359
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2446
        merger = _mod_merge.Merger.from_revision_ids(None,
2360
2447
            wt, 'E-id')
2361
2448
        merger.merge_type = _mod_merge.Merge3Merger
2362
2449
        merge_obj = merger.make_merger()
2370
2457
 
2371
2458
    def test_symlink_all_wt(self):
2372
2459
        """Check behavior if all trees are Working Trees."""
2373
 
        self.requireFeature(tests.SymlinkFeature)
 
2460
        self.requireFeature(features.SymlinkFeature)
2374
2461
        # The big issue is that entry.symlink_target is None for WorkingTrees.
2375
2462
        # So we need to make sure we handle that case correctly.
2376
2463
        #   A   foo => bar
2547
2634
        # Tested with a real WT, because BranchBuilder/MemoryTree don't handle
2548
2635
        # 'tree-reference'
2549
2636
        wt = self.make_branch_and_tree('tree',
2550
 
            format='dirstate-with-subtree')
 
2637
            format='development-subtree')
2551
2638
        wt.lock_write()
2552
2639
        self.addCleanup(wt.unlock)
2553
2640
        sub_tree = self.make_branch_and_tree('tree/sub-tree',
2554
 
            format='dirstate-with-subtree')
 
2641
            format='development-subtree')
2555
2642
        wt.set_root_id('a-root-id')
2556
2643
        sub_tree.set_root_id('sub-tree-root')
2557
2644
        self.build_tree_contents([('tree/sub-tree/file', 'text1')])
2571
2658
        wt.branch.set_last_revision_info(2, 'B-id')
2572
2659
        wt.commit('D', rev_id='D-id', recursive=None)
2573
2660
 
2574
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2661
        merger = _mod_merge.Merger.from_revision_ids(None,
2575
2662
            wt, 'E-id')
2576
2663
        merger.merge_type = _mod_merge.Merge3Merger
2577
2664
        merge_obj = merger.make_merger()
2582
2669
        # Tested with a real WT, because BranchBuilder/MemoryTree don't handle
2583
2670
        # 'tree-reference'
2584
2671
        wt = self.make_branch_and_tree('tree',
2585
 
            format='dirstate-with-subtree')
 
2672
            format='development-subtree')
2586
2673
        wt.lock_write()
2587
2674
        self.addCleanup(wt.unlock)
2588
2675
        sub_tree = self.make_branch_and_tree('tree/sub',
2589
 
            format='dirstate-with-subtree')
 
2676
            format='development-subtree')
2590
2677
        wt.set_root_id('a-root-id')
2591
2678
        sub_tree.set_root_id('sub-tree-root')
2592
2679
        self.build_tree_contents([('tree/sub/file', 'text1')])
2608
2695
        wt.branch.set_last_revision_info(2, 'B-id')
2609
2696
        wt.commit('D', rev_id='D-id', recursive=None)
2610
2697
 
2611
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2698
        merger = _mod_merge.Merger.from_revision_ids(None,
2612
2699
            wt, 'E-id')
2613
2700
        merger.merge_type = _mod_merge.Merge3Merger
2614
2701
        merge_obj = merger.make_merger()
2621
2708
        # Tested with a real WT, because BranchBuilder/MemoryTree don't handle
2622
2709
        # 'tree-reference'
2623
2710
        wt = self.make_branch_and_tree('tree',
2624
 
            format='dirstate-with-subtree')
 
2711
            format='development-subtree')
2625
2712
        wt.lock_write()
2626
2713
        self.addCleanup(wt.unlock)
2627
2714
        sub_tree = self.make_branch_and_tree('tree/sub',
2628
 
            format='dirstate-with-subtree')
 
2715
            format='development-subtree')
2629
2716
        wt.set_root_id('a-root-id')
2630
2717
        sub_tree.set_root_id('sub-tree-root')
2631
2718
        self.build_tree_contents([('tree/sub/file', 'text1')])
2648
2735
        wt.branch.set_last_revision_info(2, 'B-id')
2649
2736
        wt.commit('D', rev_id='D-id', recursive=None)
2650
2737
 
2651
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2738
        merger = _mod_merge.Merger.from_revision_ids(None,
2652
2739
            wt, 'E-id')
2653
2740
        merger.merge_type = _mod_merge.Merge3Merger
2654
2741
        merge_obj = merger.make_merger()
2664
2751
        # Tested with a real WT, because BranchBuilder/MemoryTree don't handle
2665
2752
        # 'tree-reference'
2666
2753
        wt = self.make_branch_and_tree('tree',
2667
 
            format='dirstate-with-subtree')
 
2754
            format='development-subtree')
2668
2755
        wt.lock_write()
2669
2756
        self.addCleanup(wt.unlock)
2670
2757
        sub_tree = self.make_branch_and_tree('tree/sub',
2671
 
            format='dirstate-with-subtree')
 
2758
            format='development-subtree')
2672
2759
        wt.set_root_id('a-root-id')
2673
2760
        sub_tree.set_root_id('sub-tree-root')
2674
2761
        self.build_tree_contents([('tree/sub/file', 'text1')])
2693
2780
        wt.branch.set_last_revision_info(2, 'B-id')
2694
2781
        wt.commit('D', rev_id='D-id', recursive=None)
2695
2782
 
2696
 
        merger = _mod_merge.Merger.from_revision_ids(progress.DummyProgress(),
 
2783
        merger = _mod_merge.Merger.from_revision_ids(None,
2697
2784
            wt, 'E-id')
2698
2785
        merger.merge_type = _mod_merge.Merge3Merger
2699
2786
        merge_obj = merger.make_merger()
2835
2922
            'bval', ['lca1val', 'lca2val', 'lca2val'], 'oval', 'tval')
2836
2923
        self.assertLCAMultiWay('conflict',
2837
2924
            'bval', ['lca1val', 'lca2val', 'lca3val'], 'oval', 'tval')
 
2925
 
 
2926
 
 
2927
class TestConfigurableFileMerger(tests.TestCaseWithTransport):
 
2928
 
 
2929
    def setUp(self):
 
2930
        super(TestConfigurableFileMerger, self).setUp()
 
2931
        self.calls = []
 
2932
 
 
2933
    def get_merger_factory(self):
 
2934
        # Allows  the inner methods to access the test attributes
 
2935
        calls = self.calls
 
2936
 
 
2937
        class FooMerger(_mod_merge.ConfigurableFileMerger):
 
2938
            name_prefix = "foo"
 
2939
            default_files = ['bar']
 
2940
 
 
2941
            def merge_text(self, params):
 
2942
                calls.append('merge_text')
 
2943
                return ('not_applicable', None)
 
2944
 
 
2945
        def factory(merger):
 
2946
            result = FooMerger(merger)
 
2947
            # Make sure we start with a clean slate
 
2948
            self.assertEqual(None, result.affected_files)
 
2949
            # Track the original merger
 
2950
            self.merger = result
 
2951
            return result
 
2952
 
 
2953
        return factory
 
2954
 
 
2955
    def _install_hook(self, factory):
 
2956
        _mod_merge.Merger.hooks.install_named_hook('merge_file_content',
 
2957
                                                   factory, 'test factory')
 
2958
 
 
2959
    def make_builder(self):
 
2960
        builder = test_merge_core.MergeBuilder(self.test_base_dir)
 
2961
        self.addCleanup(builder.cleanup)
 
2962
        return builder
 
2963
 
 
2964
    def make_text_conflict(self, file_name='bar'):
 
2965
        factory = self.get_merger_factory()
 
2966
        self._install_hook(factory)
 
2967
        builder = self.make_builder()
 
2968
        builder.add_file('bar-id', builder.tree_root, file_name, 'text1', True)
 
2969
        builder.change_contents('bar-id', other='text4', this='text3')
 
2970
        return builder
 
2971
 
 
2972
    def make_kind_change(self):
 
2973
        factory = self.get_merger_factory()
 
2974
        self._install_hook(factory)
 
2975
        builder = self.make_builder()
 
2976
        builder.add_file('bar-id', builder.tree_root, 'bar', 'text1', True,
 
2977
                         this=False)
 
2978
        builder.add_dir('bar-dir', builder.tree_root, 'bar-id',
 
2979
                        base=False, other=False)
 
2980
        return builder
 
2981
 
 
2982
    def test_uses_this_branch(self):
 
2983
        builder = self.make_text_conflict()
 
2984
        tt = builder.make_preview_transform()
 
2985
        self.addCleanup(tt.finalize)
 
2986
 
 
2987
    def test_affected_files_cached(self):
 
2988
        """Ensures that the config variable is cached"""
 
2989
        builder = self.make_text_conflict()
 
2990
        conflicts = builder.merge()
 
2991
        # The hook should set the variable
 
2992
        self.assertEqual(['bar'], self.merger.affected_files)
 
2993
        self.assertEqual(1, len(conflicts))
 
2994
 
 
2995
    def test_hook_called_for_text_conflicts(self):
 
2996
        builder = self.make_text_conflict()
 
2997
        conflicts = builder.merge()
 
2998
        # The hook should call the merge_text() method
 
2999
        self.assertEqual(['merge_text'], self.calls)
 
3000
 
 
3001
    def test_hook_not_called_for_kind_change(self):
 
3002
        builder = self.make_kind_change()
 
3003
        conflicts = builder.merge()
 
3004
        # The hook should not call the merge_text() method
 
3005
        self.assertEqual([], self.calls)
 
3006
 
 
3007
    def test_hook_not_called_for_other_files(self):
 
3008
        builder = self.make_text_conflict('foobar')
 
3009
        conflicts = builder.merge()
 
3010
        # The hook should not call the merge_text() method
 
3011
        self.assertEqual([], self.calls)
 
3012
 
 
3013
 
 
3014
class TestMergeIntoBase(tests.TestCaseWithTransport):
 
3015
 
 
3016
    def setup_simple_branch(self, relpath, shape=None, root_id=None):
 
3017
        """One commit, containing tree specified by optional shape.
 
3018
        
 
3019
        Default is empty tree (just root entry).
 
3020
        """
 
3021
        if root_id is None:
 
3022
            root_id = '%s-root-id' % (relpath,)
 
3023
        wt = self.make_branch_and_tree(relpath)
 
3024
        wt.set_root_id(root_id)
 
3025
        if shape is not None:
 
3026
            adjusted_shape = [relpath + '/' + elem for elem in shape]
 
3027
            self.build_tree(adjusted_shape)
 
3028
            ids = ['%s-%s-id' % (relpath, basename(elem.rstrip('/')))
 
3029
                   for elem in shape]
 
3030
            wt.add(shape, ids=ids)
 
3031
        rev_id = 'r1-%s' % (relpath,)
 
3032
        wt.commit("Initial commit of %s" % (relpath,), rev_id=rev_id)
 
3033
        self.assertEqual(root_id, wt.path2id(''))
 
3034
        return wt
 
3035
 
 
3036
    def setup_two_branches(self, custom_root_ids=True):
 
3037
        """Setup 2 branches, one will be a library, the other a project."""
 
3038
        if custom_root_ids:
 
3039
            root_id = None
 
3040
        else:
 
3041
            root_id = inventory.ROOT_ID
 
3042
        project_wt = self.setup_simple_branch(
 
3043
            'project', ['README', 'dir/', 'dir/file.c'],
 
3044
            root_id)
 
3045
        lib_wt = self.setup_simple_branch(
 
3046
            'lib1', ['README', 'Makefile', 'foo.c'], root_id)
 
3047
 
 
3048
        return project_wt, lib_wt
 
3049
 
 
3050
    def do_merge_into(self, location, merge_as):
 
3051
        """Helper for using MergeIntoMerger.
 
3052
        
 
3053
        :param location: location of directory to merge from, either the
 
3054
            location of a branch or of a path inside a branch.
 
3055
        :param merge_as: the path in a tree to add the new directory as.
 
3056
        :returns: the conflicts from 'do_merge'.
 
3057
        """
 
3058
        operation = cleanup.OperationWithCleanups(self._merge_into)
 
3059
        return operation.run(location, merge_as)
 
3060
 
 
3061
    def _merge_into(self, op, location, merge_as):
 
3062
        # Open and lock the various tree and branch objects
 
3063
        wt, subdir_relpath = WorkingTree.open_containing(merge_as)
 
3064
        op.add_cleanup(wt.lock_write().unlock)
 
3065
        branch_to_merge, subdir_to_merge = _mod_branch.Branch.open_containing(
 
3066
            location)
 
3067
        op.add_cleanup(branch_to_merge.lock_read().unlock)
 
3068
        other_tree = branch_to_merge.basis_tree()
 
3069
        op.add_cleanup(other_tree.lock_read().unlock)
 
3070
        # Perform the merge
 
3071
        merger = _mod_merge.MergeIntoMerger(this_tree=wt, other_tree=other_tree,
 
3072
            other_branch=branch_to_merge, target_subdir=subdir_relpath,
 
3073
            source_subpath=subdir_to_merge)
 
3074
        merger.set_base_revision(_mod_revision.NULL_REVISION, branch_to_merge)
 
3075
        conflicts = merger.do_merge()
 
3076
        merger.set_pending()
 
3077
        return conflicts
 
3078
 
 
3079
    def assertTreeEntriesEqual(self, expected_entries, tree):
 
3080
        """Assert that 'tree' contains the expected inventory entries.
 
3081
 
 
3082
        :param expected_entries: sequence of (path, file-id) pairs.
 
3083
        """
 
3084
        files = [(path, ie.file_id) for path, ie in tree.iter_entries_by_dir()]
 
3085
        self.assertEqual(expected_entries, files)
 
3086
 
 
3087
 
 
3088
class TestMergeInto(TestMergeIntoBase):
 
3089
 
 
3090
    def test_newdir_with_unique_roots(self):
 
3091
        """Merge a branch with a unique root into a new directory."""
 
3092
        project_wt, lib_wt = self.setup_two_branches()
 
3093
        self.do_merge_into('lib1', 'project/lib1')
 
3094
        project_wt.lock_read()
 
3095
        self.addCleanup(project_wt.unlock)
 
3096
        # The r1-lib1 revision should be merged into this one
 
3097
        self.assertEqual(['r1-project', 'r1-lib1'], project_wt.get_parent_ids())
 
3098
        self.assertTreeEntriesEqual(
 
3099
            [('', 'project-root-id'),
 
3100
             ('README', 'project-README-id'),
 
3101
             ('dir', 'project-dir-id'),
 
3102
             ('lib1', 'lib1-root-id'),
 
3103
             ('dir/file.c', 'project-file.c-id'),
 
3104
             ('lib1/Makefile', 'lib1-Makefile-id'),
 
3105
             ('lib1/README', 'lib1-README-id'),
 
3106
             ('lib1/foo.c', 'lib1-foo.c-id'),
 
3107
            ], project_wt)
 
3108
 
 
3109
    def test_subdir(self):
 
3110
        """Merge a branch into a subdirectory of an existing directory."""
 
3111
        project_wt, lib_wt = self.setup_two_branches()
 
3112
        self.do_merge_into('lib1', 'project/dir/lib1')
 
3113
        project_wt.lock_read()
 
3114
        self.addCleanup(project_wt.unlock)
 
3115
        # The r1-lib1 revision should be merged into this one
 
3116
        self.assertEqual(['r1-project', 'r1-lib1'], project_wt.get_parent_ids())
 
3117
        self.assertTreeEntriesEqual(
 
3118
            [('', 'project-root-id'),
 
3119
             ('README', 'project-README-id'),
 
3120
             ('dir', 'project-dir-id'),
 
3121
             ('dir/file.c', 'project-file.c-id'),
 
3122
             ('dir/lib1', 'lib1-root-id'),
 
3123
             ('dir/lib1/Makefile', 'lib1-Makefile-id'),
 
3124
             ('dir/lib1/README', 'lib1-README-id'),
 
3125
             ('dir/lib1/foo.c', 'lib1-foo.c-id'),
 
3126
            ], project_wt)
 
3127
 
 
3128
    def test_newdir_with_repeat_roots(self):
 
3129
        """If the file-id of the dir to be merged already exists a new ID will
 
3130
        be allocated to let the merge happen.
 
3131
        """
 
3132
        project_wt, lib_wt = self.setup_two_branches(custom_root_ids=False)
 
3133
        root_id = project_wt.path2id('')
 
3134
        self.do_merge_into('lib1', 'project/lib1')
 
3135
        project_wt.lock_read()
 
3136
        self.addCleanup(project_wt.unlock)
 
3137
        # The r1-lib1 revision should be merged into this one
 
3138
        self.assertEqual(['r1-project', 'r1-lib1'], project_wt.get_parent_ids())
 
3139
        new_lib1_id = project_wt.path2id('lib1')
 
3140
        self.assertNotEqual(None, new_lib1_id)
 
3141
        self.assertTreeEntriesEqual(
 
3142
            [('', root_id),
 
3143
             ('README', 'project-README-id'),
 
3144
             ('dir', 'project-dir-id'),
 
3145
             ('lib1', new_lib1_id),
 
3146
             ('dir/file.c', 'project-file.c-id'),
 
3147
             ('lib1/Makefile', 'lib1-Makefile-id'),
 
3148
             ('lib1/README', 'lib1-README-id'),
 
3149
             ('lib1/foo.c', 'lib1-foo.c-id'),
 
3150
            ], project_wt)
 
3151
 
 
3152
    def test_name_conflict(self):
 
3153
        """When the target directory name already exists a conflict is
 
3154
        generated and the original directory is renamed to foo.moved.
 
3155
        """
 
3156
        dest_wt = self.setup_simple_branch('dest', ['dir/', 'dir/file.txt'])
 
3157
        src_wt = self.setup_simple_branch('src', ['README'])
 
3158
        conflicts = self.do_merge_into('src', 'dest/dir')
 
3159
        self.assertEqual(1, conflicts)
 
3160
        dest_wt.lock_read()
 
3161
        self.addCleanup(dest_wt.unlock)
 
3162
        # The r1-lib1 revision should be merged into this one
 
3163
        self.assertEqual(['r1-dest', 'r1-src'], dest_wt.get_parent_ids())
 
3164
        self.assertTreeEntriesEqual(
 
3165
            [('', 'dest-root-id'),
 
3166
             ('dir', 'src-root-id'),
 
3167
             ('dir.moved', 'dest-dir-id'),
 
3168
             ('dir/README', 'src-README-id'),
 
3169
             ('dir.moved/file.txt', 'dest-file.txt-id'),
 
3170
            ], dest_wt)
 
3171
 
 
3172
    def test_file_id_conflict(self):
 
3173
        """A conflict is generated if the merge-into adds a file (or other
 
3174
        inventory entry) with a file-id that already exists in the target tree.
 
3175
        """
 
3176
        dest_wt = self.setup_simple_branch('dest', ['file.txt'])
 
3177
        # Make a second tree with a file-id that will clash with file.txt in
 
3178
        # dest.
 
3179
        src_wt = self.make_branch_and_tree('src')
 
3180
        self.build_tree(['src/README'])
 
3181
        src_wt.add(['README'], ids=['dest-file.txt-id'])
 
3182
        src_wt.commit("Rev 1 of src.", rev_id='r1-src')
 
3183
        conflicts = self.do_merge_into('src', 'dest/dir')
 
3184
        # This is an edge case that shouldn't happen to users very often.  So
 
3185
        # we don't care really about the exact presentation of the conflict,
 
3186
        # just that there is one.
 
3187
        self.assertEqual(1, conflicts)
 
3188
 
 
3189
    def test_only_subdir(self):
 
3190
        """When the location points to just part of a tree, merge just that
 
3191
        subtree.
 
3192
        """
 
3193
        dest_wt = self.setup_simple_branch('dest')
 
3194
        src_wt = self.setup_simple_branch(
 
3195
            'src', ['hello.txt', 'dir/', 'dir/foo.c'])
 
3196
        conflicts = self.do_merge_into('src/dir', 'dest/dir')
 
3197
        dest_wt.lock_read()
 
3198
        self.addCleanup(dest_wt.unlock)
 
3199
        # The r1-lib1 revision should NOT be merged into this one (this is a
 
3200
        # partial merge).
 
3201
        self.assertEqual(['r1-dest'], dest_wt.get_parent_ids())
 
3202
        self.assertTreeEntriesEqual(
 
3203
            [('', 'dest-root-id'),
 
3204
             ('dir', 'src-dir-id'),
 
3205
             ('dir/foo.c', 'src-foo.c-id'),
 
3206
            ], dest_wt)
 
3207
 
 
3208
    def test_only_file(self):
 
3209
        """An edge case: merge just one file, not a whole dir."""
 
3210
        dest_wt = self.setup_simple_branch('dest')
 
3211
        two_file_wt = self.setup_simple_branch(
 
3212
            'two-file', ['file1.txt', 'file2.txt'])
 
3213
        conflicts = self.do_merge_into('two-file/file1.txt', 'dest/file1.txt')
 
3214
        dest_wt.lock_read()
 
3215
        self.addCleanup(dest_wt.unlock)
 
3216
        # The r1-lib1 revision should NOT be merged into this one
 
3217
        self.assertEqual(['r1-dest'], dest_wt.get_parent_ids())
 
3218
        self.assertTreeEntriesEqual(
 
3219
            [('', 'dest-root-id'), ('file1.txt', 'two-file-file1.txt-id')],
 
3220
            dest_wt)
 
3221
 
 
3222
    def test_no_such_source_path(self):
 
3223
        """PathNotInTree is raised if the specified path in the source tree
 
3224
        does not exist.
 
3225
        """
 
3226
        dest_wt = self.setup_simple_branch('dest')
 
3227
        two_file_wt = self.setup_simple_branch('src', ['dir/'])
 
3228
        self.assertRaises(_mod_merge.PathNotInTree, self.do_merge_into,
 
3229
            'src/no-such-dir', 'dest/foo')
 
3230
        dest_wt.lock_read()
 
3231
        self.addCleanup(dest_wt.unlock)
 
3232
        # The dest tree is unmodified.
 
3233
        self.assertEqual(['r1-dest'], dest_wt.get_parent_ids())
 
3234
        self.assertTreeEntriesEqual([('', 'dest-root-id')], dest_wt)
 
3235
 
 
3236
    def test_no_such_target_path(self):
 
3237
        """PathNotInTree is also raised if the specified path in the target
 
3238
        tree does not exist.
 
3239
        """
 
3240
        dest_wt = self.setup_simple_branch('dest')
 
3241
        two_file_wt = self.setup_simple_branch('src', ['file.txt'])
 
3242
        self.assertRaises(_mod_merge.PathNotInTree, self.do_merge_into,
 
3243
            'src', 'dest/no-such-dir/foo')
 
3244
        dest_wt.lock_read()
 
3245
        self.addCleanup(dest_wt.unlock)
 
3246
        # The dest tree is unmodified.
 
3247
        self.assertEqual(['r1-dest'], dest_wt.get_parent_ids())
 
3248
        self.assertTreeEntriesEqual([('', 'dest-root-id')], dest_wt)
 
3249
 
 
3250
 
 
3251
class TestMergeHooks(TestCaseWithTransport):
 
3252
 
 
3253
    def setUp(self):
 
3254
        super(TestMergeHooks, self).setUp()
 
3255
        self.tree_a = self.make_branch_and_tree('tree_a')
 
3256
        self.build_tree_contents([('tree_a/file', 'content_1')])
 
3257
        self.tree_a.add('file', 'file-id')
 
3258
        self.tree_a.commit('added file')
 
3259
 
 
3260
        self.tree_b = self.tree_a.bzrdir.sprout('tree_b').open_workingtree()
 
3261
        self.build_tree_contents([('tree_b/file', 'content_2')])
 
3262
        self.tree_b.commit('modify file')
 
3263
 
 
3264
    def test_pre_merge_hook_inject_different_tree(self):
 
3265
        tree_c = self.tree_b.bzrdir.sprout('tree_c').open_workingtree()
 
3266
        self.build_tree_contents([('tree_c/file', 'content_3')])
 
3267
        tree_c.commit("more content")
 
3268
        calls = []
 
3269
        def factory(merger):
 
3270
            self.assertIsInstance(merger, _mod_merge.Merge3Merger)
 
3271
            merger.other_tree = tree_c
 
3272
            calls.append(merger)
 
3273
        _mod_merge.Merger.hooks.install_named_hook('pre_merge',
 
3274
                                                   factory, 'test factory')
 
3275
        self.tree_a.merge_from_branch(self.tree_b.branch)
 
3276
 
 
3277
        self.assertFileEqual("content_3", 'tree_a/file')
 
3278
        self.assertLength(1, calls)
 
3279
 
 
3280
    def test_post_merge_hook_called(self):
 
3281
        calls = []
 
3282
        def factory(merger):
 
3283
            self.assertIsInstance(merger, _mod_merge.Merge3Merger)
 
3284
            calls.append(merger)
 
3285
        _mod_merge.Merger.hooks.install_named_hook('post_merge',
 
3286
                                                   factory, 'test factory')
 
3287
 
 
3288
        self.tree_a.merge_from_branch(self.tree_b.branch)
 
3289
 
 
3290
        self.assertFileEqual("content_2", 'tree_a/file')
 
3291
        self.assertLength(1, calls)