~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 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
 
import stat
19
19
from StringIO import StringIO
20
20
import sys
 
21
import time
21
22
 
22
23
from bzrlib import (
23
24
    bencode,
24
25
    errors,
 
26
    filters,
25
27
    generate_ids,
26
28
    osutils,
27
 
    progress,
28
29
    revision as _mod_revision,
 
30
    rules,
29
31
    symbol_versioning,
30
32
    tests,
 
33
    trace,
 
34
    transform,
31
35
    urlutils,
32
36
    )
33
 
from bzrlib.bzrdir import BzrDir
34
 
from bzrlib.conflicts import (DuplicateEntry, DuplicateID, MissingParent,
35
 
                              UnversionedParent, ParentLoop, DeletingParent,
36
 
                              NonDirectoryParent)
 
37
from bzrlib.conflicts import (
 
38
    DeletingParent,
 
39
    DuplicateEntry,
 
40
    DuplicateID,
 
41
    MissingParent,
 
42
    NonDirectoryParent,
 
43
    ParentLoop,
 
44
    UnversionedParent,
 
45
)
 
46
from bzrlib.controldir import ControlDir
37
47
from bzrlib.diff import show_diff_trees
38
 
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
39
 
                           ReusingTransform, CantMoveRoot,
40
 
                           PathsNotVersionedError, ExistingLimbo,
41
 
                           ExistingPendingDeletion, ImmortalLimbo,
42
 
                           ImmortalPendingDeletion, LockError)
43
 
from bzrlib.osutils import file_kind, pathjoin
 
48
from bzrlib.errors import (
 
49
    DuplicateKey,
 
50
    ExistingLimbo,
 
51
    ExistingPendingDeletion,
 
52
    ImmortalLimbo,
 
53
    ImmortalPendingDeletion,
 
54
    LockError,
 
55
    MalformedTransform,
 
56
    ReusingTransform,
 
57
)
 
58
from bzrlib.osutils import (
 
59
    file_kind,
 
60
    pathjoin,
 
61
)
44
62
from bzrlib.merge import Merge3Merger, Merger
 
63
from bzrlib.mutabletree import MutableTree
45
64
from bzrlib.tests import (
 
65
    features,
 
66
    TestCaseInTempDir,
 
67
    TestSkipped,
 
68
    )
 
69
from bzrlib.tests.features import (
46
70
    HardlinkFeature,
47
71
    SymlinkFeature,
48
 
    TestCase,
49
 
    TestCaseInTempDir,
50
 
    TestSkipped,
51
72
    )
52
 
from bzrlib.transform import (TreeTransform, ROOT_PARENT, FinalPaths,
53
 
                              resolve_conflicts, cook_conflicts,
54
 
                              build_tree, get_backup_name,
55
 
                              _FileMover, resolve_checkout,
56
 
                              TransformPreview, create_from_tree)
 
73
from bzrlib.transform import (
 
74
    build_tree,
 
75
    create_from_tree,
 
76
    cook_conflicts,
 
77
    _FileMover,
 
78
    FinalPaths,
 
79
    resolve_conflicts,
 
80
    resolve_checkout,
 
81
    ROOT_PARENT,
 
82
    TransformPreview,
 
83
    TreeTransform,
 
84
)
57
85
 
58
86
 
59
87
class TestTreeTransform(tests.TestCaseWithTransport):
60
88
 
61
89
    def setUp(self):
62
90
        super(TestTreeTransform, self).setUp()
63
 
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
 
91
        self.wt = self.make_branch_and_tree('.', format='development-subtree')
64
92
        os.chdir('..')
65
93
 
66
94
    def get_transform(self):
68
96
        self.addCleanup(transform.finalize)
69
97
        return transform, transform.root
70
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
 
71
109
    def test_existing_limbo(self):
72
110
        transform, root = self.get_transform()
73
111
        limbo_name = transform._limbodir
100
138
        imaginary_id = transform.trans_id_tree_path('imaginary')
101
139
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
102
140
        self.assertEqual(imaginary_id, imaginary_id2)
103
 
        self.assertEqual(transform.get_tree_parent(imaginary_id), root)
104
 
        self.assertEqual(transform.final_kind(root), 'directory')
105
 
        self.assertEqual(transform.final_file_id(root), self.wt.get_root_id())
 
141
        self.assertEqual(root, transform.get_tree_parent(imaginary_id))
 
142
        self.assertEqual('directory', transform.final_kind(root))
 
143
        self.assertEqual(self.wt.get_root_id(), transform.final_file_id(root))
106
144
        trans_id = transform.create_path('name', root)
107
145
        self.assertIs(transform.final_file_id(trans_id), None)
108
 
        self.assertRaises(NoSuchFile, transform.final_kind, trans_id)
 
146
        self.assertIs(None, transform.final_kind(trans_id))
109
147
        transform.create_file('contents', trans_id)
110
148
        transform.set_executability(True, trans_id)
111
149
        transform.version_file('my_pretties', trans_id)
136
174
        transform.finalize()
137
175
        transform.finalize()
138
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
 
 
238
    def test_create_files_same_timestamp(self):
 
239
        transform, root = self.get_transform()
 
240
        self.wt.lock_tree_write()
 
241
        self.addCleanup(self.wt.unlock)
 
242
        # Roll back the clock, so that we know everything is being set to the
 
243
        # exact time
 
244
        transform._creation_mtime = creation_mtime = time.time() - 20.0
 
245
        transform.create_file('content-one',
 
246
                              transform.create_path('one', root))
 
247
        time.sleep(1) # *ugly*
 
248
        transform.create_file('content-two',
 
249
                              transform.create_path('two', root))
 
250
        transform.apply()
 
251
        fo, st1 = self.wt.get_file_with_stat(None, path='one', filtered=False)
 
252
        fo.close()
 
253
        fo, st2 = self.wt.get_file_with_stat(None, path='two', filtered=False)
 
254
        fo.close()
 
255
        # We only guarantee 2s resolution
 
256
        self.assertTrue(abs(creation_mtime - st1.st_mtime) < 2.0,
 
257
            "%s != %s within 2 seconds" % (creation_mtime, st1.st_mtime))
 
258
        # But if we have more than that, all files should get the same result
 
259
        self.assertEqual(st1.st_mtime, st2.st_mtime)
 
260
 
 
261
    def test_change_root_id(self):
 
262
        transform, root = self.get_transform()
 
263
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
 
264
        transform.new_directory('', ROOT_PARENT, 'new-root-id')
 
265
        transform.delete_contents(root)
 
266
        transform.unversion_file(root)
 
267
        transform.fixup_new_roots()
 
268
        transform.apply()
 
269
        self.assertEqual('new-root-id', self.wt.get_root_id())
 
270
 
 
271
    def test_change_root_id_add_files(self):
 
272
        transform, root = self.get_transform()
 
273
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
 
274
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
 
275
        transform.new_file('file', new_trans_id, ['new-contents\n'],
 
276
                           'new-file-id')
 
277
        transform.delete_contents(root)
 
278
        transform.unversion_file(root)
 
279
        transform.fixup_new_roots()
 
280
        transform.apply()
 
281
        self.assertEqual('new-root-id', self.wt.get_root_id())
 
282
        self.assertEqual('new-file-id', self.wt.path2id('file'))
 
283
        self.assertFileEqual('new-contents\n', self.wt.abspath('file'))
 
284
 
 
285
    def test_add_two_roots(self):
 
286
        transform, root = self.get_transform()
 
287
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
 
288
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
 
289
        self.assertRaises(ValueError, transform.fixup_new_roots)
 
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
 
139
353
    def test_hardlink(self):
140
354
        self.requireFeature(HardlinkFeature)
141
355
        transform, root = self.get_transform()
146
360
        trans_id = target_transform.create_path('file1', target_transform.root)
147
361
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
148
362
        target_transform.apply()
149
 
        self.failUnlessExists('target/file1')
 
363
        self.assertPathExists('target/file1')
150
364
        source_stat = os.stat(self.wt.abspath('file1'))
151
365
        target_stat = os.stat('target/file1')
152
366
        self.assertEqual(source_stat, target_stat)
185
399
        tree.lock_read()
186
400
        self.addCleanup(tree.unlock)
187
401
        self.assertEqual('subtree-revision',
188
 
                         tree.inventory['subtree-id'].reference_revision)
 
402
                         tree.root_inventory['subtree-id'].reference_revision)
189
403
 
190
404
    def test_conflicts(self):
191
405
        transform, root = self.get_transform()
318
532
        transform.new_file('FiLe', transform.root, 'content')
319
533
        resolve_conflicts(transform)
320
534
        transform.apply()
321
 
        self.failUnlessExists('tree/file')
322
 
        self.failUnlessExists('tree/FiLe.moved')
 
535
        self.assertPathExists('tree/file')
 
536
        self.assertPathExists('tree/FiLe.moved')
323
537
 
324
538
    def test_resolve_checkout_case_conflict(self):
325
539
        tree = self.make_branch_and_tree('tree')
334
548
        resolve_conflicts(transform,
335
549
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
336
550
        transform.apply()
337
 
        self.failUnlessExists('tree/file')
338
 
        self.failUnlessExists('tree/FiLe.moved')
 
551
        self.assertPathExists('tree/file')
 
552
        self.assertPathExists('tree/FiLe.moved')
339
553
 
340
554
    def test_apply_case_conflict(self):
341
555
        """Ensure that a transform with case conflicts can always be applied"""
349
563
        transform.new_file('dirFiLe', dir, 'content')
350
564
        resolve_conflicts(transform)
351
565
        transform.apply()
352
 
        self.failUnlessExists('tree/file')
 
566
        self.assertPathExists('tree/file')
353
567
        if not os.path.exists('tree/FiLe.moved'):
354
 
            self.failUnlessExists('tree/FiLe')
355
 
        self.failUnlessExists('tree/dir/dirfile')
 
568
            self.assertPathExists('tree/FiLe')
 
569
        self.assertPathExists('tree/dir/dirfile')
356
570
        if not os.path.exists('tree/dir/dirFiLe.moved'):
357
 
            self.failUnlessExists('tree/dir/dirFiLe')
 
571
            self.assertPathExists('tree/dir/dirFiLe')
358
572
 
359
573
    def test_case_insensitive_limbo(self):
360
574
        tree = self.make_branch_and_tree('tree')
369
583
        self.assertContainsRe(transform._limbo_name(first), 'new-1/file')
370
584
        self.assertNotContainsRe(transform._limbo_name(second), 'new-1/FiLe')
371
585
 
 
586
    def test_adjust_path_updates_child_limbo_names(self):
 
587
        tree = self.make_branch_and_tree('tree')
 
588
        transform = TreeTransform(tree)
 
589
        self.addCleanup(transform.finalize)
 
590
        foo_id = transform.new_directory('foo', transform.root)
 
591
        bar_id = transform.new_directory('bar', foo_id)
 
592
        baz_id = transform.new_directory('baz', bar_id)
 
593
        qux_id = transform.new_directory('qux', baz_id)
 
594
        transform.adjust_path('quxx', foo_id, bar_id)
 
595
        self.assertStartsWith(transform._limbo_name(qux_id),
 
596
                              transform._limbo_name(bar_id))
 
597
 
372
598
    def test_add_del(self):
373
599
        start, root = self.get_transform()
374
600
        start.new_directory('a', root, 'a')
556
782
                            'wizard2', 'behind_curtain')
557
783
 
558
784
    def test_symlinks_unicode(self):
559
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
785
        self.requireFeature(features.UnicodeFilenameFeature)
560
786
        self._test_symlinks(u'\N{Euro Sign}wizard',
561
787
                            u'wizard-targ\N{Euro Sign}t',
562
788
                            u'\N{Euro Sign}wizard2',
650
876
        raw_conflicts = resolve_conflicts(tt)
651
877
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
652
878
        tt.finalize()
653
 
        conflicts_s = [str(c) for c in cooked_conflicts]
 
879
        conflicts_s = [unicode(c) for c in cooked_conflicts]
654
880
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
655
881
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
656
882
                                         'Moved existing file to '
669
895
                                         ' versioned, but has versioned'
670
896
                                         ' children.  Versioned directory.')
671
897
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
672
 
                                         ' oz/emeraldcity.  Cancelled move.')
 
898
                                         ' oz/emeraldcity. Cancelled move.')
673
899
 
674
900
    def prepare_wrong_parent_kind(self):
675
901
        tt, root = self.get_transform()
726
952
        self.assertIs(None, self.wt.path2id('parent'))
727
953
        self.assertIs(None, self.wt.path2id('parent.new'))
728
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
 
729
970
    def test_moving_versioned_directories(self):
730
971
        create, root = self.get_transform()
731
972
        kansas = create.new_directory('kansas', root, 'kansas-id')
746
987
        create.apply()
747
988
        transform, root = self.get_transform()
748
989
        transform.adjust_root_path('oldroot', fun)
749
 
        new_root=transform.trans_id_tree_path('')
 
990
        new_root = transform.trans_id_tree_path('')
750
991
        transform.version_file('new-root', new_root)
751
992
        transform.apply()
752
993
 
764
1005
        rename.set_executability(True, myfile)
765
1006
        rename.apply()
766
1007
 
 
1008
    def test_rename_fails(self):
 
1009
        self.requireFeature(features.not_running_as_root)
 
1010
        # see https://bugs.launchpad.net/bzr/+bug/491763
 
1011
        create, root_id = self.get_transform()
 
1012
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
 
1013
        myfile = create.new_file('myfile', root_id, 'myfile-text',
 
1014
                                 'myfile-id')
 
1015
        create.apply()
 
1016
        if os.name == "posix" and sys.platform != "cygwin":
 
1017
            # posix filesystems fail on renaming if the readonly bit is set
 
1018
            osutils.make_readonly(self.wt.abspath('first-dir'))
 
1019
        elif os.name == "nt":
 
1020
            # windows filesystems fail on renaming open files
 
1021
            self.addCleanup(file(self.wt.abspath('myfile')).close)
 
1022
        else:
 
1023
            self.skip("Don't know how to force a permissions error on rename")
 
1024
        # now transform to rename
 
1025
        rename_transform, root_id = self.get_transform()
 
1026
        file_trans_id = rename_transform.trans_id_file_id('myfile-id')
 
1027
        dir_id = rename_transform.trans_id_file_id('first-id')
 
1028
        rename_transform.adjust_path('newname', dir_id, file_trans_id)
 
1029
        e = self.assertRaises(errors.TransformRenameFailed,
 
1030
            rename_transform.apply)
 
1031
        # On nix looks like: 
 
1032
        # "Failed to rename .../work/.bzr/checkout/limbo/new-1
 
1033
        # to .../first-dir/newname: [Errno 13] Permission denied"
 
1034
        # On windows looks like:
 
1035
        # "Failed to rename .../work/myfile to 
 
1036
        # .../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")
 
1045
 
767
1046
    def test_set_executability_order(self):
768
1047
        """Ensure that executability behaves the same, no matter what order.
769
1048
 
1041
1320
        parent2 = transform.new_directory('parent2', root)
1042
1321
        transform.adjust_path('child1', parent2, child1)
1043
1322
        transform.apply()
1044
 
        self.failIfExists(self.wt.abspath('parent1/child1'))
1045
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1323
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
 
1324
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1046
1325
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1047
1326
        # no rename for child1 (counting only renames during apply)
1048
 
        self.failUnlessEqual(2, transform.rename_count)
 
1327
        self.assertEqual(2, transform.rename_count)
1049
1328
 
1050
1329
    def test_cancel_parent(self):
1051
1330
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1074
1353
        parent2 = transform.new_directory('parent2', root)
1075
1354
        transform.adjust_path('child1', parent2, child1)
1076
1355
        transform.apply()
1077
 
        self.failIfExists(self.wt.abspath('parent1'))
1078
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1356
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
 
1357
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1079
1358
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1080
 
        self.failUnlessEqual(2, transform.rename_count)
 
1359
        self.assertEqual(2, transform.rename_count)
1081
1360
 
1082
1361
    def test_adjust_and_cancel(self):
1083
1362
        """Make sure adjust_path keeps track of limbo children properly"""
1116
1395
        child = transform.new_directory('child', parent)
1117
1396
        transform.adjust_path('parent', root, parent)
1118
1397
        transform.apply()
1119
 
        self.failUnlessExists(self.wt.abspath('parent/child'))
 
1398
        self.assertPathExists(self.wt.abspath('parent/child'))
1120
1399
        self.assertEqual(1, transform.rename_count)
1121
1400
 
1122
1401
    def test_reuse_name(self):
1198
1477
        # The rename will fail because the target directory is not empty (but
1199
1478
        # raises FileExists anyway).
1200
1479
        err = self.assertRaises(errors.FileExists, tt_helper)
1201
 
        self.assertContainsRe(str(err),
1202
 
            "^File exists: .+/baz")
 
1480
        self.assertEndsWith(err.path, "/baz")
1203
1481
 
1204
1482
    def test_two_directories_clash(self):
1205
1483
        def tt_helper():
1217
1495
                wt.unlock()
1218
1496
                raise
1219
1497
        err = self.assertRaises(errors.FileExists, tt_helper)
1220
 
        self.assertContainsRe(str(err),
1221
 
            "^File exists: .+/foo")
 
1498
        self.assertEndsWith(err.path, "/foo")
1222
1499
 
1223
1500
    def test_two_directories_clash_finalize(self):
1224
1501
        def tt_helper():
1236
1513
                tt.finalize()
1237
1514
                raise
1238
1515
        err = self.assertRaises(errors.FileExists, tt_helper)
1239
 
        self.assertContainsRe(str(err),
1240
 
            "^File exists: .+/foo")
 
1516
        self.assertEndsWith(err.path, "/foo")
1241
1517
 
1242
1518
    def test_file_to_directory(self):
1243
1519
        wt = self.make_branch_and_tree('.')
1253
1529
        tt.create_file(["aa\n"], bar_trans_id)
1254
1530
        tt.version_file("bar-1", bar_trans_id)
1255
1531
        tt.apply()
1256
 
        self.failUnlessExists("foo/bar")
 
1532
        self.assertPathExists("foo/bar")
1257
1533
        wt.lock_read()
1258
1534
        try:
1259
 
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1260
 
                    "directory")
 
1535
            self.assertEqual(wt.kind(wt.path2id("foo")), "directory")
1261
1536
        finally:
1262
1537
            wt.unlock()
1263
1538
        wt.commit("two")
1276
1551
        tt.delete_contents(foo_trans_id)
1277
1552
        tt.create_symlink("bar", foo_trans_id)
1278
1553
        tt.apply()
1279
 
        self.failUnlessExists("foo")
 
1554
        self.assertPathExists("foo")
1280
1555
        wt.lock_read()
1281
1556
        self.addCleanup(wt.unlock)
1282
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1283
 
                "symlink")
 
1557
        self.assertEqual(wt.kind(wt.path2id("foo")), "symlink")
1284
1558
 
1285
1559
    def test_dir_to_file(self):
1286
1560
        wt = self.make_branch_and_tree('.')
1295
1569
        tt.delete_versioned(bar_trans_id)
1296
1570
        tt.create_file(["aa\n"], foo_trans_id)
1297
1571
        tt.apply()
1298
 
        self.failUnlessExists("foo")
 
1572
        self.assertPathExists("foo")
1299
1573
        wt.lock_read()
1300
1574
        self.addCleanup(wt.unlock)
1301
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1302
 
                "file")
 
1575
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
1303
1576
 
1304
1577
    def test_dir_to_hardlink(self):
1305
1578
        self.requireFeature(HardlinkFeature)
1316
1589
        self.build_tree(['baz'])
1317
1590
        tt.create_hardlink("baz", foo_trans_id)
1318
1591
        tt.apply()
1319
 
        self.failUnlessExists("foo")
1320
 
        self.failUnlessExists("baz")
 
1592
        self.assertPathExists("foo")
 
1593
        self.assertPathExists("baz")
1321
1594
        wt.lock_read()
1322
1595
        self.addCleanup(wt.unlock)
1323
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1324
 
                "file")
 
1596
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
1325
1597
 
1326
1598
    def test_no_final_path(self):
1327
1599
        transform, root = self.get_transform()
1373
1645
    def __init__(self, dirname, root_id):
1374
1646
        self.name = dirname
1375
1647
        os.mkdir(dirname)
1376
 
        self.wt = BzrDir.create_standalone_workingtree(dirname)
 
1648
        self.wt = ControlDir.create_standalone_workingtree(dirname)
1377
1649
        self.wt.set_root_id(root_id)
1378
1650
        self.b = self.wt.branch
1379
1651
        self.tt = TreeTransform(self.wt)
1385
1657
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1386
1658
 
1387
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
 
1388
1692
class TestTransformMerge(TestCaseInTempDir):
1389
1693
 
1390
1694
    def test_text_merge(self):
1457
1761
        merge_modified = this.wt.merge_modified()
1458
1762
        self.assertSubset(merge_modified, modified)
1459
1763
        self.assertEqual(len(merge_modified), len(modified))
1460
 
        file(this.wt.id2abspath('a'), 'wb').write('booga')
 
1764
        with file(this.wt.id2abspath('a'), 'wb') as f: f.write('booga')
1461
1765
        modified.pop(0)
1462
1766
        merge_modified = this.wt.merge_modified()
1463
1767
        self.assertSubset(merge_modified, modified)
1577
1881
    def test_build_tree_with_symlinks(self):
1578
1882
        self.requireFeature(SymlinkFeature)
1579
1883
        os.mkdir('a')
1580
 
        a = BzrDir.create_standalone_workingtree('a')
 
1884
        a = ControlDir.create_standalone_workingtree('a')
1581
1885
        os.mkdir('a/foo')
1582
 
        file('a/foo/bar', 'wb').write('contents')
 
1886
        with file('a/foo/bar', 'wb') as f: f.write('contents')
1583
1887
        os.symlink('a/foo/bar', 'a/foo/baz')
1584
1888
        a.add(['foo', 'foo/bar', 'foo/baz'])
1585
1889
        a.commit('initial commit')
1586
 
        b = BzrDir.create_standalone_workingtree('b')
 
1890
        b = ControlDir.create_standalone_workingtree('b')
1587
1891
        basis = a.basis_tree()
1588
1892
        basis.lock_read()
1589
1893
        self.addCleanup(basis.unlock)
1594
1898
 
1595
1899
    def test_build_with_references(self):
1596
1900
        tree = self.make_branch_and_tree('source',
1597
 
            format='dirstate-with-subtree')
 
1901
            format='development-subtree')
1598
1902
        subtree = self.make_branch_and_tree('source/subtree',
1599
 
            format='dirstate-with-subtree')
 
1903
            format='development-subtree')
1600
1904
        tree.add_reference(subtree)
1601
1905
        tree.commit('a revision')
1602
1906
        tree.branch.create_checkout('target')
1603
 
        self.failUnlessExists('target')
1604
 
        self.failUnlessExists('target/subtree')
 
1907
        self.assertPathExists('target')
 
1908
        self.assertPathExists('target/subtree')
1605
1909
 
1606
1910
    def test_file_conflict_handling(self):
1607
1911
        """Ensure that when building trees, conflict handling is done"""
1654
1958
        source.commit('added file')
1655
1959
        build_tree(source.basis_tree(), target)
1656
1960
        self.assertEqual([], target.conflicts())
1657
 
        self.failUnlessExists('target/dir1/file')
 
1961
        self.assertPathExists('target/dir1/file')
1658
1962
 
1659
1963
        # Ensure contents are merged
1660
1964
        target = self.make_branch_and_tree('target2')
1661
1965
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1662
1966
        build_tree(source.basis_tree(), target)
1663
1967
        self.assertEqual([], target.conflicts())
1664
 
        self.failUnlessExists('target2/dir1/file2')
1665
 
        self.failUnlessExists('target2/dir1/file')
 
1968
        self.assertPathExists('target2/dir1/file2')
 
1969
        self.assertPathExists('target2/dir1/file')
1666
1970
 
1667
1971
        # Ensure new contents are suppressed for existing branches
1668
1972
        target = self.make_branch_and_tree('target3')
1669
1973
        self.make_branch('target3/dir1')
1670
1974
        self.build_tree(['target3/dir1/file2'])
1671
1975
        build_tree(source.basis_tree(), target)
1672
 
        self.failIfExists('target3/dir1/file')
1673
 
        self.failUnlessExists('target3/dir1/file2')
1674
 
        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')
1675
1979
        self.assertEqual([DuplicateEntry('Diverted to',
1676
1980
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1677
1981
            target.conflicts())
1680
1984
        self.build_tree(['target4/dir1/'])
1681
1985
        self.make_branch('target4/dir1/file')
1682
1986
        build_tree(source.basis_tree(), target)
1683
 
        self.failUnlessExists('target4/dir1/file')
 
1987
        self.assertPathExists('target4/dir1/file')
1684
1988
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1685
 
        self.failUnlessExists('target4/dir1/file.diverted')
 
1989
        self.assertPathExists('target4/dir1/file.diverted')
1686
1990
        self.assertEqual([DuplicateEntry('Diverted to',
1687
1991
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1688
1992
            target.conflicts())
1756
2060
        self.addCleanup(target.unlock)
1757
2061
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1758
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
 
1759
2075
    def test_build_tree_accelerator_tree_missing_file(self):
1760
2076
        source = self.create_ab_tree()
1761
2077
        os.unlink('source/file1')
1856
2172
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1857
2173
        self.assertTrue(source.is_executable('file1-id'))
1858
2174
 
 
2175
    def install_rot13_content_filter(self, pattern):
 
2176
        # We could use
 
2177
        # self.addCleanup(filters._reset_registry, filters._reset_registry())
 
2178
        # below, but that looks a bit... hard to read even if it's exactly
 
2179
        # the same thing.
 
2180
        original_registry = filters._reset_registry()
 
2181
        def restore_registry():
 
2182
            filters._reset_registry(original_registry)
 
2183
        self.addCleanup(restore_registry)
 
2184
        def rot13(chunks, context=None):
 
2185
            return [''.join(chunks).encode('rot13')]
 
2186
        rot13filter = filters.ContentFilter(rot13, rot13)
 
2187
        filters.filter_stacks_registry.register(
 
2188
            'rot13', {'yes': [rot13filter]}.get)
 
2189
        os.mkdir(self.test_home_dir + '/.bazaar')
 
2190
        rules_filename = self.test_home_dir + '/.bazaar/rules'
 
2191
        f = open(rules_filename, 'wb')
 
2192
        f.write('[name %s]\nrot13=yes\n' % (pattern,))
 
2193
        f.close()
 
2194
        def uninstall_rules():
 
2195
            os.remove(rules_filename)
 
2196
            rules.reset_rules()
 
2197
        self.addCleanup(uninstall_rules)
 
2198
        rules.reset_rules()
 
2199
 
 
2200
    def test_build_tree_content_filtered_files_are_not_hardlinked(self):
 
2201
        """build_tree will not hardlink files that have content filtering rules
 
2202
        applied to them (but will still hardlink other files from the same tree
 
2203
        if it can).
 
2204
        """
 
2205
        self.requireFeature(HardlinkFeature)
 
2206
        self.install_rot13_content_filter('file1')
 
2207
        source = self.create_ab_tree()
 
2208
        target = self.make_branch_and_tree('target')
 
2209
        revision_tree = source.basis_tree()
 
2210
        revision_tree.lock_read()
 
2211
        self.addCleanup(revision_tree.unlock)
 
2212
        build_tree(revision_tree, target, source, hardlink=True)
 
2213
        target.lock_read()
 
2214
        self.addCleanup(target.unlock)
 
2215
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2216
        source_stat = os.stat('source/file1')
 
2217
        target_stat = os.stat('target/file1')
 
2218
        self.assertNotEqual(source_stat, target_stat)
 
2219
        source_stat = os.stat('source/file2')
 
2220
        target_stat = os.stat('target/file2')
 
2221
        self.assertEqualStat(source_stat, target_stat)
 
2222
 
1859
2223
    def test_case_insensitive_build_tree_inventory(self):
1860
 
        if (tests.CaseInsensitiveFilesystemFeature.available()
1861
 
            or tests.CaseInsCasePresFilenameFeature.available()):
 
2224
        if (features.CaseInsensitiveFilesystemFeature.available()
 
2225
            or features.CaseInsCasePresFilenameFeature.available()):
1862
2226
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
1863
2227
        source = self.make_branch_and_tree('source')
1864
2228
        self.build_tree(['source/file', 'source/FILE'])
1872
2236
        self.assertEqual('file.moved', target.id2path('lower-id'))
1873
2237
        self.assertEqual('FILE', target.id2path('upper-id'))
1874
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
 
1875
2275
 
1876
2276
class TestCommitTransform(tests.TestCaseWithTransport):
1877
2277
 
1916
2316
        branch.lock_write()
1917
2317
        self.addCleanup(branch.unlock)
1918
2318
        tt = TransformPreview(branch.basis_tree())
 
2319
        self.addCleanup(tt.finalize)
1919
2320
        tt.new_directory('', ROOT_PARENT, 'TREE_ROOT')
1920
2321
        rev = tt.commit(branch, 'my message')
1921
2322
        self.assertEqual([], branch.basis_tree().get_parent_ids())
1927
2328
        branch.lock_write()
1928
2329
        self.addCleanup(branch.unlock)
1929
2330
        tt = TransformPreview(branch.basis_tree())
 
2331
        self.addCleanup(tt.finalize)
1930
2332
        e = self.assertRaises(ValueError, tt.commit, branch,
1931
2333
                          'my message', ['rev1b-id'])
1932
2334
        self.assertEqual('Cannot supply merge parents for first commit.',
1937
2339
        branch, tt = self.get_branch_and_transform()
1938
2340
        tt.new_file('file', tt.root, 'contents', 'file-id')
1939
2341
        trans_id = tt.new_directory('dir', tt.root, 'dir-id')
1940
 
        tt.new_symlink('symlink', trans_id, 'target', 'symlink-id')
 
2342
        if SymlinkFeature.available():
 
2343
            tt.new_symlink('symlink', trans_id, 'target', 'symlink-id')
1941
2344
        rev = tt.commit(branch, 'message')
1942
2345
        tree = branch.basis_tree()
1943
2346
        self.assertEqual('file', tree.id2path('file-id'))
1944
2347
        self.assertEqual('contents', tree.get_file_text('file-id'))
1945
2348
        self.assertEqual('dir', tree.id2path('dir-id'))
1946
 
        self.assertEqual('dir/symlink', tree.id2path('symlink-id'))
1947
 
        self.assertEqual('target', tree.get_symlink_target('symlink-id'))
 
2349
        if SymlinkFeature.available():
 
2350
            self.assertEqual('dir/symlink', tree.id2path('symlink-id'))
 
2351
            self.assertEqual('target', tree.get_symlink_target('symlink-id'))
1948
2352
 
1949
2353
    def test_add_unversioned(self):
1950
2354
        branch, tt = self.get_branch_and_transform()
1957
2361
        tt.new_file('file', tt.root, 'contents', 'file-id')
1958
2362
        tt.commit(branch, 'message', strict=True)
1959
2363
        tt = TransformPreview(branch.basis_tree())
 
2364
        self.addCleanup(tt.finalize)
1960
2365
        trans_id = tt.trans_id_file_id('file-id')
1961
2366
        tt.delete_contents(trans_id)
1962
2367
        tt.create_file('contents', trans_id)
1973
2378
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
1974
2379
                          'message')
1975
2380
 
1976
 
 
1977
 
class MockTransform(object):
1978
 
 
1979
 
    def has_named_child(self, by_parent, parent_id, name):
1980
 
        for child_id in by_parent[parent_id]:
1981
 
            if child_id == '0':
1982
 
                if name == "name~":
1983
 
                    return True
1984
 
            elif name == "name.~%s~" % child_id:
1985
 
                return True
1986
 
        return False
1987
 
 
1988
 
 
1989
 
class MockEntry(object):
1990
 
    def __init__(self):
1991
 
        object.__init__(self)
1992
 
        self.name = "name"
1993
 
 
1994
 
 
1995
 
class TestGetBackupName(TestCase):
1996
 
    def test_get_backup_name(self):
1997
 
        tt = MockTransform()
1998
 
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
1999
 
        self.assertEqual(name, 'name.~1~')
2000
 
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
2001
 
        self.assertEqual(name, 'name.~2~')
2002
 
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
2003
 
        self.assertEqual(name, 'name.~1~')
2004
 
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
2005
 
        self.assertEqual(name, 'name.~1~')
2006
 
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
2007
 
        self.assertEqual(name, 'name.~4~')
 
2381
    def test_commit_rich_revision_data(self):
 
2382
        branch, tt = self.get_branch_and_transform()
 
2383
        rev_id = tt.commit(branch, 'message', timestamp=1, timezone=43201,
 
2384
                           committer='me <me@example.com>',
 
2385
                           revprops={'foo': 'bar'}, revision_id='revid-1',
 
2386
                           authors=['Author1 <author1@example.com>',
 
2387
                              'Author2 <author2@example.com>',
 
2388
                               ])
 
2389
        self.assertEqual('revid-1', rev_id)
 
2390
        revision = branch.repository.get_revision(rev_id)
 
2391
        self.assertEqual(1, revision.timestamp)
 
2392
        self.assertEqual(43201, revision.timezone)
 
2393
        self.assertEqual('me <me@example.com>', revision.committer)
 
2394
        self.assertEqual(['Author1 <author1@example.com>',
 
2395
                          'Author2 <author2@example.com>'],
 
2396
                         revision.get_apparent_authors())
 
2397
        del revision.properties['authors']
 
2398
        self.assertEqual({'foo': 'bar',
 
2399
                          'branch-nick': 'tree'},
 
2400
                         revision.properties)
 
2401
 
 
2402
    def test_no_explicit_revprops(self):
 
2403
        branch, tt = self.get_branch_and_transform()
 
2404
        rev_id = tt.commit(branch, 'message', authors=[
 
2405
            'Author1 <author1@example.com>',
 
2406
            'Author2 <author2@example.com>', ])
 
2407
        revision = branch.repository.get_revision(rev_id)
 
2408
        self.assertEqual(['Author1 <author1@example.com>',
 
2409
                          'Author2 <author2@example.com>'],
 
2410
                         revision.get_apparent_authors())
 
2411
        self.assertEqual('tree', revision.properties['branch-nick'])
2008
2412
 
2009
2413
 
2010
2414
class TestFileMover(tests.TestCaseWithTransport):
2013
2417
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2014
2418
        mover = _FileMover()
2015
2419
        mover.rename('a', 'q')
2016
 
        self.failUnlessExists('q')
2017
 
        self.failIfExists('a')
2018
 
        self.failUnlessExists('q/b')
2019
 
        self.failUnlessExists('c')
2020
 
        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')
2021
2425
 
2022
2426
    def test_pre_delete_rollback(self):
2023
2427
        self.build_tree(['a/'])
2024
2428
        mover = _FileMover()
2025
2429
        mover.pre_delete('a', 'q')
2026
 
        self.failUnlessExists('q')
2027
 
        self.failIfExists('a')
 
2430
        self.assertPathExists('q')
 
2431
        self.assertPathDoesNotExist('a')
2028
2432
        mover.rollback()
2029
 
        self.failIfExists('q')
2030
 
        self.failUnlessExists('a')
 
2433
        self.assertPathDoesNotExist('q')
 
2434
        self.assertPathExists('a')
2031
2435
 
2032
2436
    def test_apply_deletions(self):
2033
2437
        self.build_tree(['a/', 'b/'])
2034
2438
        mover = _FileMover()
2035
2439
        mover.pre_delete('a', 'q')
2036
2440
        mover.pre_delete('b', 'r')
2037
 
        self.failUnlessExists('q')
2038
 
        self.failUnlessExists('r')
2039
 
        self.failIfExists('a')
2040
 
        self.failIfExists('b')
 
2441
        self.assertPathExists('q')
 
2442
        self.assertPathExists('r')
 
2443
        self.assertPathDoesNotExist('a')
 
2444
        self.assertPathDoesNotExist('b')
2041
2445
        mover.apply_deletions()
2042
 
        self.failIfExists('q')
2043
 
        self.failIfExists('r')
2044
 
        self.failIfExists('a')
2045
 
        self.failIfExists('b')
 
2446
        self.assertPathDoesNotExist('q')
 
2447
        self.assertPathDoesNotExist('r')
 
2448
        self.assertPathDoesNotExist('a')
 
2449
        self.assertPathDoesNotExist('b')
2046
2450
 
2047
2451
    def test_file_mover_rollback(self):
2048
2452
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2053
2457
            mover.rename('a', 'c')
2054
2458
        except errors.FileExists, e:
2055
2459
            mover.rollback()
2056
 
        self.failUnlessExists('a')
2057
 
        self.failUnlessExists('c/d')
 
2460
        self.assertPathExists('a')
 
2461
        self.assertPathExists('c/d')
2058
2462
 
2059
2463
 
2060
2464
class Bogus(Exception):
2090
2494
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2091
2495
        self.assertRaises(Bogus, tt.apply,
2092
2496
                          _mover=self.ExceptionFileMover(bad_source='a'))
2093
 
        self.failUnlessExists('a')
2094
 
        self.failUnlessExists('a/b')
 
2497
        self.assertPathExists('a')
 
2498
        self.assertPathExists('a/b')
2095
2499
        tt.apply()
2096
 
        self.failUnlessExists('c')
2097
 
        self.failUnlessExists('c/d')
 
2500
        self.assertPathExists('c')
 
2501
        self.assertPathExists('c/d')
2098
2502
 
2099
2503
    def test_rollback_rename_into_place(self):
2100
2504
        tree = self.make_branch_and_tree('.')
2106
2510
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2107
2511
        self.assertRaises(Bogus, tt.apply,
2108
2512
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2109
 
        self.failUnlessExists('a')
2110
 
        self.failUnlessExists('a/b')
 
2513
        self.assertPathExists('a')
 
2514
        self.assertPathExists('a/b')
2111
2515
        tt.apply()
2112
 
        self.failUnlessExists('c')
2113
 
        self.failUnlessExists('c/d')
 
2516
        self.assertPathExists('c')
 
2517
        self.assertPathExists('c/d')
2114
2518
 
2115
2519
    def test_rollback_deletion(self):
2116
2520
        tree = self.make_branch_and_tree('.')
2122
2526
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2123
2527
        self.assertRaises(Bogus, tt.apply,
2124
2528
                          _mover=self.ExceptionFileMover(bad_target='d'))
2125
 
        self.failUnlessExists('a')
2126
 
        self.failUnlessExists('a/b')
2127
 
 
2128
 
    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):
2129
2660
        wt = self.make_branch_and_tree('.')
 
2661
        self.build_tree(['dir/',])
 
2662
        wt.add(['dir'], ['dir-id'])
 
2663
        wt.commit('Create dir')
2130
2664
        tt = TreeTransform(wt)
2131
2665
        self.addCleanup(tt.finalize)
2132
 
        parent = tt.trans_id_file_id('parent-id')
2133
 
        tt.new_file('file', parent, 'Contents')
2134
 
        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())
2135
2690
 
2136
2691
 
2137
2692
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2138
2693
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2139
2694
                  (False, False))
2140
2695
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2141
 
              ('', ''), ('directory', 'directory'), (False, None))
 
2696
              ('', ''), ('directory', 'directory'), (False, False))
2142
2697
 
2143
2698
 
2144
2699
class TestTransformPreview(tests.TestCaseWithTransport):
2213
2768
 
2214
2769
    def test_iter_changes(self):
2215
2770
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2216
 
        root = revision_tree.inventory.root.file_id
 
2771
        root = revision_tree.get_root_id()
2217
2772
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
2218
2773
                          (root, root), ('a', 'a'), ('file', 'file'),
2219
2774
                          (False, False))],
2223
2778
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2224
2779
        changes = preview_tree.iter_changes(revision_tree,
2225
2780
                                            include_unchanged=True)
2226
 
        root = revision_tree.inventory.root.file_id
 
2781
        root = revision_tree.get_root_id()
2227
2782
 
2228
2783
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2229
2784
 
2231
2786
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2232
2787
        changes = preview_tree.iter_changes(revision_tree,
2233
2788
                                            specific_files=[''])
2234
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2789
        self.assertEqual([A_ENTRY], list(changes))
2235
2790
 
2236
2791
    def test_want_unversioned(self):
2237
2792
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2238
2793
        changes = preview_tree.iter_changes(revision_tree,
2239
2794
                                            want_unversioned=True)
2240
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2795
        self.assertEqual([A_ENTRY], list(changes))
2241
2796
 
2242
2797
    def test_ignore_extra_trees_no_specific_files(self):
2243
2798
        # extra_trees is harmless without specific_files, so we'll silently
2253
2808
    def test_ignore_pb(self):
2254
2809
        # pb could be supported, but TT.iter_changes doesn't support it.
2255
2810
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2256
 
        preview_tree.iter_changes(revision_tree, pb=progress.DummyProgress())
 
2811
        preview_tree.iter_changes(revision_tree)
2257
2812
 
2258
2813
    def test_kind(self):
2259
2814
        revision_tree = self.create_tree()
2274
2829
        self.assertEqual(os.stat(limbo_path).st_mtime,
2275
2830
                         preview_tree.get_file_mtime('file-id'))
2276
2831
 
 
2832
    def test_get_file_mtime_renamed(self):
 
2833
        work_tree = self.make_branch_and_tree('tree')
 
2834
        self.build_tree(['tree/file'])
 
2835
        work_tree.add('file', 'file-id')
 
2836
        preview = TransformPreview(work_tree)
 
2837
        self.addCleanup(preview.finalize)
 
2838
        file_trans_id = preview.trans_id_tree_file_id('file-id')
 
2839
        preview.adjust_path('renamed', preview.root, file_trans_id)
 
2840
        preview_tree = preview.get_preview_tree()
 
2841
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
 
2842
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
 
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
 
2277
2856
    def test_get_file(self):
2278
2857
        preview = self.get_empty_preview()
2279
2858
        preview.new_file('file', preview.root, 'contents', 'file-id')
2427
3006
        self.assertEqual(('missing', None, None, None), summary)
2428
3007
 
2429
3008
    def test_file_content_summary_executable(self):
2430
 
        if not osutils.supports_executable():
2431
 
            raise TestNotApplicable()
2432
3009
        preview = self.get_empty_preview()
2433
3010
        path_id = preview.new_file('path', preview.root, 'contents', 'path-id')
2434
3011
        preview.set_executability(True, path_id)
2443
3020
        self.assertIs(None, summary[3])
2444
3021
 
2445
3022
    def test_change_executability(self):
2446
 
        if not osutils.supports_executable():
2447
 
            raise TestNotApplicable()
2448
3023
        tree = self.make_branch_and_tree('tree')
2449
3024
        self.build_tree(['tree/path'])
2450
3025
        tree.add('path')
2464
3039
        # size must be known
2465
3040
        self.assertEqual(len('contents'), summary[1])
2466
3041
        # not executable
2467
 
        if osutils.supports_executable():
2468
 
            self.assertEqual(False, summary[2])
2469
 
        else:
2470
 
            self.assertEqual(None, summary[2])
 
3042
        self.assertEqual(False, summary[2])
2471
3043
        # will not have hash (not cheap to determine)
2472
3044
        self.assertIs(None, summary[3])
2473
3045
 
2614
3186
 
2615
3187
    def test_walkdirs(self):
2616
3188
        preview = self.get_empty_preview()
2617
 
        preview.version_file('tree-root', preview.root)
 
3189
        root = preview.new_directory('', ROOT_PARENT, 'tree-root')
 
3190
        # FIXME: new_directory should mark root.
 
3191
        preview.fixup_new_roots()
2618
3192
        preview_tree = preview.get_preview_tree()
2619
3193
        file_trans_id = preview.new_file('a', preview.root, 'contents',
2620
3194
                                         'a-id')
2651
3225
        self.addCleanup(work_tree.unlock)
2652
3226
        preview = TransformPreview(work_tree)
2653
3227
        self.addCleanup(preview.finalize)
2654
 
        preview_tree = preview.get_preview_tree()
2655
3228
        file_trans_id = preview.trans_id_file_id('file-id')
2656
3229
        preview.delete_contents(file_trans_id)
2657
3230
        preview.create_file('a\nb\n', file_trans_id)
2658
 
        pb = progress.DummyProgress()
2659
 
        merger = Merger.from_revision_ids(pb, preview_tree,
 
3231
        preview_tree = preview.get_preview_tree()
 
3232
        merger = Merger.from_revision_ids(None, preview_tree,
2660
3233
                                          child_tree.branch.last_revision(),
2661
3234
                                          other_branch=child_tree.branch,
2662
3235
                                          tree_branch=work_tree.branch)
2674
3247
        tt.new_file('name', tt.root, 'content', 'file-id')
2675
3248
        tree2 = self.make_branch_and_tree('tree2')
2676
3249
        tree2.set_root_id('TREE_ROOT')
2677
 
        pb = progress.DummyProgress()
2678
3250
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
2679
 
                                         pb, tree.basis_tree())
 
3251
                                         None, tree.basis_tree())
2680
3252
        merger.merge_type = Merge3Merger
2681
3253
        merger.do_merge()
2682
3254
 
2692
3264
        tt.create_file('baz', trans_id)
2693
3265
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
2694
3266
        self.build_tree_contents([('tree2/foo', 'qux')])
2695
 
        pb = progress.DummyProgress()
 
3267
        pb = None
2696
3268
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
2697
3269
                                         pb, tree.basis_tree())
2698
3270
        merger.merge_type = Merge3Merger
2699
3271
        merger.do_merge()
2700
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
 
2701
3291
    def test_is_executable(self):
2702
3292
        tree = self.make_branch_and_tree('tree')
2703
3293
        preview = TransformPreview(tree)
2725
3315
        rev2_tree = tree.branch.repository.revision_tree(rev2_id)
2726
3316
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
2727
3317
 
 
3318
    def test_ascii_limbo_paths(self):
 
3319
        self.requireFeature(features.UnicodeFilenameFeature)
 
3320
        branch = self.make_branch('any')
 
3321
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
 
3322
        tt = TransformPreview(tree)
 
3323
        self.addCleanup(tt.finalize)
 
3324
        foo_id = tt.new_directory('', ROOT_PARENT)
 
3325
        bar_id = tt.new_file(u'\u1234bar', foo_id, 'contents')
 
3326
        limbo_path = tt._limbo_name(bar_id)
 
3327
        self.assertEqual(limbo_path.encode('ascii', 'replace'), limbo_path)
 
3328
 
2728
3329
 
2729
3330
class FakeSerializer(object):
2730
3331
    """Serializer implementation that simply returns the input.
2738
3339
 
2739
3340
class TestSerializeTransform(tests.TestCaseWithTransport):
2740
3341
 
2741
 
    _test_needs_features = [tests.UnicodeFilenameFeature]
 
3342
    _test_needs_features = [features.UnicodeFilenameFeature]
2742
3343
 
2743
3344
    def get_preview(self, tree=None):
2744
3345
        if tree is None:
2819
3420
        return self.make_records(attribs, contents)
2820
3421
 
2821
3422
    def test_serialize_symlink_creation(self):
2822
 
        self.requireFeature(tests.SymlinkFeature)
 
3423
        self.requireFeature(features.SymlinkFeature)
2823
3424
        tt = self.get_preview()
2824
3425
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
2825
3426
        self.assertSerializesTo(self.symlink_creation_records(), tt)
2826
3427
 
2827
3428
    def test_deserialize_symlink_creation(self):
2828
 
        self.requireFeature(tests.SymlinkFeature)
 
3429
        self.requireFeature(features.SymlinkFeature)
2829
3430
        tt = self.get_preview()
2830
3431
        tt.deserialize(iter(self.symlink_creation_records()))
2831
3432
        abspath = tt._limbo_name('new-1')
2998
3599
        trans_id = tt.trans_id_tree_path('file')
2999
3600
        self.assertEqual((LINES_ONE,),
3000
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)