~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-09-29 22:03:03 UTC
  • mfrom: (5416.2.6 jam-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20100929220303-cr95h8iwtggco721
(mbp) Add 'break-lock --force'

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
import errno
18
17
import os
19
18
from StringIO import StringIO
20
19
import sys
28
27
    osutils,
29
28
    revision as _mod_revision,
30
29
    rules,
31
 
    symbol_versioning,
32
30
    tests,
33
 
    trace,
34
 
    transform,
35
31
    urlutils,
36
32
    )
 
33
from bzrlib.bzrdir import BzrDir
37
34
from bzrlib.conflicts import (
38
35
    DeletingParent,
39
36
    DuplicateEntry,
43
40
    ParentLoop,
44
41
    UnversionedParent,
45
42
)
46
 
from bzrlib.controldir import ControlDir
47
43
from bzrlib.diff import show_diff_trees
48
44
from bzrlib.errors import (
49
45
    DuplicateKey,
53
49
    ImmortalPendingDeletion,
54
50
    LockError,
55
51
    MalformedTransform,
 
52
    NoSuchFile,
56
53
    ReusingTransform,
57
54
)
58
55
from bzrlib.osutils import (
60
57
    pathjoin,
61
58
)
62
59
from bzrlib.merge import Merge3Merger, Merger
63
 
from bzrlib.mutabletree import MutableTree
64
60
from bzrlib.tests import (
65
 
    features,
 
61
    HardlinkFeature,
 
62
    SymlinkFeature,
 
63
    TestCase,
66
64
    TestCaseInTempDir,
67
65
    TestSkipped,
68
 
    )
69
 
from bzrlib.tests.features import (
70
 
    HardlinkFeature,
71
 
    SymlinkFeature,
72
 
    )
 
66
)
73
67
from bzrlib.transform import (
74
68
    build_tree,
75
69
    create_from_tree,
76
70
    cook_conflicts,
77
71
    _FileMover,
78
72
    FinalPaths,
 
73
    get_backup_name,
79
74
    resolve_conflicts,
80
75
    resolve_checkout,
81
76
    ROOT_PARENT,
88
83
 
89
84
    def setUp(self):
90
85
        super(TestTreeTransform, self).setUp()
91
 
        self.wt = self.make_branch_and_tree('.', format='development-subtree')
 
86
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
92
87
        os.chdir('..')
93
88
 
94
89
    def get_transform(self):
96
91
        self.addCleanup(transform.finalize)
97
92
        return transform, transform.root
98
93
 
99
 
    def get_transform_for_sha1_test(self):
100
 
        trans, root = self.get_transform()
101
 
        self.wt.lock_tree_write()
102
 
        self.addCleanup(self.wt.unlock)
103
 
        contents = ['just some content\n']
104
 
        sha1 = osutils.sha_strings(contents)
105
 
        # Roll back the clock
106
 
        trans._creation_mtime = time.time() - 20.0
107
 
        return trans, root, contents, sha1
108
 
 
109
94
    def test_existing_limbo(self):
110
95
        transform, root = self.get_transform()
111
96
        limbo_name = transform._limbodir
174
159
        transform.finalize()
175
160
        transform.finalize()
176
161
 
177
 
    def test_apply_informs_tree_of_observed_sha1(self):
178
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
179
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
180
 
                                  sha1=sha1)
181
 
        calls = []
182
 
        orig = self.wt._observed_sha1
183
 
        def _observed_sha1(*args):
184
 
            calls.append(args)
185
 
            orig(*args)
186
 
        self.wt._observed_sha1 = _observed_sha1
187
 
        trans.apply()
188
 
        self.assertEqual([(None, 'file1', trans._observed_sha1s[trans_id])],
189
 
                         calls)
190
 
 
191
 
    def test_create_file_caches_sha1(self):
192
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
193
 
        trans_id = trans.create_path('file1', root)
194
 
        trans.create_file(contents, trans_id, sha1=sha1)
195
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
196
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
197
 
        self.assertEqual(o_sha1, sha1)
198
 
        self.assertEqualStat(o_st_val, st_val)
199
 
 
200
 
    def test__apply_insertions_updates_sha1(self):
201
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
202
 
        trans_id = trans.create_path('file1', root)
203
 
        trans.create_file(contents, trans_id, sha1=sha1)
204
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
205
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
206
 
        self.assertEqual(o_sha1, sha1)
207
 
        self.assertEqualStat(o_st_val, st_val)
208
 
        creation_mtime = trans._creation_mtime + 10.0
209
 
        # We fake a time difference from when the file was created until now it
210
 
        # is being renamed by using os.utime. Note that the change we actually
211
 
        # want to see is the real ctime change from 'os.rename()', but as long
212
 
        # as we observe a new stat value, we should be fine.
213
 
        os.utime(trans._limbo_name(trans_id), (creation_mtime, creation_mtime))
214
 
        trans.apply()
215
 
        new_st_val = osutils.lstat(self.wt.abspath('file1'))
216
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
217
 
        self.assertEqual(o_sha1, sha1)
218
 
        self.assertEqualStat(o_st_val, new_st_val)
219
 
        self.assertNotEqual(st_val.st_mtime, new_st_val.st_mtime)
220
 
 
221
 
    def test_new_file_caches_sha1(self):
222
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
223
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
224
 
                                  sha1=sha1)
225
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
226
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
227
 
        self.assertEqual(o_sha1, sha1)
228
 
        self.assertEqualStat(o_st_val, st_val)
229
 
 
230
 
    def test_cancel_creation_removes_observed_sha1(self):
231
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
232
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
233
 
                                  sha1=sha1)
234
 
        self.assertTrue(trans_id in trans._observed_sha1s)
235
 
        trans.cancel_creation(trans_id)
236
 
        self.assertFalse(trans_id in trans._observed_sha1s)
237
 
 
238
162
    def test_create_files_same_timestamp(self):
239
163
        transform, root = self.get_transform()
240
164
        self.wt.lock_tree_write()
288
212
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
289
213
        self.assertRaises(ValueError, transform.fixup_new_roots)
290
214
 
291
 
    def test_retain_existing_root(self):
292
 
        tt, root = self.get_transform()
293
 
        with tt:
294
 
            tt.new_directory('', ROOT_PARENT, 'new-root-id')
295
 
            tt.fixup_new_roots()
296
 
            self.assertNotEqual('new-root-id', tt.final_file_id(tt.root))
297
 
 
298
 
    def test_retain_existing_root_added_file(self):
299
 
        tt, root = self.get_transform()
300
 
        new_trans_id = tt.new_directory('', ROOT_PARENT, 'new-root-id')
301
 
        child = tt.new_directory('child', new_trans_id, 'child-id')
302
 
        tt.fixup_new_roots()
303
 
        self.assertEqual(tt.root, tt.final_parent(child))
304
 
 
305
 
    def test_add_unversioned_root(self):
306
 
        transform, root = self.get_transform()
307
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, None)
308
 
        transform.delete_contents(transform.root)
309
 
        transform.fixup_new_roots()
310
 
        self.assertNotIn(transform.root, transform._new_id)
311
 
 
312
 
    def test_remove_root_fixup(self):
313
 
        transform, root = self.get_transform()
314
 
        old_root_id = self.wt.get_root_id()
315
 
        self.assertNotEqual('new-root-id', old_root_id)
316
 
        transform.delete_contents(root)
317
 
        transform.unversion_file(root)
318
 
        transform.fixup_new_roots()
319
 
        transform.apply()
320
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
321
 
 
322
 
        transform, root = self.get_transform()
323
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
324
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
325
 
        self.assertRaises(ValueError, transform.fixup_new_roots)
326
 
 
327
 
    def test_fixup_new_roots_permits_empty_tree(self):
328
 
        transform, root = self.get_transform()
329
 
        transform.delete_contents(root)
330
 
        transform.unversion_file(root)
331
 
        transform.fixup_new_roots()
332
 
        self.assertIs(None, transform.final_kind(root))
333
 
        self.assertIs(None, transform.final_file_id(root))
334
 
 
335
 
    def test_apply_retains_root_directory(self):
336
 
        # Do not attempt to delete the physical root directory, because that
337
 
        # is impossible.
338
 
        transform, root = self.get_transform()
339
 
        with transform:
340
 
            transform.delete_contents(root)
341
 
            e = self.assertRaises(AssertionError, self.assertRaises,
342
 
                                  errors.TransformRenameFailed,
343
 
                                  transform.apply)
344
 
        self.assertContainsRe('TransformRenameFailed not raised', str(e))
345
 
 
346
 
    def test_apply_retains_file_id(self):
347
 
        transform, root = self.get_transform()
348
 
        old_root_id = transform.tree_file_id(root)
349
 
        transform.unversion_file(root)
350
 
        transform.apply()
351
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
352
 
 
353
215
    def test_hardlink(self):
354
216
        self.requireFeature(HardlinkFeature)
355
217
        transform, root = self.get_transform()
360
222
        trans_id = target_transform.create_path('file1', target_transform.root)
361
223
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
362
224
        target_transform.apply()
363
 
        self.assertPathExists('target/file1')
 
225
        self.failUnlessExists('target/file1')
364
226
        source_stat = os.stat(self.wt.abspath('file1'))
365
227
        target_stat = os.stat('target/file1')
366
228
        self.assertEqual(source_stat, target_stat)
399
261
        tree.lock_read()
400
262
        self.addCleanup(tree.unlock)
401
263
        self.assertEqual('subtree-revision',
402
 
                         tree.root_inventory['subtree-id'].reference_revision)
 
264
                         tree.inventory['subtree-id'].reference_revision)
403
265
 
404
266
    def test_conflicts(self):
405
267
        transform, root = self.get_transform()
532
394
        transform.new_file('FiLe', transform.root, 'content')
533
395
        resolve_conflicts(transform)
534
396
        transform.apply()
535
 
        self.assertPathExists('tree/file')
536
 
        self.assertPathExists('tree/FiLe.moved')
 
397
        self.failUnlessExists('tree/file')
 
398
        self.failUnlessExists('tree/FiLe.moved')
537
399
 
538
400
    def test_resolve_checkout_case_conflict(self):
539
401
        tree = self.make_branch_and_tree('tree')
548
410
        resolve_conflicts(transform,
549
411
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
550
412
        transform.apply()
551
 
        self.assertPathExists('tree/file')
552
 
        self.assertPathExists('tree/FiLe.moved')
 
413
        self.failUnlessExists('tree/file')
 
414
        self.failUnlessExists('tree/FiLe.moved')
553
415
 
554
416
    def test_apply_case_conflict(self):
555
417
        """Ensure that a transform with case conflicts can always be applied"""
563
425
        transform.new_file('dirFiLe', dir, 'content')
564
426
        resolve_conflicts(transform)
565
427
        transform.apply()
566
 
        self.assertPathExists('tree/file')
 
428
        self.failUnlessExists('tree/file')
567
429
        if not os.path.exists('tree/FiLe.moved'):
568
 
            self.assertPathExists('tree/FiLe')
569
 
        self.assertPathExists('tree/dir/dirfile')
 
430
            self.failUnlessExists('tree/FiLe')
 
431
        self.failUnlessExists('tree/dir/dirfile')
570
432
        if not os.path.exists('tree/dir/dirFiLe.moved'):
571
 
            self.assertPathExists('tree/dir/dirFiLe')
 
433
            self.failUnlessExists('tree/dir/dirFiLe')
572
434
 
573
435
    def test_case_insensitive_limbo(self):
574
436
        tree = self.make_branch_and_tree('tree')
782
644
                            'wizard2', 'behind_curtain')
783
645
 
784
646
    def test_symlinks_unicode(self):
785
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
647
        self.requireFeature(tests.UnicodeFilenameFeature)
786
648
        self._test_symlinks(u'\N{Euro Sign}wizard',
787
649
                            u'wizard-targ\N{Euro Sign}t',
788
650
                            u'\N{Euro Sign}wizard2',
876
738
        raw_conflicts = resolve_conflicts(tt)
877
739
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
878
740
        tt.finalize()
879
 
        conflicts_s = [unicode(c) for c in cooked_conflicts]
 
741
        conflicts_s = [str(c) for c in cooked_conflicts]
880
742
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
881
743
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
882
744
                                         'Moved existing file to '
952
814
        self.assertIs(None, self.wt.path2id('parent'))
953
815
        self.assertIs(None, self.wt.path2id('parent.new'))
954
816
 
955
 
    def test_resolve_conflicts_missing_parent(self):
956
 
        wt = self.make_branch_and_tree('.')
957
 
        tt = TreeTransform(wt)
958
 
        self.addCleanup(tt.finalize)
959
 
        parent = tt.trans_id_file_id('parent-id')
960
 
        tt.new_file('file', parent, 'Contents')
961
 
        raw_conflicts = resolve_conflicts(tt)
962
 
        # Since the directory doesn't exist it's seen as 'missing'.  So
963
 
        # 'resolve_conflicts' create a conflict asking for it to be created.
964
 
        self.assertLength(1, raw_conflicts)
965
 
        self.assertEqual(('missing parent', 'Created directory', 'new-1'),
966
 
                         raw_conflicts.pop())
967
 
        # apply fail since the missing directory doesn't exist
968
 
        self.assertRaises(errors.NoFinalPath, tt.apply)
969
 
 
970
817
    def test_moving_versioned_directories(self):
971
818
        create, root = self.get_transform()
972
819
        kansas = create.new_directory('kansas', root, 'kansas-id')
1006
853
        rename.apply()
1007
854
 
1008
855
    def test_rename_fails(self):
1009
 
        self.requireFeature(features.not_running_as_root)
1010
856
        # see https://bugs.launchpad.net/bzr/+bug/491763
1011
857
        create, root_id = self.get_transform()
1012
858
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
1034
880
        # On windows looks like:
1035
881
        # "Failed to rename .../work/myfile to 
1036
882
        # .../work/.bzr/checkout/limbo/new-1: [Errno 13] Permission denied"
1037
 
        # This test isn't concerned with exactly what the error looks like,
1038
 
        # and the strerror will vary across OS and locales, but the assert
1039
 
        # that the exeception attributes are what we expect
1040
 
        self.assertEqual(e.errno, errno.EACCES)
1041
 
        if os.name == "posix":
1042
 
            self.assertEndsWith(e.to_path, "/first-dir/newname")
1043
 
        else:
1044
 
            self.assertEqual(os.path.basename(e.from_path), "myfile")
 
883
        # The strerror will vary per OS and language so it's not checked here
 
884
        self.assertContainsRe(str(e),
 
885
            "Failed to rename .*(first-dir.newname:|myfile)")
1045
886
 
1046
887
    def test_set_executability_order(self):
1047
888
        """Ensure that executability behaves the same, no matter what order.
1320
1161
        parent2 = transform.new_directory('parent2', root)
1321
1162
        transform.adjust_path('child1', parent2, child1)
1322
1163
        transform.apply()
1323
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
1324
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1164
        self.failIfExists(self.wt.abspath('parent1/child1'))
 
1165
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1325
1166
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1326
1167
        # no rename for child1 (counting only renames during apply)
1327
 
        self.assertEqual(2, transform.rename_count)
 
1168
        self.failUnlessEqual(2, transform.rename_count)
1328
1169
 
1329
1170
    def test_cancel_parent(self):
1330
1171
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1353
1194
        parent2 = transform.new_directory('parent2', root)
1354
1195
        transform.adjust_path('child1', parent2, child1)
1355
1196
        transform.apply()
1356
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
1357
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1197
        self.failIfExists(self.wt.abspath('parent1'))
 
1198
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1358
1199
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1359
 
        self.assertEqual(2, transform.rename_count)
 
1200
        self.failUnlessEqual(2, transform.rename_count)
1360
1201
 
1361
1202
    def test_adjust_and_cancel(self):
1362
1203
        """Make sure adjust_path keeps track of limbo children properly"""
1395
1236
        child = transform.new_directory('child', parent)
1396
1237
        transform.adjust_path('parent', root, parent)
1397
1238
        transform.apply()
1398
 
        self.assertPathExists(self.wt.abspath('parent/child'))
 
1239
        self.failUnlessExists(self.wt.abspath('parent/child'))
1399
1240
        self.assertEqual(1, transform.rename_count)
1400
1241
 
1401
1242
    def test_reuse_name(self):
1477
1318
        # The rename will fail because the target directory is not empty (but
1478
1319
        # raises FileExists anyway).
1479
1320
        err = self.assertRaises(errors.FileExists, tt_helper)
1480
 
        self.assertEndsWith(err.path, "/baz")
 
1321
        self.assertContainsRe(str(err),
 
1322
            "^File exists: .+/baz")
1481
1323
 
1482
1324
    def test_two_directories_clash(self):
1483
1325
        def tt_helper():
1495
1337
                wt.unlock()
1496
1338
                raise
1497
1339
        err = self.assertRaises(errors.FileExists, tt_helper)
1498
 
        self.assertEndsWith(err.path, "/foo")
 
1340
        self.assertContainsRe(str(err),
 
1341
            "^File exists: .+/foo")
1499
1342
 
1500
1343
    def test_two_directories_clash_finalize(self):
1501
1344
        def tt_helper():
1513
1356
                tt.finalize()
1514
1357
                raise
1515
1358
        err = self.assertRaises(errors.FileExists, tt_helper)
1516
 
        self.assertEndsWith(err.path, "/foo")
 
1359
        self.assertContainsRe(str(err),
 
1360
            "^File exists: .+/foo")
1517
1361
 
1518
1362
    def test_file_to_directory(self):
1519
1363
        wt = self.make_branch_and_tree('.')
1529
1373
        tt.create_file(["aa\n"], bar_trans_id)
1530
1374
        tt.version_file("bar-1", bar_trans_id)
1531
1375
        tt.apply()
1532
 
        self.assertPathExists("foo/bar")
 
1376
        self.failUnlessExists("foo/bar")
1533
1377
        wt.lock_read()
1534
1378
        try:
1535
 
            self.assertEqual(wt.kind(wt.path2id("foo")), "directory")
 
1379
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
 
1380
                    "directory")
1536
1381
        finally:
1537
1382
            wt.unlock()
1538
1383
        wt.commit("two")
1551
1396
        tt.delete_contents(foo_trans_id)
1552
1397
        tt.create_symlink("bar", foo_trans_id)
1553
1398
        tt.apply()
1554
 
        self.assertPathExists("foo")
 
1399
        self.failUnlessExists("foo")
1555
1400
        wt.lock_read()
1556
1401
        self.addCleanup(wt.unlock)
1557
 
        self.assertEqual(wt.kind(wt.path2id("foo")), "symlink")
 
1402
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
 
1403
                "symlink")
1558
1404
 
1559
1405
    def test_dir_to_file(self):
1560
1406
        wt = self.make_branch_and_tree('.')
1569
1415
        tt.delete_versioned(bar_trans_id)
1570
1416
        tt.create_file(["aa\n"], foo_trans_id)
1571
1417
        tt.apply()
1572
 
        self.assertPathExists("foo")
 
1418
        self.failUnlessExists("foo")
1573
1419
        wt.lock_read()
1574
1420
        self.addCleanup(wt.unlock)
1575
 
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
 
1421
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
 
1422
                "file")
1576
1423
 
1577
1424
    def test_dir_to_hardlink(self):
1578
1425
        self.requireFeature(HardlinkFeature)
1589
1436
        self.build_tree(['baz'])
1590
1437
        tt.create_hardlink("baz", foo_trans_id)
1591
1438
        tt.apply()
1592
 
        self.assertPathExists("foo")
1593
 
        self.assertPathExists("baz")
 
1439
        self.failUnlessExists("foo")
 
1440
        self.failUnlessExists("baz")
1594
1441
        wt.lock_read()
1595
1442
        self.addCleanup(wt.unlock)
1596
 
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
 
1443
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
 
1444
                "file")
1597
1445
 
1598
1446
    def test_no_final_path(self):
1599
1447
        transform, root = self.get_transform()
1645
1493
    def __init__(self, dirname, root_id):
1646
1494
        self.name = dirname
1647
1495
        os.mkdir(dirname)
1648
 
        self.wt = ControlDir.create_standalone_workingtree(dirname)
 
1496
        self.wt = BzrDir.create_standalone_workingtree(dirname)
1649
1497
        self.wt.set_root_id(root_id)
1650
1498
        self.b = self.wt.branch
1651
1499
        self.tt = TreeTransform(self.wt)
1657
1505
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1658
1506
 
1659
1507
 
1660
 
class TestInventoryAltered(tests.TestCaseWithTransport):
1661
 
 
1662
 
    def test_inventory_altered_unchanged(self):
1663
 
        tree = self.make_branch_and_tree('tree')
1664
 
        self.build_tree(['tree/foo'])
1665
 
        tree.add('foo', 'foo-id')
1666
 
        with TransformPreview(tree) as tt:
1667
 
            self.assertEqual([], tt._inventory_altered())
1668
 
 
1669
 
    def test_inventory_altered_changed_parent_id(self):
1670
 
        tree = self.make_branch_and_tree('tree')
1671
 
        self.build_tree(['tree/foo'])
1672
 
        tree.add('foo', 'foo-id')
1673
 
        with TransformPreview(tree) as tt:
1674
 
            tt.unversion_file(tt.root)
1675
 
            tt.version_file('new-id', tt.root)
1676
 
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1677
 
            foo_tuple = ('foo', foo_trans_id)
1678
 
            root_tuple = ('', tt.root)
1679
 
            self.assertEqual([root_tuple, foo_tuple], tt._inventory_altered())
1680
 
 
1681
 
    def test_inventory_altered_noop_changed_parent_id(self):
1682
 
        tree = self.make_branch_and_tree('tree')
1683
 
        self.build_tree(['tree/foo'])
1684
 
        tree.add('foo', 'foo-id')
1685
 
        with TransformPreview(tree) as tt:
1686
 
            tt.unversion_file(tt.root)
1687
 
            tt.version_file(tree.get_root_id(), tt.root)
1688
 
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1689
 
            self.assertEqual([], tt._inventory_altered())
1690
 
 
1691
 
 
1692
1508
class TestTransformMerge(TestCaseInTempDir):
1693
1509
 
1694
1510
    def test_text_merge(self):
1761
1577
        merge_modified = this.wt.merge_modified()
1762
1578
        self.assertSubset(merge_modified, modified)
1763
1579
        self.assertEqual(len(merge_modified), len(modified))
1764
 
        with file(this.wt.id2abspath('a'), 'wb') as f: f.write('booga')
 
1580
        file(this.wt.id2abspath('a'), 'wb').write('booga')
1765
1581
        modified.pop(0)
1766
1582
        merge_modified = this.wt.merge_modified()
1767
1583
        self.assertSubset(merge_modified, modified)
1881
1697
    def test_build_tree_with_symlinks(self):
1882
1698
        self.requireFeature(SymlinkFeature)
1883
1699
        os.mkdir('a')
1884
 
        a = ControlDir.create_standalone_workingtree('a')
 
1700
        a = BzrDir.create_standalone_workingtree('a')
1885
1701
        os.mkdir('a/foo')
1886
 
        with file('a/foo/bar', 'wb') as f: f.write('contents')
 
1702
        file('a/foo/bar', 'wb').write('contents')
1887
1703
        os.symlink('a/foo/bar', 'a/foo/baz')
1888
1704
        a.add(['foo', 'foo/bar', 'foo/baz'])
1889
1705
        a.commit('initial commit')
1890
 
        b = ControlDir.create_standalone_workingtree('b')
 
1706
        b = BzrDir.create_standalone_workingtree('b')
1891
1707
        basis = a.basis_tree()
1892
1708
        basis.lock_read()
1893
1709
        self.addCleanup(basis.unlock)
1898
1714
 
1899
1715
    def test_build_with_references(self):
1900
1716
        tree = self.make_branch_and_tree('source',
1901
 
            format='development-subtree')
 
1717
            format='dirstate-with-subtree')
1902
1718
        subtree = self.make_branch_and_tree('source/subtree',
1903
 
            format='development-subtree')
 
1719
            format='dirstate-with-subtree')
1904
1720
        tree.add_reference(subtree)
1905
1721
        tree.commit('a revision')
1906
1722
        tree.branch.create_checkout('target')
1907
 
        self.assertPathExists('target')
1908
 
        self.assertPathExists('target/subtree')
 
1723
        self.failUnlessExists('target')
 
1724
        self.failUnlessExists('target/subtree')
1909
1725
 
1910
1726
    def test_file_conflict_handling(self):
1911
1727
        """Ensure that when building trees, conflict handling is done"""
1958
1774
        source.commit('added file')
1959
1775
        build_tree(source.basis_tree(), target)
1960
1776
        self.assertEqual([], target.conflicts())
1961
 
        self.assertPathExists('target/dir1/file')
 
1777
        self.failUnlessExists('target/dir1/file')
1962
1778
 
1963
1779
        # Ensure contents are merged
1964
1780
        target = self.make_branch_and_tree('target2')
1965
1781
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1966
1782
        build_tree(source.basis_tree(), target)
1967
1783
        self.assertEqual([], target.conflicts())
1968
 
        self.assertPathExists('target2/dir1/file2')
1969
 
        self.assertPathExists('target2/dir1/file')
 
1784
        self.failUnlessExists('target2/dir1/file2')
 
1785
        self.failUnlessExists('target2/dir1/file')
1970
1786
 
1971
1787
        # Ensure new contents are suppressed for existing branches
1972
1788
        target = self.make_branch_and_tree('target3')
1973
1789
        self.make_branch('target3/dir1')
1974
1790
        self.build_tree(['target3/dir1/file2'])
1975
1791
        build_tree(source.basis_tree(), target)
1976
 
        self.assertPathDoesNotExist('target3/dir1/file')
1977
 
        self.assertPathExists('target3/dir1/file2')
1978
 
        self.assertPathExists('target3/dir1.diverted/file')
 
1792
        self.failIfExists('target3/dir1/file')
 
1793
        self.failUnlessExists('target3/dir1/file2')
 
1794
        self.failUnlessExists('target3/dir1.diverted/file')
1979
1795
        self.assertEqual([DuplicateEntry('Diverted to',
1980
1796
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1981
1797
            target.conflicts())
1984
1800
        self.build_tree(['target4/dir1/'])
1985
1801
        self.make_branch('target4/dir1/file')
1986
1802
        build_tree(source.basis_tree(), target)
1987
 
        self.assertPathExists('target4/dir1/file')
 
1803
        self.failUnlessExists('target4/dir1/file')
1988
1804
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1989
 
        self.assertPathExists('target4/dir1/file.diverted')
 
1805
        self.failUnlessExists('target4/dir1/file.diverted')
1990
1806
        self.assertEqual([DuplicateEntry('Diverted to',
1991
1807
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1992
1808
            target.conflicts())
2060
1876
        self.addCleanup(target.unlock)
2061
1877
        self.assertEqual([], list(target.iter_changes(revision_tree)))
2062
1878
 
2063
 
    def test_build_tree_accelerator_tree_observes_sha1(self):
2064
 
        source = self.create_ab_tree()
2065
 
        sha1 = osutils.sha_string('A')
2066
 
        target = self.make_branch_and_tree('target')
2067
 
        target.lock_write()
2068
 
        self.addCleanup(target.unlock)
2069
 
        state = target.current_dirstate()
2070
 
        state._cutoff_time = time.time() + 60
2071
 
        build_tree(source.basis_tree(), target, source)
2072
 
        entry = state._get_entry(0, path_utf8='file1')
2073
 
        self.assertEqual(sha1, entry[1][0][1])
2074
 
 
2075
1879
    def test_build_tree_accelerator_tree_missing_file(self):
2076
1880
        source = self.create_ab_tree()
2077
1881
        os.unlink('source/file1')
2184
1988
        def rot13(chunks, context=None):
2185
1989
            return [''.join(chunks).encode('rot13')]
2186
1990
        rot13filter = filters.ContentFilter(rot13, rot13)
2187
 
        filters.filter_stacks_registry.register(
2188
 
            'rot13', {'yes': [rot13filter]}.get)
 
1991
        filters.register_filter_stack_map('rot13', {'yes': [rot13filter]}.get)
2189
1992
        os.mkdir(self.test_home_dir + '/.bazaar')
2190
1993
        rules_filename = self.test_home_dir + '/.bazaar/rules'
2191
1994
        f = open(rules_filename, 'wb')
2221
2024
        self.assertEqualStat(source_stat, target_stat)
2222
2025
 
2223
2026
    def test_case_insensitive_build_tree_inventory(self):
2224
 
        if (features.CaseInsensitiveFilesystemFeature.available()
2225
 
            or features.CaseInsCasePresFilenameFeature.available()):
 
2027
        if (tests.CaseInsensitiveFilesystemFeature.available()
 
2028
            or tests.CaseInsCasePresFilenameFeature.available()):
2226
2029
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
2227
2030
        source = self.make_branch_and_tree('source')
2228
2031
        self.build_tree(['source/file', 'source/FILE'])
2236
2039
        self.assertEqual('file.moved', target.id2path('lower-id'))
2237
2040
        self.assertEqual('FILE', target.id2path('upper-id'))
2238
2041
 
2239
 
    def test_build_tree_observes_sha(self):
2240
 
        source = self.make_branch_and_tree('source')
2241
 
        self.build_tree(['source/file1', 'source/dir/', 'source/dir/file2'])
2242
 
        source.add(['file1', 'dir', 'dir/file2'],
2243
 
                   ['file1-id', 'dir-id', 'file2-id'])
2244
 
        source.commit('new files')
2245
 
        target = self.make_branch_and_tree('target')
2246
 
        target.lock_write()
2247
 
        self.addCleanup(target.unlock)
2248
 
        # We make use of the fact that DirState caches its cutoff time. So we
2249
 
        # set the 'safe' time to one minute in the future.
2250
 
        state = target.current_dirstate()
2251
 
        state._cutoff_time = time.time() + 60
2252
 
        build_tree(source.basis_tree(), target)
2253
 
        entry1_sha = osutils.sha_file_by_name('source/file1')
2254
 
        entry2_sha = osutils.sha_file_by_name('source/dir/file2')
2255
 
        # entry[1] is the state information, entry[1][0] is the state of the
2256
 
        # working tree, entry[1][0][1] is the sha value for the current working
2257
 
        # tree
2258
 
        entry1 = state._get_entry(0, path_utf8='file1')
2259
 
        self.assertEqual(entry1_sha, entry1[1][0][1])
2260
 
        # The 'size' field must also be set.
2261
 
        self.assertEqual(25, entry1[1][0][2])
2262
 
        entry1_state = entry1[1][0]
2263
 
        entry2 = state._get_entry(0, path_utf8='dir/file2')
2264
 
        self.assertEqual(entry2_sha, entry2[1][0][1])
2265
 
        self.assertEqual(29, entry2[1][0][2])
2266
 
        entry2_state = entry2[1][0]
2267
 
        # Now, make sure that we don't have to re-read the content. The
2268
 
        # packed_stat should match exactly.
2269
 
        self.assertEqual(entry1_sha, target.get_file_sha1('file1-id', 'file1'))
2270
 
        self.assertEqual(entry2_sha,
2271
 
                         target.get_file_sha1('file2-id', 'dir/file2'))
2272
 
        self.assertEqual(entry1_state, entry1[1][0])
2273
 
        self.assertEqual(entry2_state, entry2[1][0])
2274
 
 
2275
2042
 
2276
2043
class TestCommitTransform(tests.TestCaseWithTransport):
2277
2044
 
2411
2178
        self.assertEqual('tree', revision.properties['branch-nick'])
2412
2179
 
2413
2180
 
 
2181
class MockTransform(object):
 
2182
 
 
2183
    def has_named_child(self, by_parent, parent_id, name):
 
2184
        for child_id in by_parent[parent_id]:
 
2185
            if child_id == '0':
 
2186
                if name == "name~":
 
2187
                    return True
 
2188
            elif name == "name.~%s~" % child_id:
 
2189
                return True
 
2190
        return False
 
2191
 
 
2192
 
 
2193
class MockEntry(object):
 
2194
    def __init__(self):
 
2195
        object.__init__(self)
 
2196
        self.name = "name"
 
2197
 
 
2198
 
 
2199
class TestGetBackupName(TestCase):
 
2200
    def test_get_backup_name(self):
 
2201
        tt = MockTransform()
 
2202
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
 
2203
        self.assertEqual(name, 'name.~1~')
 
2204
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
 
2205
        self.assertEqual(name, 'name.~2~')
 
2206
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
 
2207
        self.assertEqual(name, 'name.~1~')
 
2208
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
 
2209
        self.assertEqual(name, 'name.~1~')
 
2210
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
 
2211
        self.assertEqual(name, 'name.~4~')
 
2212
 
 
2213
 
2414
2214
class TestFileMover(tests.TestCaseWithTransport):
2415
2215
 
2416
2216
    def test_file_mover(self):
2417
2217
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2418
2218
        mover = _FileMover()
2419
2219
        mover.rename('a', 'q')
2420
 
        self.assertPathExists('q')
2421
 
        self.assertPathDoesNotExist('a')
2422
 
        self.assertPathExists('q/b')
2423
 
        self.assertPathExists('c')
2424
 
        self.assertPathExists('c/d')
 
2220
        self.failUnlessExists('q')
 
2221
        self.failIfExists('a')
 
2222
        self.failUnlessExists('q/b')
 
2223
        self.failUnlessExists('c')
 
2224
        self.failUnlessExists('c/d')
2425
2225
 
2426
2226
    def test_pre_delete_rollback(self):
2427
2227
        self.build_tree(['a/'])
2428
2228
        mover = _FileMover()
2429
2229
        mover.pre_delete('a', 'q')
2430
 
        self.assertPathExists('q')
2431
 
        self.assertPathDoesNotExist('a')
 
2230
        self.failUnlessExists('q')
 
2231
        self.failIfExists('a')
2432
2232
        mover.rollback()
2433
 
        self.assertPathDoesNotExist('q')
2434
 
        self.assertPathExists('a')
 
2233
        self.failIfExists('q')
 
2234
        self.failUnlessExists('a')
2435
2235
 
2436
2236
    def test_apply_deletions(self):
2437
2237
        self.build_tree(['a/', 'b/'])
2438
2238
        mover = _FileMover()
2439
2239
        mover.pre_delete('a', 'q')
2440
2240
        mover.pre_delete('b', 'r')
2441
 
        self.assertPathExists('q')
2442
 
        self.assertPathExists('r')
2443
 
        self.assertPathDoesNotExist('a')
2444
 
        self.assertPathDoesNotExist('b')
 
2241
        self.failUnlessExists('q')
 
2242
        self.failUnlessExists('r')
 
2243
        self.failIfExists('a')
 
2244
        self.failIfExists('b')
2445
2245
        mover.apply_deletions()
2446
 
        self.assertPathDoesNotExist('q')
2447
 
        self.assertPathDoesNotExist('r')
2448
 
        self.assertPathDoesNotExist('a')
2449
 
        self.assertPathDoesNotExist('b')
 
2246
        self.failIfExists('q')
 
2247
        self.failIfExists('r')
 
2248
        self.failIfExists('a')
 
2249
        self.failIfExists('b')
2450
2250
 
2451
2251
    def test_file_mover_rollback(self):
2452
2252
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2457
2257
            mover.rename('a', 'c')
2458
2258
        except errors.FileExists, e:
2459
2259
            mover.rollback()
2460
 
        self.assertPathExists('a')
2461
 
        self.assertPathExists('c/d')
 
2260
        self.failUnlessExists('a')
 
2261
        self.failUnlessExists('c/d')
2462
2262
 
2463
2263
 
2464
2264
class Bogus(Exception):
2494
2294
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2495
2295
        self.assertRaises(Bogus, tt.apply,
2496
2296
                          _mover=self.ExceptionFileMover(bad_source='a'))
2497
 
        self.assertPathExists('a')
2498
 
        self.assertPathExists('a/b')
 
2297
        self.failUnlessExists('a')
 
2298
        self.failUnlessExists('a/b')
2499
2299
        tt.apply()
2500
 
        self.assertPathExists('c')
2501
 
        self.assertPathExists('c/d')
 
2300
        self.failUnlessExists('c')
 
2301
        self.failUnlessExists('c/d')
2502
2302
 
2503
2303
    def test_rollback_rename_into_place(self):
2504
2304
        tree = self.make_branch_and_tree('.')
2510
2310
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2511
2311
        self.assertRaises(Bogus, tt.apply,
2512
2312
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2513
 
        self.assertPathExists('a')
2514
 
        self.assertPathExists('a/b')
 
2313
        self.failUnlessExists('a')
 
2314
        self.failUnlessExists('a/b')
2515
2315
        tt.apply()
2516
 
        self.assertPathExists('c')
2517
 
        self.assertPathExists('c/d')
 
2316
        self.failUnlessExists('c')
 
2317
        self.failUnlessExists('c/d')
2518
2318
 
2519
2319
    def test_rollback_deletion(self):
2520
2320
        tree = self.make_branch_and_tree('.')
2526
2326
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2527
2327
        self.assertRaises(Bogus, tt.apply,
2528
2328
                          _mover=self.ExceptionFileMover(bad_target='d'))
2529
 
        self.assertPathExists('a')
2530
 
        self.assertPathExists('a/b')
2531
 
 
2532
 
 
2533
 
class TestFinalizeRobustness(tests.TestCaseWithTransport):
2534
 
    """Ensure treetransform creation errors can be safely cleaned up after"""
2535
 
 
2536
 
    def _override_globals_in_method(self, instance, method_name, globals):
2537
 
        """Replace method on instance with one with updated globals"""
2538
 
        import types
2539
 
        func = getattr(instance, method_name).im_func
2540
 
        new_globals = dict(func.func_globals)
2541
 
        new_globals.update(globals)
2542
 
        new_func = types.FunctionType(func.func_code, new_globals,
2543
 
            func.func_name, func.func_defaults)
2544
 
        setattr(instance, method_name,
2545
 
            types.MethodType(new_func, instance, instance.__class__))
2546
 
        self.addCleanup(delattr, instance, method_name)
2547
 
 
2548
 
    @staticmethod
2549
 
    def _fake_open_raises_before(name, mode):
2550
 
        """Like open() but raises before doing anything"""
2551
 
        raise RuntimeError
2552
 
 
2553
 
    @staticmethod
2554
 
    def _fake_open_raises_after(name, mode):
2555
 
        """Like open() but raises after creating file without returning"""
2556
 
        open(name, mode).close()
2557
 
        raise RuntimeError
2558
 
 
2559
 
    def create_transform_and_root_trans_id(self):
2560
 
        """Setup a transform creating a file in limbo"""
2561
 
        tree = self.make_branch_and_tree('.')
2562
 
        tt = TreeTransform(tree)
2563
 
        return tt, tt.create_path("a", tt.root)
2564
 
 
2565
 
    def create_transform_and_subdir_trans_id(self):
2566
 
        """Setup a transform creating a directory containing a file in limbo"""
2567
 
        tree = self.make_branch_and_tree('.')
2568
 
        tt = TreeTransform(tree)
2569
 
        d_trans_id = tt.create_path("d", tt.root)
2570
 
        tt.create_directory(d_trans_id)
2571
 
        f_trans_id = tt.create_path("a", d_trans_id)
2572
 
        tt.adjust_path("a", d_trans_id, f_trans_id)
2573
 
        return tt, f_trans_id
2574
 
 
2575
 
    def test_root_create_file_open_raises_before_creation(self):
2576
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2577
 
        self._override_globals_in_method(tt, "create_file",
2578
 
            {"open": self._fake_open_raises_before})
2579
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2580
 
        path = tt._limbo_name(trans_id)
2581
 
        self.assertPathDoesNotExist(path)
2582
 
        tt.finalize()
2583
 
        self.assertPathDoesNotExist(tt._limbodir)
2584
 
 
2585
 
    def test_root_create_file_open_raises_after_creation(self):
2586
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2587
 
        self._override_globals_in_method(tt, "create_file",
2588
 
            {"open": self._fake_open_raises_after})
2589
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2590
 
        path = tt._limbo_name(trans_id)
2591
 
        self.assertPathExists(path)
2592
 
        tt.finalize()
2593
 
        self.assertPathDoesNotExist(path)
2594
 
        self.assertPathDoesNotExist(tt._limbodir)
2595
 
 
2596
 
    def test_subdir_create_file_open_raises_before_creation(self):
2597
 
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2598
 
        self._override_globals_in_method(tt, "create_file",
2599
 
            {"open": self._fake_open_raises_before})
2600
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2601
 
        path = tt._limbo_name(trans_id)
2602
 
        self.assertPathDoesNotExist(path)
2603
 
        tt.finalize()
2604
 
        self.assertPathDoesNotExist(tt._limbodir)
2605
 
 
2606
 
    def test_subdir_create_file_open_raises_after_creation(self):
2607
 
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2608
 
        self._override_globals_in_method(tt, "create_file",
2609
 
            {"open": self._fake_open_raises_after})
2610
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2611
 
        path = tt._limbo_name(trans_id)
2612
 
        self.assertPathExists(path)
2613
 
        tt.finalize()
2614
 
        self.assertPathDoesNotExist(path)
2615
 
        self.assertPathDoesNotExist(tt._limbodir)
2616
 
 
2617
 
    def test_rename_in_limbo_rename_raises_after_rename(self):
2618
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2619
 
        parent1 = tt.new_directory('parent1', tt.root)
2620
 
        child1 = tt.new_file('child1', parent1, 'contents')
2621
 
        parent2 = tt.new_directory('parent2', tt.root)
2622
 
 
2623
 
        class FakeOSModule(object):
2624
 
            def rename(self, old, new):
2625
 
                os.rename(old, new)
2626
 
                raise RuntimeError
2627
 
        self._override_globals_in_method(tt, "_rename_in_limbo",
2628
 
            {"os": FakeOSModule()})
2629
 
        self.assertRaises(
2630
 
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2631
 
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
2632
 
        self.assertPathExists(path)
2633
 
        tt.finalize()
2634
 
        self.assertPathDoesNotExist(path)
2635
 
        self.assertPathDoesNotExist(tt._limbodir)
2636
 
 
2637
 
    def test_rename_in_limbo_rename_raises_before_rename(self):
2638
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2639
 
        parent1 = tt.new_directory('parent1', tt.root)
2640
 
        child1 = tt.new_file('child1', parent1, 'contents')
2641
 
        parent2 = tt.new_directory('parent2', tt.root)
2642
 
 
2643
 
        class FakeOSModule(object):
2644
 
            def rename(self, old, new):
2645
 
                raise RuntimeError
2646
 
        self._override_globals_in_method(tt, "_rename_in_limbo",
2647
 
            {"os": FakeOSModule()})
2648
 
        self.assertRaises(
2649
 
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2650
 
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
2651
 
        self.assertPathExists(path)
2652
 
        tt.finalize()
2653
 
        self.assertPathDoesNotExist(path)
2654
 
        self.assertPathDoesNotExist(tt._limbodir)
2655
 
 
2656
 
 
2657
 
class TestTransformMissingParent(tests.TestCaseWithTransport):
2658
 
 
2659
 
    def make_tt_with_versioned_dir(self):
 
2329
        self.failUnlessExists('a')
 
2330
        self.failUnlessExists('a/b')
 
2331
 
 
2332
    def test_resolve_no_parent(self):
2660
2333
        wt = self.make_branch_and_tree('.')
2661
 
        self.build_tree(['dir/',])
2662
 
        wt.add(['dir'], ['dir-id'])
2663
 
        wt.commit('Create dir')
2664
2334
        tt = TreeTransform(wt)
2665
2335
        self.addCleanup(tt.finalize)
2666
 
        return wt, tt
2667
 
 
2668
 
    def test_resolve_create_parent_for_versioned_file(self):
2669
 
        wt, tt = self.make_tt_with_versioned_dir()
2670
 
        dir_tid = tt.trans_id_tree_file_id('dir-id')
2671
 
        file_tid = tt.new_file('file', dir_tid, 'Contents', file_id='file-id')
2672
 
        tt.delete_contents(dir_tid)
2673
 
        tt.unversion_file(dir_tid)
2674
 
        conflicts = resolve_conflicts(tt)
2675
 
        # one conflict for the missing directory, one for the unversioned
2676
 
        # parent
2677
 
        self.assertLength(2, conflicts)
2678
 
 
2679
 
    def test_non_versioned_file_create_conflict(self):
2680
 
        wt, tt = self.make_tt_with_versioned_dir()
2681
 
        dir_tid = tt.trans_id_tree_file_id('dir-id')
2682
 
        tt.new_file('file', dir_tid, 'Contents')
2683
 
        tt.delete_contents(dir_tid)
2684
 
        tt.unversion_file(dir_tid)
2685
 
        conflicts = resolve_conflicts(tt)
2686
 
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
2687
 
        self.assertLength(1, conflicts)
2688
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
2689
 
                         conflicts.pop())
 
2336
        parent = tt.trans_id_file_id('parent-id')
 
2337
        tt.new_file('file', parent, 'Contents')
 
2338
        resolve_conflicts(tt)
2690
2339
 
2691
2340
 
2692
2341
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2693
2342
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2694
2343
                  (False, False))
2695
2344
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2696
 
              ('', ''), ('directory', 'directory'), (False, False))
 
2345
              ('', ''), ('directory', 'directory'), (False, None))
2697
2346
 
2698
2347
 
2699
2348
class TestTransformPreview(tests.TestCaseWithTransport):
2768
2417
 
2769
2418
    def test_iter_changes(self):
2770
2419
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2771
 
        root = revision_tree.get_root_id()
 
2420
        root = revision_tree.inventory.root.file_id
2772
2421
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
2773
2422
                          (root, root), ('a', 'a'), ('file', 'file'),
2774
2423
                          (False, False))],
2778
2427
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2779
2428
        changes = preview_tree.iter_changes(revision_tree,
2780
2429
                                            include_unchanged=True)
2781
 
        root = revision_tree.get_root_id()
 
2430
        root = revision_tree.inventory.root.file_id
2782
2431
 
2783
2432
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2784
2433
 
2786
2435
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2787
2436
        changes = preview_tree.iter_changes(revision_tree,
2788
2437
                                            specific_files=[''])
2789
 
        self.assertEqual([A_ENTRY], list(changes))
 
2438
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2790
2439
 
2791
2440
    def test_want_unversioned(self):
2792
2441
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2793
2442
        changes = preview_tree.iter_changes(revision_tree,
2794
2443
                                            want_unversioned=True)
2795
 
        self.assertEqual([A_ENTRY], list(changes))
 
2444
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2796
2445
 
2797
2446
    def test_ignore_extra_trees_no_specific_files(self):
2798
2447
        # extra_trees is harmless without specific_files, so we'll silently
2841
2490
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2842
2491
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2843
2492
 
2844
 
    def test_get_file_size(self):
2845
 
        work_tree = self.make_branch_and_tree('tree')
2846
 
        self.build_tree_contents([('tree/old', 'old')])
2847
 
        work_tree.add('old', 'old-id')
2848
 
        preview = TransformPreview(work_tree)
2849
 
        self.addCleanup(preview.finalize)
2850
 
        new_id = preview.new_file('name', preview.root, 'contents', 'new-id',
2851
 
                                  'executable')
2852
 
        tree = preview.get_preview_tree()
2853
 
        self.assertEqual(len('old'), tree.get_file_size('old-id'))
2854
 
        self.assertEqual(len('contents'), tree.get_file_size('new-id'))
2855
 
 
2856
2493
    def test_get_file(self):
2857
2494
        preview = self.get_empty_preview()
2858
2495
        preview.new_file('file', preview.root, 'contents', 'file-id')
3270
2907
        merger.merge_type = Merge3Merger
3271
2908
        merger.do_merge()
3272
2909
 
3273
 
    def test_has_filename(self):
3274
 
        wt = self.make_branch_and_tree('tree')
3275
 
        self.build_tree(['tree/unmodified', 'tree/removed', 'tree/modified'])
3276
 
        tt = TransformPreview(wt)
3277
 
        removed_id = tt.trans_id_tree_path('removed')
3278
 
        tt.delete_contents(removed_id)
3279
 
        tt.new_file('new', tt.root, 'contents')
3280
 
        modified_id = tt.trans_id_tree_path('modified')
3281
 
        tt.delete_contents(modified_id)
3282
 
        tt.create_file('modified-contents', modified_id)
3283
 
        self.addCleanup(tt.finalize)
3284
 
        tree = tt.get_preview_tree()
3285
 
        self.assertTrue(tree.has_filename('unmodified'))
3286
 
        self.assertFalse(tree.has_filename('not-present'))
3287
 
        self.assertFalse(tree.has_filename('removed'))
3288
 
        self.assertTrue(tree.has_filename('new'))
3289
 
        self.assertTrue(tree.has_filename('modified'))
3290
 
 
3291
2910
    def test_is_executable(self):
3292
2911
        tree = self.make_branch_and_tree('tree')
3293
2912
        preview = TransformPreview(tree)
3316
2935
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
3317
2936
 
3318
2937
    def test_ascii_limbo_paths(self):
3319
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
2938
        self.requireFeature(tests.UnicodeFilenameFeature)
3320
2939
        branch = self.make_branch('any')
3321
2940
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
3322
2941
        tt = TransformPreview(tree)
3339
2958
 
3340
2959
class TestSerializeTransform(tests.TestCaseWithTransport):
3341
2960
 
3342
 
    _test_needs_features = [features.UnicodeFilenameFeature]
 
2961
    _test_needs_features = [tests.UnicodeFilenameFeature]
3343
2962
 
3344
2963
    def get_preview(self, tree=None):
3345
2964
        if tree is None:
3420
3039
        return self.make_records(attribs, contents)
3421
3040
 
3422
3041
    def test_serialize_symlink_creation(self):
3423
 
        self.requireFeature(features.SymlinkFeature)
 
3042
        self.requireFeature(tests.SymlinkFeature)
3424
3043
        tt = self.get_preview()
3425
3044
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3426
3045
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3427
3046
 
3428
3047
    def test_deserialize_symlink_creation(self):
3429
 
        self.requireFeature(features.SymlinkFeature)
 
3048
        self.requireFeature(tests.SymlinkFeature)
3430
3049
        tt = self.get_preview()
3431
3050
        tt.deserialize(iter(self.symlink_creation_records()))
3432
3051
        abspath = tt._limbo_name('new-1')
3599
3218
        trans_id = tt.trans_id_tree_path('file')
3600
3219
        self.assertEqual((LINES_ONE,),
3601
3220
            tt._get_parents_texts(trans_id))
3602
 
 
3603
 
 
3604
 
class TestOrphan(tests.TestCaseWithTransport):
3605
 
 
3606
 
    def test_no_orphan_for_transform_preview(self):
3607
 
        tree = self.make_branch_and_tree('tree')
3608
 
        tt = transform.TransformPreview(tree)
3609
 
        self.addCleanup(tt.finalize)
3610
 
        self.assertRaises(NotImplementedError, tt.new_orphan, 'foo', 'bar')
3611
 
 
3612
 
    def _set_orphan_policy(self, wt, policy):
3613
 
        wt.branch.get_config_stack().set('bzr.transform.orphan_policy',
3614
 
                                               policy)
3615
 
 
3616
 
    def _prepare_orphan(self, wt):
3617
 
        self.build_tree(['dir/', 'dir/file', 'dir/foo'])
3618
 
        wt.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
3619
 
        wt.commit('add dir and file ignoring foo')
3620
 
        tt = transform.TreeTransform(wt)
3621
 
        self.addCleanup(tt.finalize)
3622
 
        # dir and bar are deleted
3623
 
        dir_tid = tt.trans_id_tree_path('dir')
3624
 
        file_tid = tt.trans_id_tree_path('dir/file')
3625
 
        orphan_tid = tt.trans_id_tree_path('dir/foo')
3626
 
        tt.delete_contents(file_tid)
3627
 
        tt.unversion_file(file_tid)
3628
 
        tt.delete_contents(dir_tid)
3629
 
        tt.unversion_file(dir_tid)
3630
 
        # There should be a conflict because dir still contain foo
3631
 
        raw_conflicts = tt.find_conflicts()
3632
 
        self.assertLength(1, raw_conflicts)
3633
 
        self.assertEqual(('missing parent', 'new-1'), raw_conflicts[0])
3634
 
        return tt, orphan_tid
3635
 
 
3636
 
    def test_new_orphan_created(self):
3637
 
        wt = self.make_branch_and_tree('.')
3638
 
        self._set_orphan_policy(wt, 'move')
3639
 
        tt, orphan_tid = self._prepare_orphan(wt)
3640
 
        warnings = []
3641
 
        def warning(*args):
3642
 
            warnings.append(args[0] % args[1:])
3643
 
        self.overrideAttr(trace, 'warning', warning)
3644
 
        remaining_conflicts = resolve_conflicts(tt)
3645
 
        self.assertEquals(['dir/foo has been orphaned in bzr-orphans'],
3646
 
                          warnings)
3647
 
        # Yeah for resolved conflicts !
3648
 
        self.assertLength(0, remaining_conflicts)
3649
 
        # We have a new orphan
3650
 
        self.assertEquals('foo.~1~', tt.final_name(orphan_tid))
3651
 
        self.assertEquals('bzr-orphans',
3652
 
                          tt.final_name(tt.final_parent(orphan_tid)))
3653
 
 
3654
 
    def test_never_orphan(self):
3655
 
        wt = self.make_branch_and_tree('.')
3656
 
        self._set_orphan_policy(wt, 'conflict')
3657
 
        tt, orphan_tid = self._prepare_orphan(wt)
3658
 
        remaining_conflicts = resolve_conflicts(tt)
3659
 
        self.assertLength(1, remaining_conflicts)
3660
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3661
 
                         remaining_conflicts.pop())
3662
 
 
3663
 
    def test_orphan_error(self):
3664
 
        def bogus_orphan(tt, orphan_id, parent_id):
3665
 
            raise transform.OrphaningError(tt.final_name(orphan_id),
3666
 
                                           tt.final_name(parent_id))
3667
 
        transform.orphaning_registry.register('bogus', bogus_orphan,
3668
 
                                              'Raise an error when orphaning')
3669
 
        wt = self.make_branch_and_tree('.')
3670
 
        self._set_orphan_policy(wt, 'bogus')
3671
 
        tt, orphan_tid = self._prepare_orphan(wt)
3672
 
        remaining_conflicts = resolve_conflicts(tt)
3673
 
        self.assertLength(1, remaining_conflicts)
3674
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3675
 
                         remaining_conflicts.pop())
3676
 
 
3677
 
    def test_unknown_orphan_policy(self):
3678
 
        wt = self.make_branch_and_tree('.')
3679
 
        # Set a fictional policy nobody ever implemented
3680
 
        self._set_orphan_policy(wt, 'donttouchmypreciouuus')
3681
 
        tt, orphan_tid = self._prepare_orphan(wt)
3682
 
        warnings = []
3683
 
        def warning(*args):
3684
 
            warnings.append(args[0] % args[1:])
3685
 
        self.overrideAttr(trace, 'warning', warning)
3686
 
        remaining_conflicts = resolve_conflicts(tt)
3687
 
        # We fallback to the default policy which create a conflict
3688
 
        self.assertLength(1, remaining_conflicts)
3689
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3690
 
                         remaining_conflicts.pop())
3691
 
        self.assertLength(1, warnings)
3692
 
        self.assertStartsWith(warnings[0], 'Value "donttouchmypreciouuus" ')
3693
 
 
3694
 
 
3695
 
class TestTransformHooks(tests.TestCaseWithTransport):
3696
 
 
3697
 
    def setUp(self):
3698
 
        super(TestTransformHooks, self).setUp()
3699
 
        self.wt = self.make_branch_and_tree('.')
3700
 
        os.chdir('..')
3701
 
 
3702
 
    def get_transform(self):
3703
 
        transform = TreeTransform(self.wt)
3704
 
        self.addCleanup(transform.finalize)
3705
 
        return transform, transform.root
3706
 
 
3707
 
    def test_pre_commit_hooks(self):
3708
 
        calls = []
3709
 
        def record_pre_transform(tree, tt):
3710
 
            calls.append((tree, tt))
3711
 
        MutableTree.hooks.install_named_hook('pre_transform',
3712
 
            record_pre_transform, "Pre transform")
3713
 
        transform, root = self.get_transform()
3714
 
        old_root_id = transform.tree_file_id(root)
3715
 
        transform.apply()
3716
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
3717
 
        self.assertEquals([(self.wt, transform)], calls)
3718
 
 
3719
 
    def test_post_commit_hooks(self):
3720
 
        calls = []
3721
 
        def record_post_transform(tree, tt):
3722
 
            calls.append((tree, tt))
3723
 
        MutableTree.hooks.install_named_hook('post_transform',
3724
 
            record_post_transform, "Post transform")
3725
 
        transform, root = self.get_transform()
3726
 
        old_root_id = transform.tree_file_id(root)
3727
 
        transform.apply()
3728
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
3729
 
        self.assertEquals([(self.wt, transform)], calls)