~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

  • Committer: Patch Queue Manager
  • Date: 2013-05-20 17:46:29 UTC
  • mfrom: (6573.1.1 bzr)
  • Revision ID: pqm@pqm.ubuntu.com-20130520174629-dp7zujtuclvomuzd
(jameinel) Fix CVE 2013-2009. Avoid allowing multiple wildcards in a single
 SSL cert hostname segment. (Andrew Starr-Bochicchio)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 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
17
18
import os
18
19
from StringIO import StringIO
19
20
import sys
27
28
    osutils,
28
29
    revision as _mod_revision,
29
30
    rules,
 
31
    symbol_versioning,
30
32
    tests,
 
33
    trace,
 
34
    transform,
31
35
    urlutils,
32
36
    )
33
 
from bzrlib.bzrdir import BzrDir
34
37
from bzrlib.conflicts import (
35
38
    DeletingParent,
36
39
    DuplicateEntry,
40
43
    ParentLoop,
41
44
    UnversionedParent,
42
45
)
 
46
from bzrlib.controldir import ControlDir
43
47
from bzrlib.diff import show_diff_trees
44
48
from bzrlib.errors import (
45
49
    DuplicateKey,
49
53
    ImmortalPendingDeletion,
50
54
    LockError,
51
55
    MalformedTransform,
52
 
    NoSuchFile,
53
56
    ReusingTransform,
54
57
)
55
58
from bzrlib.osutils import (
57
60
    pathjoin,
58
61
)
59
62
from bzrlib.merge import Merge3Merger, Merger
 
63
from bzrlib.mutabletree import MutableTree
60
64
from bzrlib.tests import (
 
65
    features,
 
66
    TestCaseInTempDir,
 
67
    TestSkipped,
 
68
    )
 
69
from bzrlib.tests.features import (
61
70
    HardlinkFeature,
62
71
    SymlinkFeature,
63
 
    TestCase,
64
 
    TestCaseInTempDir,
65
 
    TestSkipped,
66
 
)
 
72
    )
67
73
from bzrlib.transform import (
68
74
    build_tree,
69
75
    create_from_tree,
70
76
    cook_conflicts,
71
77
    _FileMover,
72
78
    FinalPaths,
73
 
    get_backup_name,
74
79
    resolve_conflicts,
75
80
    resolve_checkout,
76
81
    ROOT_PARENT,
83
88
 
84
89
    def setUp(self):
85
90
        super(TestTreeTransform, self).setUp()
86
 
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
 
91
        self.wt = self.make_branch_and_tree('.', format='development-subtree')
87
92
        os.chdir('..')
88
93
 
89
94
    def get_transform(self):
91
96
        self.addCleanup(transform.finalize)
92
97
        return transform, transform.root
93
98
 
 
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
 
94
109
    def test_existing_limbo(self):
95
110
        transform, root = self.get_transform()
96
111
        limbo_name = transform._limbodir
159
174
        transform.finalize()
160
175
        transform.finalize()
161
176
 
 
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
 
162
238
    def test_create_files_same_timestamp(self):
163
239
        transform, root = self.get_transform()
164
240
        self.wt.lock_tree_write()
212
288
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
213
289
        self.assertRaises(ValueError, transform.fixup_new_roots)
214
290
 
 
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
 
215
353
    def test_hardlink(self):
216
354
        self.requireFeature(HardlinkFeature)
217
355
        transform, root = self.get_transform()
222
360
        trans_id = target_transform.create_path('file1', target_transform.root)
223
361
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
224
362
        target_transform.apply()
225
 
        self.failUnlessExists('target/file1')
 
363
        self.assertPathExists('target/file1')
226
364
        source_stat = os.stat(self.wt.abspath('file1'))
227
365
        target_stat = os.stat('target/file1')
228
366
        self.assertEqual(source_stat, target_stat)
261
399
        tree.lock_read()
262
400
        self.addCleanup(tree.unlock)
263
401
        self.assertEqual('subtree-revision',
264
 
                         tree.inventory['subtree-id'].reference_revision)
 
402
                         tree.root_inventory['subtree-id'].reference_revision)
265
403
 
266
404
    def test_conflicts(self):
267
405
        transform, root = self.get_transform()
394
532
        transform.new_file('FiLe', transform.root, 'content')
395
533
        resolve_conflicts(transform)
396
534
        transform.apply()
397
 
        self.failUnlessExists('tree/file')
398
 
        self.failUnlessExists('tree/FiLe.moved')
 
535
        self.assertPathExists('tree/file')
 
536
        self.assertPathExists('tree/FiLe.moved')
399
537
 
400
538
    def test_resolve_checkout_case_conflict(self):
401
539
        tree = self.make_branch_and_tree('tree')
410
548
        resolve_conflicts(transform,
411
549
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
412
550
        transform.apply()
413
 
        self.failUnlessExists('tree/file')
414
 
        self.failUnlessExists('tree/FiLe.moved')
 
551
        self.assertPathExists('tree/file')
 
552
        self.assertPathExists('tree/FiLe.moved')
415
553
 
416
554
    def test_apply_case_conflict(self):
417
555
        """Ensure that a transform with case conflicts can always be applied"""
425
563
        transform.new_file('dirFiLe', dir, 'content')
426
564
        resolve_conflicts(transform)
427
565
        transform.apply()
428
 
        self.failUnlessExists('tree/file')
 
566
        self.assertPathExists('tree/file')
429
567
        if not os.path.exists('tree/FiLe.moved'):
430
 
            self.failUnlessExists('tree/FiLe')
431
 
        self.failUnlessExists('tree/dir/dirfile')
 
568
            self.assertPathExists('tree/FiLe')
 
569
        self.assertPathExists('tree/dir/dirfile')
432
570
        if not os.path.exists('tree/dir/dirFiLe.moved'):
433
 
            self.failUnlessExists('tree/dir/dirFiLe')
 
571
            self.assertPathExists('tree/dir/dirFiLe')
434
572
 
435
573
    def test_case_insensitive_limbo(self):
436
574
        tree = self.make_branch_and_tree('tree')
644
782
                            'wizard2', 'behind_curtain')
645
783
 
646
784
    def test_symlinks_unicode(self):
647
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
785
        self.requireFeature(features.UnicodeFilenameFeature)
648
786
        self._test_symlinks(u'\N{Euro Sign}wizard',
649
787
                            u'wizard-targ\N{Euro Sign}t',
650
788
                            u'\N{Euro Sign}wizard2',
738
876
        raw_conflicts = resolve_conflicts(tt)
739
877
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
740
878
        tt.finalize()
741
 
        conflicts_s = [str(c) for c in cooked_conflicts]
 
879
        conflicts_s = [unicode(c) for c in cooked_conflicts]
742
880
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
743
881
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
744
882
                                         'Moved existing file to '
814
952
        self.assertIs(None, self.wt.path2id('parent'))
815
953
        self.assertIs(None, self.wt.path2id('parent.new'))
816
954
 
 
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
 
817
970
    def test_moving_versioned_directories(self):
818
971
        create, root = self.get_transform()
819
972
        kansas = create.new_directory('kansas', root, 'kansas-id')
853
1006
        rename.apply()
854
1007
 
855
1008
    def test_rename_fails(self):
 
1009
        self.requireFeature(features.not_running_as_root)
856
1010
        # see https://bugs.launchpad.net/bzr/+bug/491763
857
1011
        create, root_id = self.get_transform()
858
1012
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
880
1034
        # On windows looks like:
881
1035
        # "Failed to rename .../work/myfile to 
882
1036
        # .../work/.bzr/checkout/limbo/new-1: [Errno 13] Permission denied"
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)")
 
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")
886
1045
 
887
1046
    def test_set_executability_order(self):
888
1047
        """Ensure that executability behaves the same, no matter what order.
1161
1320
        parent2 = transform.new_directory('parent2', root)
1162
1321
        transform.adjust_path('child1', parent2, child1)
1163
1322
        transform.apply()
1164
 
        self.failIfExists(self.wt.abspath('parent1/child1'))
1165
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1323
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
 
1324
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1166
1325
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1167
1326
        # no rename for child1 (counting only renames during apply)
1168
 
        self.failUnlessEqual(2, transform.rename_count)
 
1327
        self.assertEqual(2, transform.rename_count)
1169
1328
 
1170
1329
    def test_cancel_parent(self):
1171
1330
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1194
1353
        parent2 = transform.new_directory('parent2', root)
1195
1354
        transform.adjust_path('child1', parent2, child1)
1196
1355
        transform.apply()
1197
 
        self.failIfExists(self.wt.abspath('parent1'))
1198
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1356
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
 
1357
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1199
1358
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1200
 
        self.failUnlessEqual(2, transform.rename_count)
 
1359
        self.assertEqual(2, transform.rename_count)
1201
1360
 
1202
1361
    def test_adjust_and_cancel(self):
1203
1362
        """Make sure adjust_path keeps track of limbo children properly"""
1236
1395
        child = transform.new_directory('child', parent)
1237
1396
        transform.adjust_path('parent', root, parent)
1238
1397
        transform.apply()
1239
 
        self.failUnlessExists(self.wt.abspath('parent/child'))
 
1398
        self.assertPathExists(self.wt.abspath('parent/child'))
1240
1399
        self.assertEqual(1, transform.rename_count)
1241
1400
 
1242
1401
    def test_reuse_name(self):
1318
1477
        # The rename will fail because the target directory is not empty (but
1319
1478
        # raises FileExists anyway).
1320
1479
        err = self.assertRaises(errors.FileExists, tt_helper)
1321
 
        self.assertContainsRe(str(err),
1322
 
            "^File exists: .+/baz")
 
1480
        self.assertEndsWith(err.path, "/baz")
1323
1481
 
1324
1482
    def test_two_directories_clash(self):
1325
1483
        def tt_helper():
1337
1495
                wt.unlock()
1338
1496
                raise
1339
1497
        err = self.assertRaises(errors.FileExists, tt_helper)
1340
 
        self.assertContainsRe(str(err),
1341
 
            "^File exists: .+/foo")
 
1498
        self.assertEndsWith(err.path, "/foo")
1342
1499
 
1343
1500
    def test_two_directories_clash_finalize(self):
1344
1501
        def tt_helper():
1356
1513
                tt.finalize()
1357
1514
                raise
1358
1515
        err = self.assertRaises(errors.FileExists, tt_helper)
1359
 
        self.assertContainsRe(str(err),
1360
 
            "^File exists: .+/foo")
 
1516
        self.assertEndsWith(err.path, "/foo")
1361
1517
 
1362
1518
    def test_file_to_directory(self):
1363
1519
        wt = self.make_branch_and_tree('.')
1373
1529
        tt.create_file(["aa\n"], bar_trans_id)
1374
1530
        tt.version_file("bar-1", bar_trans_id)
1375
1531
        tt.apply()
1376
 
        self.failUnlessExists("foo/bar")
 
1532
        self.assertPathExists("foo/bar")
1377
1533
        wt.lock_read()
1378
1534
        try:
1379
 
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1380
 
                    "directory")
 
1535
            self.assertEqual(wt.kind(wt.path2id("foo")), "directory")
1381
1536
        finally:
1382
1537
            wt.unlock()
1383
1538
        wt.commit("two")
1396
1551
        tt.delete_contents(foo_trans_id)
1397
1552
        tt.create_symlink("bar", foo_trans_id)
1398
1553
        tt.apply()
1399
 
        self.failUnlessExists("foo")
 
1554
        self.assertPathExists("foo")
1400
1555
        wt.lock_read()
1401
1556
        self.addCleanup(wt.unlock)
1402
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1403
 
                "symlink")
 
1557
        self.assertEqual(wt.kind(wt.path2id("foo")), "symlink")
1404
1558
 
1405
1559
    def test_dir_to_file(self):
1406
1560
        wt = self.make_branch_and_tree('.')
1415
1569
        tt.delete_versioned(bar_trans_id)
1416
1570
        tt.create_file(["aa\n"], foo_trans_id)
1417
1571
        tt.apply()
1418
 
        self.failUnlessExists("foo")
 
1572
        self.assertPathExists("foo")
1419
1573
        wt.lock_read()
1420
1574
        self.addCleanup(wt.unlock)
1421
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1422
 
                "file")
 
1575
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
1423
1576
 
1424
1577
    def test_dir_to_hardlink(self):
1425
1578
        self.requireFeature(HardlinkFeature)
1436
1589
        self.build_tree(['baz'])
1437
1590
        tt.create_hardlink("baz", foo_trans_id)
1438
1591
        tt.apply()
1439
 
        self.failUnlessExists("foo")
1440
 
        self.failUnlessExists("baz")
 
1592
        self.assertPathExists("foo")
 
1593
        self.assertPathExists("baz")
1441
1594
        wt.lock_read()
1442
1595
        self.addCleanup(wt.unlock)
1443
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1444
 
                "file")
 
1596
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
1445
1597
 
1446
1598
    def test_no_final_path(self):
1447
1599
        transform, root = self.get_transform()
1493
1645
    def __init__(self, dirname, root_id):
1494
1646
        self.name = dirname
1495
1647
        os.mkdir(dirname)
1496
 
        self.wt = BzrDir.create_standalone_workingtree(dirname)
 
1648
        self.wt = ControlDir.create_standalone_workingtree(dirname)
1497
1649
        self.wt.set_root_id(root_id)
1498
1650
        self.b = self.wt.branch
1499
1651
        self.tt = TreeTransform(self.wt)
1505
1657
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1506
1658
 
1507
1659
 
 
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
 
1508
1692
class TestTransformMerge(TestCaseInTempDir):
1509
1693
 
1510
1694
    def test_text_merge(self):
1577
1761
        merge_modified = this.wt.merge_modified()
1578
1762
        self.assertSubset(merge_modified, modified)
1579
1763
        self.assertEqual(len(merge_modified), len(modified))
1580
 
        file(this.wt.id2abspath('a'), 'wb').write('booga')
 
1764
        with file(this.wt.id2abspath('a'), 'wb') as f: f.write('booga')
1581
1765
        modified.pop(0)
1582
1766
        merge_modified = this.wt.merge_modified()
1583
1767
        self.assertSubset(merge_modified, modified)
1697
1881
    def test_build_tree_with_symlinks(self):
1698
1882
        self.requireFeature(SymlinkFeature)
1699
1883
        os.mkdir('a')
1700
 
        a = BzrDir.create_standalone_workingtree('a')
 
1884
        a = ControlDir.create_standalone_workingtree('a')
1701
1885
        os.mkdir('a/foo')
1702
 
        file('a/foo/bar', 'wb').write('contents')
 
1886
        with file('a/foo/bar', 'wb') as f: f.write('contents')
1703
1887
        os.symlink('a/foo/bar', 'a/foo/baz')
1704
1888
        a.add(['foo', 'foo/bar', 'foo/baz'])
1705
1889
        a.commit('initial commit')
1706
 
        b = BzrDir.create_standalone_workingtree('b')
 
1890
        b = ControlDir.create_standalone_workingtree('b')
1707
1891
        basis = a.basis_tree()
1708
1892
        basis.lock_read()
1709
1893
        self.addCleanup(basis.unlock)
1714
1898
 
1715
1899
    def test_build_with_references(self):
1716
1900
        tree = self.make_branch_and_tree('source',
1717
 
            format='dirstate-with-subtree')
 
1901
            format='development-subtree')
1718
1902
        subtree = self.make_branch_and_tree('source/subtree',
1719
 
            format='dirstate-with-subtree')
 
1903
            format='development-subtree')
1720
1904
        tree.add_reference(subtree)
1721
1905
        tree.commit('a revision')
1722
1906
        tree.branch.create_checkout('target')
1723
 
        self.failUnlessExists('target')
1724
 
        self.failUnlessExists('target/subtree')
 
1907
        self.assertPathExists('target')
 
1908
        self.assertPathExists('target/subtree')
1725
1909
 
1726
1910
    def test_file_conflict_handling(self):
1727
1911
        """Ensure that when building trees, conflict handling is done"""
1774
1958
        source.commit('added file')
1775
1959
        build_tree(source.basis_tree(), target)
1776
1960
        self.assertEqual([], target.conflicts())
1777
 
        self.failUnlessExists('target/dir1/file')
 
1961
        self.assertPathExists('target/dir1/file')
1778
1962
 
1779
1963
        # Ensure contents are merged
1780
1964
        target = self.make_branch_and_tree('target2')
1781
1965
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1782
1966
        build_tree(source.basis_tree(), target)
1783
1967
        self.assertEqual([], target.conflicts())
1784
 
        self.failUnlessExists('target2/dir1/file2')
1785
 
        self.failUnlessExists('target2/dir1/file')
 
1968
        self.assertPathExists('target2/dir1/file2')
 
1969
        self.assertPathExists('target2/dir1/file')
1786
1970
 
1787
1971
        # Ensure new contents are suppressed for existing branches
1788
1972
        target = self.make_branch_and_tree('target3')
1789
1973
        self.make_branch('target3/dir1')
1790
1974
        self.build_tree(['target3/dir1/file2'])
1791
1975
        build_tree(source.basis_tree(), target)
1792
 
        self.failIfExists('target3/dir1/file')
1793
 
        self.failUnlessExists('target3/dir1/file2')
1794
 
        self.failUnlessExists('target3/dir1.diverted/file')
 
1976
        self.assertPathDoesNotExist('target3/dir1/file')
 
1977
        self.assertPathExists('target3/dir1/file2')
 
1978
        self.assertPathExists('target3/dir1.diverted/file')
1795
1979
        self.assertEqual([DuplicateEntry('Diverted to',
1796
1980
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1797
1981
            target.conflicts())
1800
1984
        self.build_tree(['target4/dir1/'])
1801
1985
        self.make_branch('target4/dir1/file')
1802
1986
        build_tree(source.basis_tree(), target)
1803
 
        self.failUnlessExists('target4/dir1/file')
 
1987
        self.assertPathExists('target4/dir1/file')
1804
1988
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1805
 
        self.failUnlessExists('target4/dir1/file.diverted')
 
1989
        self.assertPathExists('target4/dir1/file.diverted')
1806
1990
        self.assertEqual([DuplicateEntry('Diverted to',
1807
1991
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1808
1992
            target.conflicts())
1876
2060
        self.addCleanup(target.unlock)
1877
2061
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1878
2062
 
 
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
 
1879
2075
    def test_build_tree_accelerator_tree_missing_file(self):
1880
2076
        source = self.create_ab_tree()
1881
2077
        os.unlink('source/file1')
1988
2184
        def rot13(chunks, context=None):
1989
2185
            return [''.join(chunks).encode('rot13')]
1990
2186
        rot13filter = filters.ContentFilter(rot13, rot13)
1991
 
        filters.register_filter_stack_map('rot13', {'yes': [rot13filter]}.get)
 
2187
        filters.filter_stacks_registry.register(
 
2188
            'rot13', {'yes': [rot13filter]}.get)
1992
2189
        os.mkdir(self.test_home_dir + '/.bazaar')
1993
2190
        rules_filename = self.test_home_dir + '/.bazaar/rules'
1994
2191
        f = open(rules_filename, 'wb')
2024
2221
        self.assertEqualStat(source_stat, target_stat)
2025
2222
 
2026
2223
    def test_case_insensitive_build_tree_inventory(self):
2027
 
        if (tests.CaseInsensitiveFilesystemFeature.available()
2028
 
            or tests.CaseInsCasePresFilenameFeature.available()):
 
2224
        if (features.CaseInsensitiveFilesystemFeature.available()
 
2225
            or features.CaseInsCasePresFilenameFeature.available()):
2029
2226
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
2030
2227
        source = self.make_branch_and_tree('source')
2031
2228
        self.build_tree(['source/file', 'source/FILE'])
2039
2236
        self.assertEqual('file.moved', target.id2path('lower-id'))
2040
2237
        self.assertEqual('FILE', target.id2path('upper-id'))
2041
2238
 
 
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
 
2042
2275
 
2043
2276
class TestCommitTransform(tests.TestCaseWithTransport):
2044
2277
 
2178
2411
        self.assertEqual('tree', revision.properties['branch-nick'])
2179
2412
 
2180
2413
 
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
 
 
2214
2414
class TestFileMover(tests.TestCaseWithTransport):
2215
2415
 
2216
2416
    def test_file_mover(self):
2217
2417
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2218
2418
        mover = _FileMover()
2219
2419
        mover.rename('a', 'q')
2220
 
        self.failUnlessExists('q')
2221
 
        self.failIfExists('a')
2222
 
        self.failUnlessExists('q/b')
2223
 
        self.failUnlessExists('c')
2224
 
        self.failUnlessExists('c/d')
 
2420
        self.assertPathExists('q')
 
2421
        self.assertPathDoesNotExist('a')
 
2422
        self.assertPathExists('q/b')
 
2423
        self.assertPathExists('c')
 
2424
        self.assertPathExists('c/d')
2225
2425
 
2226
2426
    def test_pre_delete_rollback(self):
2227
2427
        self.build_tree(['a/'])
2228
2428
        mover = _FileMover()
2229
2429
        mover.pre_delete('a', 'q')
2230
 
        self.failUnlessExists('q')
2231
 
        self.failIfExists('a')
 
2430
        self.assertPathExists('q')
 
2431
        self.assertPathDoesNotExist('a')
2232
2432
        mover.rollback()
2233
 
        self.failIfExists('q')
2234
 
        self.failUnlessExists('a')
 
2433
        self.assertPathDoesNotExist('q')
 
2434
        self.assertPathExists('a')
2235
2435
 
2236
2436
    def test_apply_deletions(self):
2237
2437
        self.build_tree(['a/', 'b/'])
2238
2438
        mover = _FileMover()
2239
2439
        mover.pre_delete('a', 'q')
2240
2440
        mover.pre_delete('b', 'r')
2241
 
        self.failUnlessExists('q')
2242
 
        self.failUnlessExists('r')
2243
 
        self.failIfExists('a')
2244
 
        self.failIfExists('b')
 
2441
        self.assertPathExists('q')
 
2442
        self.assertPathExists('r')
 
2443
        self.assertPathDoesNotExist('a')
 
2444
        self.assertPathDoesNotExist('b')
2245
2445
        mover.apply_deletions()
2246
 
        self.failIfExists('q')
2247
 
        self.failIfExists('r')
2248
 
        self.failIfExists('a')
2249
 
        self.failIfExists('b')
 
2446
        self.assertPathDoesNotExist('q')
 
2447
        self.assertPathDoesNotExist('r')
 
2448
        self.assertPathDoesNotExist('a')
 
2449
        self.assertPathDoesNotExist('b')
2250
2450
 
2251
2451
    def test_file_mover_rollback(self):
2252
2452
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2257
2457
            mover.rename('a', 'c')
2258
2458
        except errors.FileExists, e:
2259
2459
            mover.rollback()
2260
 
        self.failUnlessExists('a')
2261
 
        self.failUnlessExists('c/d')
 
2460
        self.assertPathExists('a')
 
2461
        self.assertPathExists('c/d')
2262
2462
 
2263
2463
 
2264
2464
class Bogus(Exception):
2294
2494
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2295
2495
        self.assertRaises(Bogus, tt.apply,
2296
2496
                          _mover=self.ExceptionFileMover(bad_source='a'))
2297
 
        self.failUnlessExists('a')
2298
 
        self.failUnlessExists('a/b')
 
2497
        self.assertPathExists('a')
 
2498
        self.assertPathExists('a/b')
2299
2499
        tt.apply()
2300
 
        self.failUnlessExists('c')
2301
 
        self.failUnlessExists('c/d')
 
2500
        self.assertPathExists('c')
 
2501
        self.assertPathExists('c/d')
2302
2502
 
2303
2503
    def test_rollback_rename_into_place(self):
2304
2504
        tree = self.make_branch_and_tree('.')
2310
2510
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2311
2511
        self.assertRaises(Bogus, tt.apply,
2312
2512
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2313
 
        self.failUnlessExists('a')
2314
 
        self.failUnlessExists('a/b')
 
2513
        self.assertPathExists('a')
 
2514
        self.assertPathExists('a/b')
2315
2515
        tt.apply()
2316
 
        self.failUnlessExists('c')
2317
 
        self.failUnlessExists('c/d')
 
2516
        self.assertPathExists('c')
 
2517
        self.assertPathExists('c/d')
2318
2518
 
2319
2519
    def test_rollback_deletion(self):
2320
2520
        tree = self.make_branch_and_tree('.')
2326
2526
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2327
2527
        self.assertRaises(Bogus, tt.apply,
2328
2528
                          _mover=self.ExceptionFileMover(bad_target='d'))
2329
 
        self.failUnlessExists('a')
2330
 
        self.failUnlessExists('a/b')
2331
 
 
2332
 
    def test_resolve_no_parent(self):
 
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):
2333
2660
        wt = self.make_branch_and_tree('.')
 
2661
        self.build_tree(['dir/',])
 
2662
        wt.add(['dir'], ['dir-id'])
 
2663
        wt.commit('Create dir')
2334
2664
        tt = TreeTransform(wt)
2335
2665
        self.addCleanup(tt.finalize)
2336
 
        parent = tt.trans_id_file_id('parent-id')
2337
 
        tt.new_file('file', parent, 'Contents')
2338
 
        resolve_conflicts(tt)
 
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())
2339
2690
 
2340
2691
 
2341
2692
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2342
2693
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2343
2694
                  (False, False))
2344
2695
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2345
 
              ('', ''), ('directory', 'directory'), (False, None))
 
2696
              ('', ''), ('directory', 'directory'), (False, False))
2346
2697
 
2347
2698
 
2348
2699
class TestTransformPreview(tests.TestCaseWithTransport):
2417
2768
 
2418
2769
    def test_iter_changes(self):
2419
2770
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2420
 
        root = revision_tree.inventory.root.file_id
 
2771
        root = revision_tree.get_root_id()
2421
2772
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
2422
2773
                          (root, root), ('a', 'a'), ('file', 'file'),
2423
2774
                          (False, False))],
2427
2778
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2428
2779
        changes = preview_tree.iter_changes(revision_tree,
2429
2780
                                            include_unchanged=True)
2430
 
        root = revision_tree.inventory.root.file_id
 
2781
        root = revision_tree.get_root_id()
2431
2782
 
2432
2783
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2433
2784
 
2435
2786
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2436
2787
        changes = preview_tree.iter_changes(revision_tree,
2437
2788
                                            specific_files=[''])
2438
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2789
        self.assertEqual([A_ENTRY], list(changes))
2439
2790
 
2440
2791
    def test_want_unversioned(self):
2441
2792
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2442
2793
        changes = preview_tree.iter_changes(revision_tree,
2443
2794
                                            want_unversioned=True)
2444
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2795
        self.assertEqual([A_ENTRY], list(changes))
2445
2796
 
2446
2797
    def test_ignore_extra_trees_no_specific_files(self):
2447
2798
        # extra_trees is harmless without specific_files, so we'll silently
2490
2841
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2491
2842
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2492
2843
 
 
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
 
2493
2856
    def test_get_file(self):
2494
2857
        preview = self.get_empty_preview()
2495
2858
        preview.new_file('file', preview.root, 'contents', 'file-id')
2907
3270
        merger.merge_type = Merge3Merger
2908
3271
        merger.do_merge()
2909
3272
 
 
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
 
2910
3291
    def test_is_executable(self):
2911
3292
        tree = self.make_branch_and_tree('tree')
2912
3293
        preview = TransformPreview(tree)
2935
3316
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
2936
3317
 
2937
3318
    def test_ascii_limbo_paths(self):
2938
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
3319
        self.requireFeature(features.UnicodeFilenameFeature)
2939
3320
        branch = self.make_branch('any')
2940
3321
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
2941
3322
        tt = TransformPreview(tree)
2958
3339
 
2959
3340
class TestSerializeTransform(tests.TestCaseWithTransport):
2960
3341
 
2961
 
    _test_needs_features = [tests.UnicodeFilenameFeature]
 
3342
    _test_needs_features = [features.UnicodeFilenameFeature]
2962
3343
 
2963
3344
    def get_preview(self, tree=None):
2964
3345
        if tree is None:
3039
3420
        return self.make_records(attribs, contents)
3040
3421
 
3041
3422
    def test_serialize_symlink_creation(self):
3042
 
        self.requireFeature(tests.SymlinkFeature)
 
3423
        self.requireFeature(features.SymlinkFeature)
3043
3424
        tt = self.get_preview()
3044
3425
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3045
3426
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3046
3427
 
3047
3428
    def test_deserialize_symlink_creation(self):
3048
 
        self.requireFeature(tests.SymlinkFeature)
 
3429
        self.requireFeature(features.SymlinkFeature)
3049
3430
        tt = self.get_preview()
3050
3431
        tt.deserialize(iter(self.symlink_creation_records()))
3051
3432
        abspath = tt._limbo_name('new-1')
3218
3599
        trans_id = tt.trans_id_tree_path('file')
3219
3600
        self.assertEqual((LINES_ONE,),
3220
3601
            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)