~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

(vila) Revise legal option names to be less drastic. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
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
from StringIO import StringIO
19
20
import sys
 
21
import time
20
22
 
21
23
from bzrlib import (
 
24
    bencode,
22
25
    errors,
 
26
    filters,
23
27
    generate_ids,
 
28
    osutils,
 
29
    revision as _mod_revision,
 
30
    rules,
24
31
    symbol_versioning,
25
32
    tests,
 
33
    trace,
 
34
    transform,
26
35
    urlutils,
27
36
    )
28
 
from bzrlib.bzrdir import BzrDir
29
 
from bzrlib.conflicts import (DuplicateEntry, DuplicateID, MissingParent,
30
 
                              UnversionedParent, ParentLoop, DeletingParent,)
31
 
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
32
 
                           ReusingTransform, CantMoveRoot, 
33
 
                           PathsNotVersionedError, ExistingLimbo,
34
 
                           ImmortalLimbo, LockError)
35
 
from bzrlib.osutils import file_kind, has_symlinks, pathjoin
36
 
from bzrlib.merge import Merge3Merger
37
 
from bzrlib.tests import TestCaseInTempDir, TestSkipped, TestCase
38
 
from bzrlib.transform import (TreeTransform, ROOT_PARENT, FinalPaths, 
39
 
                              resolve_conflicts, cook_conflicts, 
40
 
                              find_interesting, build_tree, get_backup_name,
41
 
                              change_entry)
 
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
 
47
from bzrlib.diff import show_diff_trees
 
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
)
 
62
from bzrlib.merge import Merge3Merger, Merger
 
63
from bzrlib.mutabletree import MutableTree
 
64
from bzrlib.tests import (
 
65
    features,
 
66
    TestCaseInTempDir,
 
67
    TestSkipped,
 
68
    )
 
69
from bzrlib.tests.features import (
 
70
    HardlinkFeature,
 
71
    SymlinkFeature,
 
72
    )
 
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
)
42
85
 
43
86
 
44
87
class TestTreeTransform(tests.TestCaseWithTransport):
45
88
 
46
89
    def setUp(self):
47
90
        super(TestTreeTransform, self).setUp()
48
 
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
 
91
        self.wt = self.make_branch_and_tree('.', format='development-subtree')
49
92
        os.chdir('..')
50
93
 
51
94
    def get_transform(self):
52
95
        transform = TreeTransform(self.wt)
53
 
        #self.addCleanup(transform.finalize)
 
96
        self.addCleanup(transform.finalize)
54
97
        return transform, transform.root
55
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
 
56
109
    def test_existing_limbo(self):
57
 
        limbo_name = urlutils.local_path_from_url(
58
 
            self.wt._control_files.controlfilename('limbo'))
59
110
        transform, root = self.get_transform()
 
111
        limbo_name = transform._limbodir
 
112
        deletion_path = transform._deletiondir
60
113
        os.mkdir(pathjoin(limbo_name, 'hehe'))
61
114
        self.assertRaises(ImmortalLimbo, transform.apply)
62
115
        self.assertRaises(LockError, self.wt.unlock)
64
117
        self.assertRaises(LockError, self.wt.unlock)
65
118
        os.rmdir(pathjoin(limbo_name, 'hehe'))
66
119
        os.rmdir(limbo_name)
 
120
        os.rmdir(deletion_path)
67
121
        transform, root = self.get_transform()
68
122
        transform.apply()
69
123
 
 
124
    def test_existing_pending_deletion(self):
 
125
        transform, root = self.get_transform()
 
126
        deletion_path = self._limbodir = urlutils.local_path_from_url(
 
127
            transform._tree._transport.abspath('pending-deletion'))
 
128
        os.mkdir(pathjoin(deletion_path, 'blocking-directory'))
 
129
        self.assertRaises(ImmortalPendingDeletion, transform.apply)
 
130
        self.assertRaises(LockError, self.wt.unlock)
 
131
        self.assertRaises(ExistingPendingDeletion, self.get_transform)
 
132
 
70
133
    def test_build(self):
71
 
        transform, root = self.get_transform() 
 
134
        transform, root = self.get_transform()
 
135
        self.wt.lock_tree_write()
 
136
        self.addCleanup(self.wt.unlock)
72
137
        self.assertIs(transform.get_tree_parent(root), ROOT_PARENT)
73
138
        imaginary_id = transform.trans_id_tree_path('imaginary')
74
139
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
75
140
        self.assertEqual(imaginary_id, imaginary_id2)
76
 
        self.assertEqual(transform.get_tree_parent(imaginary_id), root)
77
 
        self.assertEqual(transform.final_kind(root), 'directory')
78
 
        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))
79
144
        trans_id = transform.create_path('name', root)
80
145
        self.assertIs(transform.final_file_id(trans_id), None)
81
 
        self.assertRaises(NoSuchFile, transform.final_kind, trans_id)
 
146
        self.assertIs(None, transform.final_kind(trans_id))
82
147
        transform.create_file('contents', trans_id)
83
148
        transform.set_executability(True, trans_id)
84
149
        transform.version_file('my_pretties', trans_id)
102
167
        self.assertIs(self.wt.is_executable('my_pretties2'), False)
103
168
        self.assertEqual('directory', file_kind(self.wt.abspath('oz')))
104
169
        self.assertEqual(len(modified_paths), 3)
105
 
        tree_mod_paths = [self.wt.id2abspath(f) for f in 
 
170
        tree_mod_paths = [self.wt.id2abspath(f) for f in
106
171
                          ('ozzie', 'my_pretties', 'my_pretties2')]
107
172
        self.assertSubset(tree_mod_paths, modified_paths)
108
173
        # is it safe to finalize repeatedly?
109
174
        transform.finalize()
110
175
        transform.finalize()
111
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
 
 
353
    def test_hardlink(self):
 
354
        self.requireFeature(HardlinkFeature)
 
355
        transform, root = self.get_transform()
 
356
        transform.new_file('file1', root, 'contents')
 
357
        transform.apply()
 
358
        target = self.make_branch_and_tree('target')
 
359
        target_transform = TreeTransform(target)
 
360
        trans_id = target_transform.create_path('file1', target_transform.root)
 
361
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
 
362
        target_transform.apply()
 
363
        self.assertPathExists('target/file1')
 
364
        source_stat = os.stat(self.wt.abspath('file1'))
 
365
        target_stat = os.stat('target/file1')
 
366
        self.assertEqual(source_stat, target_stat)
 
367
 
112
368
    def test_convenience(self):
113
369
        transform, root = self.get_transform()
114
 
        trans_id = transform.new_file('name', root, 'contents', 
 
370
        self.wt.lock_tree_write()
 
371
        self.addCleanup(self.wt.unlock)
 
372
        trans_id = transform.new_file('name', root, 'contents',
115
373
                                      'my_pretties', True)
116
374
        oz = transform.new_directory('oz', root, 'oz-id')
117
375
        dorothy = transform.new_directory('dorothy', oz, 'dorothy-id')
118
 
        toto = transform.new_file('toto', dorothy, 'toto-contents', 
 
376
        toto = transform.new_file('toto', dorothy, 'toto-contents',
119
377
                                  'toto-id', False)
120
378
 
121
379
        self.assertEqual(len(transform.find_conflicts()), 0)
141
399
        tree.lock_read()
142
400
        self.addCleanup(tree.unlock)
143
401
        self.assertEqual('subtree-revision',
144
 
                         tree.inventory['subtree-id'].reference_revision)
 
402
                         tree.root_inventory['subtree-id'].reference_revision)
145
403
 
146
404
    def test_conflicts(self):
147
405
        transform, root = self.get_transform()
148
 
        trans_id = transform.new_file('name', root, 'contents', 
 
406
        trans_id = transform.new_file('name', root, 'contents',
149
407
                                      'my_pretties')
150
408
        self.assertEqual(len(transform.find_conflicts()), 0)
151
409
        trans_id2 = transform.new_file('name', root, 'Crontents', 'toto')
152
 
        self.assertEqual(transform.find_conflicts(), 
 
410
        self.assertEqual(transform.find_conflicts(),
153
411
                         [('duplicate', trans_id, trans_id2, 'name')])
154
412
        self.assertRaises(MalformedTransform, transform.apply)
155
413
        transform.adjust_path('name', trans_id, trans_id2)
156
 
        self.assertEqual(transform.find_conflicts(), 
 
414
        self.assertEqual(transform.find_conflicts(),
157
415
                         [('non-directory parent', trans_id)])
158
416
        tinman_id = transform.trans_id_tree_path('tinman')
159
417
        transform.adjust_path('name', tinman_id, trans_id2)
160
 
        self.assertEqual(transform.find_conflicts(), 
161
 
                         [('unversioned parent', tinman_id), 
 
418
        self.assertEqual(transform.find_conflicts(),
 
419
                         [('unversioned parent', tinman_id),
162
420
                          ('missing parent', tinman_id)])
163
421
        lion_id = transform.create_path('lion', root)
164
 
        self.assertEqual(transform.find_conflicts(), 
165
 
                         [('unversioned parent', tinman_id), 
 
422
        self.assertEqual(transform.find_conflicts(),
 
423
                         [('unversioned parent', tinman_id),
166
424
                          ('missing parent', tinman_id)])
167
425
        transform.adjust_path('name', lion_id, trans_id2)
168
 
        self.assertEqual(transform.find_conflicts(), 
 
426
        self.assertEqual(transform.find_conflicts(),
169
427
                         [('unversioned parent', lion_id),
170
428
                          ('missing parent', lion_id)])
171
429
        transform.version_file("Courage", lion_id)
172
 
        self.assertEqual(transform.find_conflicts(), 
173
 
                         [('missing parent', lion_id), 
 
430
        self.assertEqual(transform.find_conflicts(),
 
431
                         [('missing parent', lion_id),
174
432
                          ('versioning no contents', lion_id)])
175
433
        transform.adjust_path('name2', root, trans_id2)
176
 
        self.assertEqual(transform.find_conflicts(), 
 
434
        self.assertEqual(transform.find_conflicts(),
177
435
                         [('versioning no contents', lion_id)])
178
436
        transform.create_file('Contents, okay?', lion_id)
179
437
        transform.adjust_path('name2', trans_id2, trans_id2)
180
 
        self.assertEqual(transform.find_conflicts(), 
181
 
                         [('parent loop', trans_id2), 
 
438
        self.assertEqual(transform.find_conflicts(),
 
439
                         [('parent loop', trans_id2),
182
440
                          ('non-directory parent', trans_id2)])
183
441
        transform.adjust_path('name2', root, trans_id2)
184
442
        oz_id = transform.new_directory('oz', root)
185
443
        transform.set_executability(True, oz_id)
186
 
        self.assertEqual(transform.find_conflicts(), 
 
444
        self.assertEqual(transform.find_conflicts(),
187
445
                         [('unversioned executability', oz_id)])
188
446
        transform.version_file('oz-id', oz_id)
189
 
        self.assertEqual(transform.find_conflicts(), 
 
447
        self.assertEqual(transform.find_conflicts(),
190
448
                         [('non-file executability', oz_id)])
191
449
        transform.set_executability(None, oz_id)
192
450
        tip_id = transform.new_file('tip', oz_id, 'ozma', 'tip-id')
201
459
        self.assert_('oz/tip' in transform2._tree_path_ids)
202
460
        self.assertEqual(fp.get_path(newtip), pathjoin('oz', 'tip'))
203
461
        self.assertEqual(len(result), 2)
204
 
        self.assertEqual((result[0][0], result[0][1]), 
 
462
        self.assertEqual((result[0][0], result[0][1]),
205
463
                         ('duplicate', newtip))
206
 
        self.assertEqual((result[1][0], result[1][2]), 
 
464
        self.assertEqual((result[1][0], result[1][2]),
207
465
                         ('duplicate id', newtip))
208
466
        transform2.finalize()
209
467
        transform3 = TreeTransform(self.wt)
210
468
        self.addCleanup(transform3.finalize)
211
469
        oz_id = transform3.trans_id_tree_file_id('oz-id')
212
470
        transform3.delete_contents(oz_id)
213
 
        self.assertEqual(transform3.find_conflicts(), 
 
471
        self.assertEqual(transform3.find_conflicts(),
214
472
                         [('missing parent', oz_id)])
215
473
        root_id = transform3.root
216
474
        tip_id = transform3.trans_id_tree_file_id('tip-id')
217
475
        transform3.adjust_path('tip', root_id, tip_id)
218
476
        transform3.apply()
219
477
 
 
478
    def test_conflict_on_case_insensitive(self):
 
479
        tree = self.make_branch_and_tree('tree')
 
480
        # Don't try this at home, kids!
 
481
        # Force the tree to report that it is case sensitive, for conflict
 
482
        # resolution tests
 
483
        tree.case_sensitive = True
 
484
        transform = TreeTransform(tree)
 
485
        self.addCleanup(transform.finalize)
 
486
        transform.new_file('file', transform.root, 'content')
 
487
        transform.new_file('FiLe', transform.root, 'content')
 
488
        result = transform.find_conflicts()
 
489
        self.assertEqual([], result)
 
490
        transform.finalize()
 
491
        # Force the tree to report that it is case insensitive, for conflict
 
492
        # generation tests
 
493
        tree.case_sensitive = False
 
494
        transform = TreeTransform(tree)
 
495
        self.addCleanup(transform.finalize)
 
496
        transform.new_file('file', transform.root, 'content')
 
497
        transform.new_file('FiLe', transform.root, 'content')
 
498
        result = transform.find_conflicts()
 
499
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
 
500
 
 
501
    def test_conflict_on_case_insensitive_existing(self):
 
502
        tree = self.make_branch_and_tree('tree')
 
503
        self.build_tree(['tree/FiLe'])
 
504
        # Don't try this at home, kids!
 
505
        # Force the tree to report that it is case sensitive, for conflict
 
506
        # resolution tests
 
507
        tree.case_sensitive = True
 
508
        transform = TreeTransform(tree)
 
509
        self.addCleanup(transform.finalize)
 
510
        transform.new_file('file', transform.root, 'content')
 
511
        result = transform.find_conflicts()
 
512
        self.assertEqual([], result)
 
513
        transform.finalize()
 
514
        # Force the tree to report that it is case insensitive, for conflict
 
515
        # generation tests
 
516
        tree.case_sensitive = False
 
517
        transform = TreeTransform(tree)
 
518
        self.addCleanup(transform.finalize)
 
519
        transform.new_file('file', transform.root, 'content')
 
520
        result = transform.find_conflicts()
 
521
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
 
522
 
 
523
    def test_resolve_case_insensitive_conflict(self):
 
524
        tree = self.make_branch_and_tree('tree')
 
525
        # Don't try this at home, kids!
 
526
        # Force the tree to report that it is case insensitive, for conflict
 
527
        # resolution tests
 
528
        tree.case_sensitive = False
 
529
        transform = TreeTransform(tree)
 
530
        self.addCleanup(transform.finalize)
 
531
        transform.new_file('file', transform.root, 'content')
 
532
        transform.new_file('FiLe', transform.root, 'content')
 
533
        resolve_conflicts(transform)
 
534
        transform.apply()
 
535
        self.assertPathExists('tree/file')
 
536
        self.assertPathExists('tree/FiLe.moved')
 
537
 
 
538
    def test_resolve_checkout_case_conflict(self):
 
539
        tree = self.make_branch_and_tree('tree')
 
540
        # Don't try this at home, kids!
 
541
        # Force the tree to report that it is case insensitive, for conflict
 
542
        # resolution tests
 
543
        tree.case_sensitive = False
 
544
        transform = TreeTransform(tree)
 
545
        self.addCleanup(transform.finalize)
 
546
        transform.new_file('file', transform.root, 'content')
 
547
        transform.new_file('FiLe', transform.root, 'content')
 
548
        resolve_conflicts(transform,
 
549
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
 
550
        transform.apply()
 
551
        self.assertPathExists('tree/file')
 
552
        self.assertPathExists('tree/FiLe.moved')
 
553
 
 
554
    def test_apply_case_conflict(self):
 
555
        """Ensure that a transform with case conflicts can always be applied"""
 
556
        tree = self.make_branch_and_tree('tree')
 
557
        transform = TreeTransform(tree)
 
558
        self.addCleanup(transform.finalize)
 
559
        transform.new_file('file', transform.root, 'content')
 
560
        transform.new_file('FiLe', transform.root, 'content')
 
561
        dir = transform.new_directory('dir', transform.root)
 
562
        transform.new_file('dirfile', dir, 'content')
 
563
        transform.new_file('dirFiLe', dir, 'content')
 
564
        resolve_conflicts(transform)
 
565
        transform.apply()
 
566
        self.assertPathExists('tree/file')
 
567
        if not os.path.exists('tree/FiLe.moved'):
 
568
            self.assertPathExists('tree/FiLe')
 
569
        self.assertPathExists('tree/dir/dirfile')
 
570
        if not os.path.exists('tree/dir/dirFiLe.moved'):
 
571
            self.assertPathExists('tree/dir/dirFiLe')
 
572
 
 
573
    def test_case_insensitive_limbo(self):
 
574
        tree = self.make_branch_and_tree('tree')
 
575
        # Don't try this at home, kids!
 
576
        # Force the tree to report that it is case insensitive
 
577
        tree.case_sensitive = False
 
578
        transform = TreeTransform(tree)
 
579
        self.addCleanup(transform.finalize)
 
580
        dir = transform.new_directory('dir', transform.root)
 
581
        first = transform.new_file('file', dir, 'content')
 
582
        second = transform.new_file('FiLe', dir, 'content')
 
583
        self.assertContainsRe(transform._limbo_name(first), 'new-1/file')
 
584
        self.assertNotContainsRe(transform._limbo_name(second), 'new-1/FiLe')
 
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
 
220
598
    def test_add_del(self):
221
599
        start, root = self.get_transform()
222
600
        start.new_directory('a', root, 'a')
235
613
        self.addCleanup(unversion.finalize)
236
614
        parent = unversion.trans_id_tree_path('parent')
237
615
        unversion.unversion_file(parent)
238
 
        self.assertEqual(unversion.find_conflicts(), 
 
616
        self.assertEqual(unversion.find_conflicts(),
239
617
                         [('unversioned parent', parent_id)])
240
618
        file_id = unversion.trans_id_tree_file_id('child-id')
241
619
        unversion.unversion_file(file_id)
261
639
        mangle_tree.adjust_path('name2', root, name1)
262
640
        mangle_tree.adjust_path('name1', root, name2)
263
641
 
264
 
        #tests for deleting parent directories 
 
642
        #tests for deleting parent directories
265
643
        ddir = mangle_tree.trans_id_tree_file_id('ddir')
266
644
        mangle_tree.delete_contents(ddir)
267
645
        dfile = mangle_tree.trans_id_tree_file_id('dfile')
296
674
        create_tree,root = self.get_transform()
297
675
        newdir = create_tree.new_directory('selftest', root, 'selftest-id')
298
676
        create_tree.new_file('blackbox.py', newdir, 'hello1', 'blackbox-id')
299
 
        create_tree.apply()        
 
677
        create_tree.apply()
300
678
        mangle_tree,root = self.get_transform()
301
679
        selftest = mangle_tree.trans_id_tree_file_id('selftest-id')
302
680
        blackbox = mangle_tree.trans_id_tree_file_id('blackbox-id')
310
688
        bzrlib = create_tree.new_directory('bzrlib', root, 'bzrlib-id')
311
689
        tests = create_tree.new_directory('tests', bzrlib, 'tests-id')
312
690
        blackbox = create_tree.new_directory('blackbox', tests, 'blackbox-id')
313
 
        create_tree.new_file('test_too_much.py', blackbox, 'hello1', 
 
691
        create_tree.new_file('test_too_much.py', blackbox, 'hello1',
314
692
                             'test_too_much-id')
315
 
        create_tree.apply()        
 
693
        create_tree.apply()
316
694
        mangle_tree,root = self.get_transform()
317
695
        bzrlib = mangle_tree.trans_id_tree_file_id('bzrlib-id')
318
696
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
319
697
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
320
698
        mangle_tree.adjust_path('selftest', bzrlib, tests)
321
 
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much) 
 
699
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
322
700
        mangle_tree.set_executability(True, test_too_much)
323
701
        mangle_tree.apply()
324
702
 
325
703
    def test_both_rename3(self):
326
704
        create_tree,root = self.get_transform()
327
705
        tests = create_tree.new_directory('tests', root, 'tests-id')
328
 
        create_tree.new_file('test_too_much.py', tests, 'hello1', 
 
706
        create_tree.new_file('test_too_much.py', tests, 'hello1',
329
707
                             'test_too_much-id')
330
 
        create_tree.apply()        
 
708
        create_tree.apply()
331
709
        mangle_tree,root = self.get_transform()
332
710
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
333
711
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
334
712
        mangle_tree.adjust_path('selftest', root, tests)
335
 
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much) 
 
713
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
336
714
        mangle_tree.set_executability(True, test_too_much)
337
715
        mangle_tree.apply()
338
716
 
351
729
        newdir = move_id.new_directory('dir', root, 'newdir')
352
730
        move_id.adjust_path('name2', newdir, name1)
353
731
        move_id.apply()
354
 
        
 
732
 
355
733
    def test_replace_dangling_ie(self):
356
734
        create_tree, root = self.get_transform()
357
735
        # prepare tree
373
751
        resolve_conflicts(replace)
374
752
        replace.apply()
375
753
 
376
 
    def test_symlinks(self):
377
 
        if not has_symlinks():
378
 
            raise TestSkipped('Symlinks are not supported on this platform')
379
 
        transform,root = self.get_transform()
 
754
    def _test_symlinks(self, link_name1,link_target1,
 
755
                       link_name2, link_target2):
 
756
 
 
757
        def ozpath(p): return 'oz/' + p
 
758
 
 
759
        self.requireFeature(SymlinkFeature)
 
760
        transform, root = self.get_transform()
380
761
        oz_id = transform.new_directory('oz', root, 'oz-id')
381
 
        wizard = transform.new_symlink('wizard', oz_id, 'wizard-target', 
 
762
        wizard = transform.new_symlink(link_name1, oz_id, link_target1,
382
763
                                       'wizard-id')
383
 
        wiz_id = transform.create_path('wizard2', oz_id)
384
 
        transform.create_symlink('behind_curtain', wiz_id)
385
 
        transform.version_file('wiz-id2', wiz_id)            
 
764
        wiz_id = transform.create_path(link_name2, oz_id)
 
765
        transform.create_symlink(link_target2, wiz_id)
 
766
        transform.version_file('wiz-id2', wiz_id)
386
767
        transform.set_executability(True, wiz_id)
387
 
        self.assertEqual(transform.find_conflicts(), 
 
768
        self.assertEqual(transform.find_conflicts(),
388
769
                         [('non-file executability', wiz_id)])
389
770
        transform.set_executability(None, wiz_id)
390
771
        transform.apply()
391
 
        self.assertEqual(self.wt.path2id('oz/wizard'), 'wizard-id')
392
 
        self.assertEqual(file_kind(self.wt.abspath('oz/wizard')), 'symlink')
393
 
        self.assertEqual(os.readlink(self.wt.abspath('oz/wizard2')), 
394
 
                         'behind_curtain')
395
 
        self.assertEqual(os.readlink(self.wt.abspath('oz/wizard')),
396
 
                         'wizard-target')
 
772
        self.assertEqual(self.wt.path2id(ozpath(link_name1)), 'wizard-id')
 
773
        self.assertEqual('symlink',
 
774
                         file_kind(self.wt.abspath(ozpath(link_name1))))
 
775
        self.assertEqual(link_target2,
 
776
                         osutils.readlink(self.wt.abspath(ozpath(link_name2))))
 
777
        self.assertEqual(link_target1,
 
778
                         osutils.readlink(self.wt.abspath(ozpath(link_name1))))
 
779
 
 
780
    def test_symlinks(self):
 
781
        self._test_symlinks('wizard', 'wizard-target',
 
782
                            'wizard2', 'behind_curtain')
 
783
 
 
784
    def test_symlinks_unicode(self):
 
785
        self.requireFeature(features.UnicodeFilenameFeature)
 
786
        self._test_symlinks(u'\N{Euro Sign}wizard',
 
787
                            u'wizard-targ\N{Euro Sign}t',
 
788
                            u'\N{Euro Sign}wizard2',
 
789
                            u'b\N{Euro Sign}hind_curtain')
 
790
 
 
791
    def test_unable_create_symlink(self):
 
792
        def tt_helper():
 
793
            wt = self.make_branch_and_tree('.')
 
794
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
 
795
            try:
 
796
                tt.new_symlink('foo', tt.root, 'bar')
 
797
                tt.apply()
 
798
            finally:
 
799
                wt.unlock()
 
800
        os_symlink = getattr(os, 'symlink', None)
 
801
        os.symlink = None
 
802
        try:
 
803
            err = self.assertRaises(errors.UnableCreateSymlink, tt_helper)
 
804
            self.assertEquals(
 
805
                "Unable to create symlink 'foo' on this platform",
 
806
                str(err))
 
807
        finally:
 
808
            if os_symlink:
 
809
                os.symlink = os_symlink
397
810
 
398
811
    def get_conflicted(self):
399
812
        create,root = self.get_transform()
403
816
        create.apply()
404
817
        conflicts,root = self.get_transform()
405
818
        # set up duplicate entry, duplicate id
406
 
        new_dorothy = conflicts.new_file('dorothy', root, 'dorothy', 
 
819
        new_dorothy = conflicts.new_file('dorothy', root, 'dorothy',
407
820
                                         'dorothy-id')
408
821
        old_dorothy = conflicts.trans_id_tree_file_id('dorothy-id')
409
822
        oz = conflicts.trans_id_tree_file_id('oz-id')
433
846
        tt, emerald, oz, old_dorothy, new_dorothy = self.get_conflicted()
434
847
        raw_conflicts = resolve_conflicts(tt)
435
848
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
436
 
        duplicate = DuplicateEntry('Moved existing file to', 'dorothy.moved', 
 
849
        duplicate = DuplicateEntry('Moved existing file to', 'dorothy.moved',
437
850
                                   'dorothy', None, 'dorothy-id')
438
851
        self.assertEqual(cooked_conflicts[0], duplicate)
439
 
        duplicate_id = DuplicateID('Unversioned existing file', 
 
852
        duplicate_id = DuplicateID('Unversioned existing file',
440
853
                                   'dorothy.moved', 'dorothy', None,
441
854
                                   'dorothy-id')
442
855
        self.assertEqual(cooked_conflicts[1], duplicate_id)
450
863
        unversioned_parent2 = UnversionedParent('Versioned directory', 'oz',
451
864
                                               'oz-id')
452
865
        self.assertEqual(cooked_conflicts[3], unversioned_parent)
453
 
        parent_loop = ParentLoop('Cancelled move', 'oz/emeraldcity', 
 
866
        parent_loop = ParentLoop('Cancelled move', 'oz/emeraldcity',
454
867
                                 'oz/emeraldcity', 'emerald-id', 'emerald-id')
455
868
        self.assertEqual(cooked_conflicts[4], deleted_parent)
456
869
        self.assertEqual(cooked_conflicts[5], unversioned_parent2)
463
876
        raw_conflicts = resolve_conflicts(tt)
464
877
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
465
878
        tt.finalize()
466
 
        conflicts_s = [str(c) for c in cooked_conflicts]
 
879
        conflicts_s = [unicode(c) for c in cooked_conflicts]
467
880
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
468
881
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
469
882
                                         'Moved existing file to '
482
895
                                         ' versioned, but has versioned'
483
896
                                         ' children.  Versioned directory.')
484
897
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
485
 
                                         ' oz/emeraldcity.  Cancelled move.')
 
898
                                         ' oz/emeraldcity. Cancelled move.')
 
899
 
 
900
    def prepare_wrong_parent_kind(self):
 
901
        tt, root = self.get_transform()
 
902
        tt.new_file('parent', root, 'contents', 'parent-id')
 
903
        tt.apply()
 
904
        tt, root = self.get_transform()
 
905
        parent_id = tt.trans_id_file_id('parent-id')
 
906
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
 
907
        return tt
 
908
 
 
909
    def test_find_conflicts_wrong_parent_kind(self):
 
910
        tt = self.prepare_wrong_parent_kind()
 
911
        tt.find_conflicts()
 
912
 
 
913
    def test_resolve_conflicts_wrong_existing_parent_kind(self):
 
914
        tt = self.prepare_wrong_parent_kind()
 
915
        raw_conflicts = resolve_conflicts(tt)
 
916
        self.assertEqual(set([('non-directory parent', 'Created directory',
 
917
                         'new-3')]), raw_conflicts)
 
918
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
 
919
        self.assertEqual([NonDirectoryParent('Created directory', 'parent.new',
 
920
        'parent-id')], cooked_conflicts)
 
921
        tt.apply()
 
922
        self.assertEqual(None, self.wt.path2id('parent'))
 
923
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
 
924
 
 
925
    def test_resolve_conflicts_wrong_new_parent_kind(self):
 
926
        tt, root = self.get_transform()
 
927
        parent_id = tt.new_directory('parent', root, 'parent-id')
 
928
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
 
929
        tt.apply()
 
930
        tt, root = self.get_transform()
 
931
        parent_id = tt.trans_id_file_id('parent-id')
 
932
        tt.delete_contents(parent_id)
 
933
        tt.create_file('contents', parent_id)
 
934
        raw_conflicts = resolve_conflicts(tt)
 
935
        self.assertEqual(set([('non-directory parent', 'Created directory',
 
936
                         'new-3')]), raw_conflicts)
 
937
        tt.apply()
 
938
        self.assertEqual(None, self.wt.path2id('parent'))
 
939
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
 
940
 
 
941
    def test_resolve_conflicts_wrong_parent_kind_unversioned(self):
 
942
        tt, root = self.get_transform()
 
943
        parent_id = tt.new_directory('parent', root)
 
944
        tt.new_file('child,', parent_id, 'contents2')
 
945
        tt.apply()
 
946
        tt, root = self.get_transform()
 
947
        parent_id = tt.trans_id_tree_path('parent')
 
948
        tt.delete_contents(parent_id)
 
949
        tt.create_file('contents', parent_id)
 
950
        resolve_conflicts(tt)
 
951
        tt.apply()
 
952
        self.assertIs(None, self.wt.path2id('parent'))
 
953
        self.assertIs(None, self.wt.path2id('parent.new'))
 
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)
486
969
 
487
970
    def test_moving_versioned_directories(self):
488
971
        create, root = self.get_transform()
504
987
        create.apply()
505
988
        transform, root = self.get_transform()
506
989
        transform.adjust_root_path('oldroot', fun)
507
 
        new_root=transform.trans_id_tree_path('')
 
990
        new_root = transform.trans_id_tree_path('')
508
991
        transform.version_file('new-root', new_root)
509
992
        transform.apply()
510
993
 
522
1005
        rename.set_executability(True, myfile)
523
1006
        rename.apply()
524
1007
 
525
 
    def test_find_interesting(self):
526
 
        create, root = self.get_transform()
527
 
        wt = create._tree
528
 
        create.new_file('vfile', root, 'myfile-text', 'myfile-id')
529
 
        create.new_file('uvfile', root, 'othertext')
 
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')
530
1015
        create.apply()
531
 
        result = self.applyDeprecated(symbol_versioning.zero_fifteen,
532
 
            find_interesting, wt, wt, ['vfile'])
533
 
        self.assertEqual(result, set(['myfile-id']))
 
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")
534
1045
 
535
1046
    def test_set_executability_order(self):
536
1047
        """Ensure that executability behaves the same, no matter what order.
537
 
        
 
1048
 
538
1049
        - create file and set executability simultaneously
539
1050
        - create file and set executability afterward
540
1051
        - unsetting the executability of a file whose executability has not been
543
1054
        """
544
1055
        transform, root = self.get_transform()
545
1056
        wt = transform._tree
 
1057
        wt.lock_read()
 
1058
        self.addCleanup(wt.unlock)
546
1059
        transform.new_file('set_on_creation', root, 'Set on creation', 'soc',
547
1060
                           True)
548
1061
        sac = transform.new_file('set_after_creation', root,
562
1075
        transform, root = self.get_transform()
563
1076
        transform.new_file('file1', root, 'contents', 'file1-id', True)
564
1077
        transform.apply()
 
1078
        self.wt.lock_write()
 
1079
        self.addCleanup(self.wt.unlock)
565
1080
        self.assertTrue(self.wt.is_executable('file1-id'))
566
1081
        transform, root = self.get_transform()
567
1082
        file1_id = transform.trans_id_tree_file_id('file1-id')
607
1122
        transform.apply()
608
1123
        transform, root = self.get_transform()
609
1124
        try:
610
 
            self.assertEqual([], list(transform._iter_changes()))
 
1125
            self.assertEqual([], list(transform.iter_changes()))
611
1126
            old = transform.trans_id_tree_file_id('id-1')
612
1127
            transform.unversion_file(old)
613
1128
            self.assertEqual([('id-1', ('old', None), False, (True, False),
614
1129
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
615
 
                (True, True))], list(transform._iter_changes()))
 
1130
                (True, True))], list(transform.iter_changes()))
616
1131
            transform.new_directory('new', root, 'id-1')
617
1132
            self.assertEqual([('id-1', ('old', 'new'), True, (True, True),
618
1133
                ('eert_toor', 'eert_toor'), ('old', 'new'),
619
1134
                ('file', 'directory'),
620
 
                (True, False))], list(transform._iter_changes()))
 
1135
                (True, False))], list(transform.iter_changes()))
621
1136
        finally:
622
1137
            transform.finalize()
623
1138
 
632
1147
            transform.version_file('id-1', old)
633
1148
            self.assertEqual([('id-1', (None, 'old'), False, (False, True),
634
1149
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
635
 
                (False, False))], list(transform._iter_changes()))
 
1150
                (False, False))], list(transform.iter_changes()))
636
1151
        finally:
637
1152
            transform.finalize()
638
1153
 
648
1163
            old = transform.trans_id_tree_path('old')
649
1164
            subdir = transform.trans_id_tree_file_id('subdir-id')
650
1165
            new = transform.trans_id_tree_path('new')
651
 
            self.assertEqual([], list(transform._iter_changes()))
 
1166
            self.assertEqual([], list(transform.iter_changes()))
652
1167
 
653
1168
            #content deletion
654
1169
            transform.delete_contents(old)
655
1170
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
656
1171
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', None),
657
 
                (False, False))], list(transform._iter_changes()))
 
1172
                (False, False))], list(transform.iter_changes()))
658
1173
 
659
1174
            #content change
660
1175
            transform.create_file('blah', old)
661
1176
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
662
1177
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
663
 
                (False, False))], list(transform._iter_changes()))
 
1178
                (False, False))], list(transform.iter_changes()))
664
1179
            transform.cancel_deletion(old)
665
1180
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
666
1181
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
667
 
                (False, False))], list(transform._iter_changes()))
 
1182
                (False, False))], list(transform.iter_changes()))
668
1183
            transform.cancel_creation(old)
669
1184
 
670
1185
            # move file_id to a different file
671
 
            self.assertEqual([], list(transform._iter_changes()))
 
1186
            self.assertEqual([], list(transform.iter_changes()))
672
1187
            transform.unversion_file(old)
673
1188
            transform.version_file('id-1', new)
674
1189
            transform.adjust_path('old', root, new)
675
1190
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
676
1191
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
677
 
                (False, False))], list(transform._iter_changes()))
 
1192
                (False, False))], list(transform.iter_changes()))
678
1193
            transform.cancel_versioning(new)
679
1194
            transform._removed_id = set()
680
1195
 
681
1196
            #execute bit
682
 
            self.assertEqual([], list(transform._iter_changes()))
 
1197
            self.assertEqual([], list(transform.iter_changes()))
683
1198
            transform.set_executability(True, old)
684
1199
            self.assertEqual([('id-1', ('old', 'old'), False, (True, True),
685
1200
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
686
 
                (False, True))], list(transform._iter_changes()))
 
1201
                (False, True))], list(transform.iter_changes()))
687
1202
            transform.set_executability(None, old)
688
1203
 
689
1204
            # filename
690
 
            self.assertEqual([], list(transform._iter_changes()))
 
1205
            self.assertEqual([], list(transform.iter_changes()))
691
1206
            transform.adjust_path('new', root, old)
692
1207
            transform._new_parent = {}
693
1208
            self.assertEqual([('id-1', ('old', 'new'), False, (True, True),
694
1209
                ('eert_toor', 'eert_toor'), ('old', 'new'), ('file', 'file'),
695
 
                (False, False))], list(transform._iter_changes()))
 
1210
                (False, False))], list(transform.iter_changes()))
696
1211
            transform._new_name = {}
697
1212
 
698
1213
            # parent directory
699
 
            self.assertEqual([], list(transform._iter_changes()))
 
1214
            self.assertEqual([], list(transform.iter_changes()))
700
1215
            transform.adjust_path('new', subdir, old)
701
1216
            transform._new_name = {}
702
1217
            self.assertEqual([('id-1', ('old', 'subdir/old'), False,
703
1218
                (True, True), ('eert_toor', 'subdir-id'), ('old', 'old'),
704
1219
                ('file', 'file'), (False, False))],
705
 
                list(transform._iter_changes()))
 
1220
                list(transform.iter_changes()))
706
1221
            transform._new_path = {}
707
1222
 
708
1223
        finally:
730
1245
                ('id-2', (u'file2', u'file2'), False, (True, True),
731
1246
                ('eert_toor', 'eert_toor'), ('file2', u'file2'),
732
1247
                ('file', 'file'), (False, True))],
733
 
                list(transform._iter_changes()))
 
1248
                list(transform.iter_changes()))
734
1249
        finally:
735
1250
            transform.finalize()
736
1251
 
750
1265
            transform.adjust_path('flitter', root, floater)
751
1266
            self.assertEqual([('floater-id', ('floater', 'flitter'), False,
752
1267
            (True, True), ('toor_eert', 'toor_eert'), ('floater', 'flitter'),
753
 
            (None, None), (False, False))], list(transform._iter_changes()))
 
1268
            (None, None), (False, False))], list(transform.iter_changes()))
754
1269
        finally:
755
1270
            transform.finalize()
756
1271
 
765
1280
        try:
766
1281
            old = transform.trans_id_tree_path('old')
767
1282
            subdir = transform.trans_id_tree_file_id('subdir-id')
768
 
            self.assertEqual([], list(transform._iter_changes()))
 
1283
            self.assertEqual([], list(transform.iter_changes()))
769
1284
            transform.delete_contents(subdir)
770
1285
            transform.create_directory(subdir)
771
1286
            transform.set_executability(False, old)
772
1287
            transform.unversion_file(old)
773
1288
            transform.version_file('id-1', old)
774
1289
            transform.adjust_path('old', root, old)
775
 
            self.assertEqual([], list(transform._iter_changes()))
 
1290
            self.assertEqual([], list(transform.iter_changes()))
776
1291
        finally:
777
1292
            transform.finalize()
778
1293
 
805
1320
        parent2 = transform.new_directory('parent2', root)
806
1321
        transform.adjust_path('child1', parent2, child1)
807
1322
        transform.apply()
808
 
        self.failIfExists(self.wt.abspath('parent1/child1'))
809
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1323
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
 
1324
        self.assertPathExists(self.wt.abspath('parent2/child1'))
810
1325
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
811
1326
        # no rename for child1 (counting only renames during apply)
812
 
        self.failUnlessEqual(2, transform.rename_count)
 
1327
        self.assertEqual(2, transform.rename_count)
813
1328
 
814
1329
    def test_cancel_parent(self):
815
1330
        """Cancelling a parent doesn't cause deletion of a non-empty directory
838
1353
        parent2 = transform.new_directory('parent2', root)
839
1354
        transform.adjust_path('child1', parent2, child1)
840
1355
        transform.apply()
841
 
        self.failIfExists(self.wt.abspath('parent1'))
842
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1356
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
 
1357
        self.assertPathExists(self.wt.abspath('parent2/child1'))
843
1358
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
844
 
        self.failUnlessEqual(2, transform.rename_count)
 
1359
        self.assertEqual(2, transform.rename_count)
845
1360
 
846
1361
    def test_adjust_and_cancel(self):
847
1362
        """Make sure adjust_path keeps track of limbo children properly"""
880
1395
        child = transform.new_directory('child', parent)
881
1396
        transform.adjust_path('parent', root, parent)
882
1397
        transform.apply()
883
 
        self.failUnlessExists(self.wt.abspath('parent/child'))
 
1398
        self.assertPathExists(self.wt.abspath('parent/child'))
884
1399
        self.assertEqual(1, transform.rename_count)
885
1400
 
886
1401
    def test_reuse_name(self):
943
1458
        transform.cancel_creation(parent)
944
1459
        transform.finalize()
945
1460
 
946
 
    def test_change_entry(self):
947
 
        txt = 'bzrlib.transform.change_entry was deprecated in version 0.19.'
948
 
        self.callDeprecated([txt], change_entry, None, None, None, None, None,
949
 
            None, None, None)
 
1461
    def test_rollback_on_directory_clash(self):
 
1462
        def tt_helper():
 
1463
            wt = self.make_branch_and_tree('.')
 
1464
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
 
1465
            try:
 
1466
                foo = tt.new_directory('foo', tt.root)
 
1467
                tt.new_file('bar', foo, 'foobar')
 
1468
                baz = tt.new_directory('baz', tt.root)
 
1469
                tt.new_file('qux', baz, 'quux')
 
1470
                # Ask for a rename 'foo' -> 'baz'
 
1471
                tt.adjust_path('baz', tt.root, foo)
 
1472
                # Lie to tt that we've already resolved all conflicts.
 
1473
                tt.apply(no_conflicts=True)
 
1474
            except:
 
1475
                wt.unlock()
 
1476
                raise
 
1477
        # The rename will fail because the target directory is not empty (but
 
1478
        # raises FileExists anyway).
 
1479
        err = self.assertRaises(errors.FileExists, tt_helper)
 
1480
        self.assertEndsWith(err.path, "/baz")
 
1481
 
 
1482
    def test_two_directories_clash(self):
 
1483
        def tt_helper():
 
1484
            wt = self.make_branch_and_tree('.')
 
1485
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
 
1486
            try:
 
1487
                foo_1 = tt.new_directory('foo', tt.root)
 
1488
                tt.new_directory('bar', foo_1)
 
1489
                # Adding the same directory with a different content
 
1490
                foo_2 = tt.new_directory('foo', tt.root)
 
1491
                tt.new_directory('baz', foo_2)
 
1492
                # Lie to tt that we've already resolved all conflicts.
 
1493
                tt.apply(no_conflicts=True)
 
1494
            except:
 
1495
                wt.unlock()
 
1496
                raise
 
1497
        err = self.assertRaises(errors.FileExists, tt_helper)
 
1498
        self.assertEndsWith(err.path, "/foo")
 
1499
 
 
1500
    def test_two_directories_clash_finalize(self):
 
1501
        def tt_helper():
 
1502
            wt = self.make_branch_and_tree('.')
 
1503
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
 
1504
            try:
 
1505
                foo_1 = tt.new_directory('foo', tt.root)
 
1506
                tt.new_directory('bar', foo_1)
 
1507
                # Adding the same directory with a different content
 
1508
                foo_2 = tt.new_directory('foo', tt.root)
 
1509
                tt.new_directory('baz', foo_2)
 
1510
                # Lie to tt that we've already resolved all conflicts.
 
1511
                tt.apply(no_conflicts=True)
 
1512
            except:
 
1513
                tt.finalize()
 
1514
                raise
 
1515
        err = self.assertRaises(errors.FileExists, tt_helper)
 
1516
        self.assertEndsWith(err.path, "/foo")
 
1517
 
 
1518
    def test_file_to_directory(self):
 
1519
        wt = self.make_branch_and_tree('.')
 
1520
        self.build_tree(['foo'])
 
1521
        wt.add(['foo'])
 
1522
        wt.commit("one")
 
1523
        tt = TreeTransform(wt)
 
1524
        self.addCleanup(tt.finalize)
 
1525
        foo_trans_id = tt.trans_id_tree_path("foo")
 
1526
        tt.delete_contents(foo_trans_id)
 
1527
        tt.create_directory(foo_trans_id)
 
1528
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
 
1529
        tt.create_file(["aa\n"], bar_trans_id)
 
1530
        tt.version_file("bar-1", bar_trans_id)
 
1531
        tt.apply()
 
1532
        self.assertPathExists("foo/bar")
 
1533
        wt.lock_read()
 
1534
        try:
 
1535
            self.assertEqual(wt.kind(wt.path2id("foo")), "directory")
 
1536
        finally:
 
1537
            wt.unlock()
 
1538
        wt.commit("two")
 
1539
        changes = wt.changes_from(wt.basis_tree())
 
1540
        self.assertFalse(changes.has_changed(), changes)
 
1541
 
 
1542
    def test_file_to_symlink(self):
 
1543
        self.requireFeature(SymlinkFeature)
 
1544
        wt = self.make_branch_and_tree('.')
 
1545
        self.build_tree(['foo'])
 
1546
        wt.add(['foo'])
 
1547
        wt.commit("one")
 
1548
        tt = TreeTransform(wt)
 
1549
        self.addCleanup(tt.finalize)
 
1550
        foo_trans_id = tt.trans_id_tree_path("foo")
 
1551
        tt.delete_contents(foo_trans_id)
 
1552
        tt.create_symlink("bar", foo_trans_id)
 
1553
        tt.apply()
 
1554
        self.assertPathExists("foo")
 
1555
        wt.lock_read()
 
1556
        self.addCleanup(wt.unlock)
 
1557
        self.assertEqual(wt.kind(wt.path2id("foo")), "symlink")
 
1558
 
 
1559
    def test_dir_to_file(self):
 
1560
        wt = self.make_branch_and_tree('.')
 
1561
        self.build_tree(['foo/', 'foo/bar'])
 
1562
        wt.add(['foo', 'foo/bar'])
 
1563
        wt.commit("one")
 
1564
        tt = TreeTransform(wt)
 
1565
        self.addCleanup(tt.finalize)
 
1566
        foo_trans_id = tt.trans_id_tree_path("foo")
 
1567
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
 
1568
        tt.delete_contents(foo_trans_id)
 
1569
        tt.delete_versioned(bar_trans_id)
 
1570
        tt.create_file(["aa\n"], foo_trans_id)
 
1571
        tt.apply()
 
1572
        self.assertPathExists("foo")
 
1573
        wt.lock_read()
 
1574
        self.addCleanup(wt.unlock)
 
1575
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
 
1576
 
 
1577
    def test_dir_to_hardlink(self):
 
1578
        self.requireFeature(HardlinkFeature)
 
1579
        wt = self.make_branch_and_tree('.')
 
1580
        self.build_tree(['foo/', 'foo/bar'])
 
1581
        wt.add(['foo', 'foo/bar'])
 
1582
        wt.commit("one")
 
1583
        tt = TreeTransform(wt)
 
1584
        self.addCleanup(tt.finalize)
 
1585
        foo_trans_id = tt.trans_id_tree_path("foo")
 
1586
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
 
1587
        tt.delete_contents(foo_trans_id)
 
1588
        tt.delete_versioned(bar_trans_id)
 
1589
        self.build_tree(['baz'])
 
1590
        tt.create_hardlink("baz", foo_trans_id)
 
1591
        tt.apply()
 
1592
        self.assertPathExists("foo")
 
1593
        self.assertPathExists("baz")
 
1594
        wt.lock_read()
 
1595
        self.addCleanup(wt.unlock)
 
1596
        self.assertEqual(wt.kind(wt.path2id("foo")), "file")
 
1597
 
 
1598
    def test_no_final_path(self):
 
1599
        transform, root = self.get_transform()
 
1600
        trans_id = transform.trans_id_file_id('foo')
 
1601
        transform.create_file('bar', trans_id)
 
1602
        transform.cancel_creation(trans_id)
 
1603
        transform.apply()
 
1604
 
 
1605
    def test_create_from_tree(self):
 
1606
        tree1 = self.make_branch_and_tree('tree1')
 
1607
        self.build_tree_contents([('tree1/foo/',), ('tree1/bar', 'baz')])
 
1608
        tree1.add(['foo', 'bar'], ['foo-id', 'bar-id'])
 
1609
        tree2 = self.make_branch_and_tree('tree2')
 
1610
        tt = TreeTransform(tree2)
 
1611
        foo_trans_id = tt.create_path('foo', tt.root)
 
1612
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
 
1613
        bar_trans_id = tt.create_path('bar', tt.root)
 
1614
        create_from_tree(tt, bar_trans_id, tree1, 'bar-id')
 
1615
        tt.apply()
 
1616
        self.assertEqual('directory', osutils.file_kind('tree2/foo'))
 
1617
        self.assertFileEqual('baz', 'tree2/bar')
 
1618
 
 
1619
    def test_create_from_tree_bytes(self):
 
1620
        """Provided lines are used instead of tree content."""
 
1621
        tree1 = self.make_branch_and_tree('tree1')
 
1622
        self.build_tree_contents([('tree1/foo', 'bar'),])
 
1623
        tree1.add('foo', 'foo-id')
 
1624
        tree2 = self.make_branch_and_tree('tree2')
 
1625
        tt = TreeTransform(tree2)
 
1626
        foo_trans_id = tt.create_path('foo', tt.root)
 
1627
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id', bytes='qux')
 
1628
        tt.apply()
 
1629
        self.assertFileEqual('qux', 'tree2/foo')
 
1630
 
 
1631
    def test_create_from_tree_symlink(self):
 
1632
        self.requireFeature(SymlinkFeature)
 
1633
        tree1 = self.make_branch_and_tree('tree1')
 
1634
        os.symlink('bar', 'tree1/foo')
 
1635
        tree1.add('foo', 'foo-id')
 
1636
        tt = TreeTransform(self.make_branch_and_tree('tree2'))
 
1637
        foo_trans_id = tt.create_path('foo', tt.root)
 
1638
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
 
1639
        tt.apply()
 
1640
        self.assertEqual('bar', os.readlink('tree2/foo'))
950
1641
 
951
1642
 
952
1643
class TransformGroup(object):
 
1644
 
953
1645
    def __init__(self, dirname, root_id):
954
1646
        self.name = dirname
955
1647
        os.mkdir(dirname)
956
 
        self.wt = BzrDir.create_standalone_workingtree(dirname)
 
1648
        self.wt = ControlDir.create_standalone_workingtree(dirname)
957
1649
        self.wt.set_root_id(root_id)
958
1650
        self.b = self.wt.branch
959
1651
        self.tt = TreeTransform(self.wt)
965
1657
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
966
1658
 
967
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
 
968
1692
class TestTransformMerge(TestCaseInTempDir):
 
1693
 
969
1694
    def test_text_merge(self):
970
1695
        root_id = generate_ids.gen_root_id()
971
1696
        base = TransformGroup("base", root_id)
1001
1726
        this.tt.new_file('i', this.root, '1\n2\n3\n4\n', 'i')
1002
1727
        this.tt.apply()
1003
1728
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
 
1729
 
1004
1730
        # textual merge
1005
1731
        self.assertEqual(this.wt.get_file('a').read(), 'y\nb\nc\nd\bz\n')
1006
1732
        # three-way text conflict
1007
 
        self.assertEqual(this.wt.get_file('b').read(), 
 
1733
        self.assertEqual(this.wt.get_file('b').read(),
1008
1734
                         conflict_text('b', 'b2'))
1009
1735
        # OTHER wins
1010
1736
        self.assertEqual(this.wt.get_file('c').read(), 'c2')
1014
1740
        self.assertEqual(this.wt.get_file('e').read(), 'e2')
1015
1741
        # No change
1016
1742
        self.assertEqual(this.wt.get_file('f').read(), 'f')
1017
 
        # Correct correct results when THIS == OTHER 
 
1743
        # Correct correct results when THIS == OTHER
1018
1744
        self.assertEqual(this.wt.get_file('g').read(), 'g')
1019
1745
        # Text conflict when THIS & OTHER are text and BASE is dir
1020
 
        self.assertEqual(this.wt.get_file('h').read(), 
 
1746
        self.assertEqual(this.wt.get_file('h').read(),
1021
1747
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1022
1748
        self.assertEqual(this.wt.get_file_byname('h.THIS').read(),
1023
1749
                         '1\n2\n3\n4\n')
1024
1750
        self.assertEqual(this.wt.get_file_byname('h.OTHER').read(),
1025
1751
                         'h\ni\nj\nk\n')
1026
1752
        self.assertEqual(file_kind(this.wt.abspath('h.BASE')), 'directory')
1027
 
        self.assertEqual(this.wt.get_file('i').read(), 
 
1753
        self.assertEqual(this.wt.get_file('i').read(),
1028
1754
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1029
1755
        self.assertEqual(this.wt.get_file_byname('i.THIS').read(),
1030
1756
                         '1\n2\n3\n4\n')
1035
1761
        merge_modified = this.wt.merge_modified()
1036
1762
        self.assertSubset(merge_modified, modified)
1037
1763
        self.assertEqual(len(merge_modified), len(modified))
1038
 
        file(this.wt.id2abspath('a'), 'wb').write('booga')
 
1764
        with file(this.wt.id2abspath('a'), 'wb') as f: f.write('booga')
1039
1765
        modified.pop(0)
1040
1766
        merge_modified = this.wt.merge_modified()
1041
1767
        self.assertSubset(merge_modified, modified)
1042
1768
        self.assertEqual(len(merge_modified), len(modified))
1043
1769
        this.wt.remove('b')
1044
 
        this.wt.revert([])
 
1770
        this.wt.revert()
1045
1771
 
1046
1772
    def test_file_merge(self):
1047
 
        if not has_symlinks():
1048
 
            raise TestSkipped('Symlinks are not supported on this platform')
 
1773
        self.requireFeature(SymlinkFeature)
1049
1774
        root_id = generate_ids.gen_root_id()
1050
1775
        base = TransformGroup("BASE", root_id)
1051
1776
        this = TransformGroup("THIS", root_id)
1055
1780
            tg.tt.new_symlink('b', tg.root, 'b', 'b')
1056
1781
            tg.tt.new_file('c', tg.root, 'c', 'c')
1057
1782
            tg.tt.new_symlink('d', tg.root, tg.name, 'd')
1058
 
        targets = ((base, 'base-e', 'base-f', None, None), 
1059
 
                   (this, 'other-e', 'this-f', 'other-g', 'this-h'), 
 
1783
        targets = ((base, 'base-e', 'base-f', None, None),
 
1784
                   (this, 'other-e', 'this-f', 'other-g', 'this-h'),
1060
1785
                   (other, 'other-e', None, 'other-g', 'other-h'))
1061
1786
        for tg, e_target, f_target, g_target, h_target in targets:
1062
 
            for link, target in (('e', e_target), ('f', f_target), 
 
1787
            for link, target in (('e', e_target), ('f', f_target),
1063
1788
                                 ('g', g_target), ('h', h_target)):
1064
1789
                if target is not None:
1065
1790
                    tg.tt.new_symlink(link, tg.root, target, link)
1091
1816
        base = TransformGroup("BASE", root_id)
1092
1817
        this = TransformGroup("THIS", root_id)
1093
1818
        other = TransformGroup("OTHER", root_id)
1094
 
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a') 
 
1819
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1095
1820
                                   for t in [base, this, other]]
1096
 
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b') 
 
1821
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1097
1822
                                   for t in [base, this, other]]
1098
1823
        base.tt.new_directory('c', base_a, 'c')
1099
1824
        this.tt.new_directory('c1', this_a, 'c')
1124
1849
        base = TransformGroup("BASE", root_id)
1125
1850
        this = TransformGroup("THIS", root_id)
1126
1851
        other = TransformGroup("OTHER", root_id)
1127
 
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a') 
 
1852
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1128
1853
                                   for t in [base, this, other]]
1129
 
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b') 
 
1854
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1130
1855
                                   for t in [base, this, other]]
1131
1856
 
1132
1857
        base.tt.new_file('g', base_a, 'g', 'g')
1153
1878
 
1154
1879
class TestBuildTree(tests.TestCaseWithTransport):
1155
1880
 
1156
 
    def test_build_tree(self):
1157
 
        if not has_symlinks():
1158
 
            raise TestSkipped('Test requires symlink support')
 
1881
    def test_build_tree_with_symlinks(self):
 
1882
        self.requireFeature(SymlinkFeature)
1159
1883
        os.mkdir('a')
1160
 
        a = BzrDir.create_standalone_workingtree('a')
 
1884
        a = ControlDir.create_standalone_workingtree('a')
1161
1885
        os.mkdir('a/foo')
1162
 
        file('a/foo/bar', 'wb').write('contents')
 
1886
        with file('a/foo/bar', 'wb') as f: f.write('contents')
1163
1887
        os.symlink('a/foo/bar', 'a/foo/baz')
1164
1888
        a.add(['foo', 'foo/bar', 'foo/baz'])
1165
1889
        a.commit('initial commit')
1166
 
        b = BzrDir.create_standalone_workingtree('b')
 
1890
        b = ControlDir.create_standalone_workingtree('b')
1167
1891
        basis = a.basis_tree()
1168
1892
        basis.lock_read()
1169
1893
        self.addCleanup(basis.unlock)
1174
1898
 
1175
1899
    def test_build_with_references(self):
1176
1900
        tree = self.make_branch_and_tree('source',
1177
 
            format='dirstate-with-subtree')
 
1901
            format='development-subtree')
1178
1902
        subtree = self.make_branch_and_tree('source/subtree',
1179
 
            format='dirstate-with-subtree')
 
1903
            format='development-subtree')
1180
1904
        tree.add_reference(subtree)
1181
1905
        tree.commit('a revision')
1182
1906
        tree.branch.create_checkout('target')
1183
 
        self.failUnlessExists('target')
1184
 
        self.failUnlessExists('target/subtree')
 
1907
        self.assertPathExists('target')
 
1908
        self.assertPathExists('target/subtree')
1185
1909
 
1186
1910
    def test_file_conflict_handling(self):
1187
1911
        """Ensure that when building trees, conflict handling is done"""
1209
1933
 
1210
1934
    def test_symlink_conflict_handling(self):
1211
1935
        """Ensure that when building trees, conflict handling is done"""
1212
 
        if not has_symlinks():
1213
 
            raise TestSkipped('Test requires symlink support')
 
1936
        self.requireFeature(SymlinkFeature)
1214
1937
        source = self.make_branch_and_tree('source')
1215
1938
        os.symlink('foo', 'source/symlink')
1216
1939
        source.add('symlink', 'new-symlink')
1225
1948
        os.symlink('foo', 'target2/symlink')
1226
1949
        build_tree(source.basis_tree(), target)
1227
1950
        self.assertEqual([], target.conflicts())
1228
 
        
 
1951
 
1229
1952
    def test_directory_conflict_handling(self):
1230
1953
        """Ensure that when building trees, conflict handling is done"""
1231
1954
        source = self.make_branch_and_tree('source')
1235
1958
        source.commit('added file')
1236
1959
        build_tree(source.basis_tree(), target)
1237
1960
        self.assertEqual([], target.conflicts())
1238
 
        self.failUnlessExists('target/dir1/file')
 
1961
        self.assertPathExists('target/dir1/file')
1239
1962
 
1240
1963
        # Ensure contents are merged
1241
1964
        target = self.make_branch_and_tree('target2')
1242
1965
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1243
1966
        build_tree(source.basis_tree(), target)
1244
1967
        self.assertEqual([], target.conflicts())
1245
 
        self.failUnlessExists('target2/dir1/file2')
1246
 
        self.failUnlessExists('target2/dir1/file')
 
1968
        self.assertPathExists('target2/dir1/file2')
 
1969
        self.assertPathExists('target2/dir1/file')
1247
1970
 
1248
1971
        # Ensure new contents are suppressed for existing branches
1249
1972
        target = self.make_branch_and_tree('target3')
1250
1973
        self.make_branch('target3/dir1')
1251
1974
        self.build_tree(['target3/dir1/file2'])
1252
1975
        build_tree(source.basis_tree(), target)
1253
 
        self.failIfExists('target3/dir1/file')
1254
 
        self.failUnlessExists('target3/dir1/file2')
1255
 
        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')
1256
1979
        self.assertEqual([DuplicateEntry('Diverted to',
1257
1980
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1258
1981
            target.conflicts())
1261
1984
        self.build_tree(['target4/dir1/'])
1262
1985
        self.make_branch('target4/dir1/file')
1263
1986
        build_tree(source.basis_tree(), target)
1264
 
        self.failUnlessExists('target4/dir1/file')
 
1987
        self.assertPathExists('target4/dir1/file')
1265
1988
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1266
 
        self.failUnlessExists('target4/dir1/file.diverted')
 
1989
        self.assertPathExists('target4/dir1/file.diverted')
1267
1990
        self.assertEqual([DuplicateEntry('Diverted to',
1268
1991
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1269
1992
            target.conflicts())
1287
2010
        target = self.make_branch_and_tree('target')
1288
2011
        self.build_tree(['target/name'])
1289
2012
        target.add('name')
1290
 
        self.assertRaises(errors.WorkingTreeAlreadyPopulated, 
 
2013
        self.assertRaises(errors.WorkingTreeAlreadyPopulated,
1291
2014
            build_tree, source.basis_tree(), target)
1292
2015
 
1293
2016
    def test_build_tree_rename_count(self):
1307
2030
        # children of non-root directories should not be renamed
1308
2031
        self.assertEqual(2, transform_result.rename_count)
1309
2032
 
1310
 
 
1311
 
class MockTransform(object):
1312
 
 
1313
 
    def has_named_child(self, by_parent, parent_id, name):
1314
 
        for child_id in by_parent[parent_id]:
1315
 
            if child_id == '0':
1316
 
                if name == "name~":
1317
 
                    return True
1318
 
            elif name == "name.~%s~" % child_id:
1319
 
                return True
1320
 
        return False
1321
 
 
1322
 
 
1323
 
class MockEntry(object):
1324
 
    def __init__(self):
1325
 
        object.__init__(self)
1326
 
        self.name = "name"
1327
 
 
1328
 
class TestGetBackupName(TestCase):
1329
 
    def test_get_backup_name(self):
1330
 
        tt = MockTransform()
1331
 
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
1332
 
        self.assertEqual(name, 'name.~1~')
1333
 
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
1334
 
        self.assertEqual(name, 'name.~2~')
1335
 
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
1336
 
        self.assertEqual(name, 'name.~1~')
1337
 
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
1338
 
        self.assertEqual(name, 'name.~1~')
1339
 
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
1340
 
        self.assertEqual(name, 'name.~4~')
 
2033
    def create_ab_tree(self):
 
2034
        """Create a committed test tree with two files"""
 
2035
        source = self.make_branch_and_tree('source')
 
2036
        self.build_tree_contents([('source/file1', 'A')])
 
2037
        self.build_tree_contents([('source/file2', 'B')])
 
2038
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
 
2039
        source.commit('commit files')
 
2040
        source.lock_write()
 
2041
        self.addCleanup(source.unlock)
 
2042
        return source
 
2043
 
 
2044
    def test_build_tree_accelerator_tree(self):
 
2045
        source = self.create_ab_tree()
 
2046
        self.build_tree_contents([('source/file2', 'C')])
 
2047
        calls = []
 
2048
        real_source_get_file = source.get_file
 
2049
        def get_file(file_id, path=None):
 
2050
            calls.append(file_id)
 
2051
            return real_source_get_file(file_id, path)
 
2052
        source.get_file = get_file
 
2053
        target = self.make_branch_and_tree('target')
 
2054
        revision_tree = source.basis_tree()
 
2055
        revision_tree.lock_read()
 
2056
        self.addCleanup(revision_tree.unlock)
 
2057
        build_tree(revision_tree, target, source)
 
2058
        self.assertEqual(['file1-id'], calls)
 
2059
        target.lock_read()
 
2060
        self.addCleanup(target.unlock)
 
2061
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
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
 
 
2075
    def test_build_tree_accelerator_tree_missing_file(self):
 
2076
        source = self.create_ab_tree()
 
2077
        os.unlink('source/file1')
 
2078
        source.remove(['file2'])
 
2079
        target = self.make_branch_and_tree('target')
 
2080
        revision_tree = source.basis_tree()
 
2081
        revision_tree.lock_read()
 
2082
        self.addCleanup(revision_tree.unlock)
 
2083
        build_tree(revision_tree, target, source)
 
2084
        target.lock_read()
 
2085
        self.addCleanup(target.unlock)
 
2086
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2087
 
 
2088
    def test_build_tree_accelerator_wrong_kind(self):
 
2089
        self.requireFeature(SymlinkFeature)
 
2090
        source = self.make_branch_and_tree('source')
 
2091
        self.build_tree_contents([('source/file1', '')])
 
2092
        self.build_tree_contents([('source/file2', '')])
 
2093
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
 
2094
        source.commit('commit files')
 
2095
        os.unlink('source/file2')
 
2096
        self.build_tree_contents([('source/file2/', 'C')])
 
2097
        os.unlink('source/file1')
 
2098
        os.symlink('file2', 'source/file1')
 
2099
        calls = []
 
2100
        real_source_get_file = source.get_file
 
2101
        def get_file(file_id, path=None):
 
2102
            calls.append(file_id)
 
2103
            return real_source_get_file(file_id, path)
 
2104
        source.get_file = get_file
 
2105
        target = self.make_branch_and_tree('target')
 
2106
        revision_tree = source.basis_tree()
 
2107
        revision_tree.lock_read()
 
2108
        self.addCleanup(revision_tree.unlock)
 
2109
        build_tree(revision_tree, target, source)
 
2110
        self.assertEqual([], calls)
 
2111
        target.lock_read()
 
2112
        self.addCleanup(target.unlock)
 
2113
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2114
 
 
2115
    def test_build_tree_hardlink(self):
 
2116
        self.requireFeature(HardlinkFeature)
 
2117
        source = self.create_ab_tree()
 
2118
        target = self.make_branch_and_tree('target')
 
2119
        revision_tree = source.basis_tree()
 
2120
        revision_tree.lock_read()
 
2121
        self.addCleanup(revision_tree.unlock)
 
2122
        build_tree(revision_tree, target, source, hardlink=True)
 
2123
        target.lock_read()
 
2124
        self.addCleanup(target.unlock)
 
2125
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2126
        source_stat = os.stat('source/file1')
 
2127
        target_stat = os.stat('target/file1')
 
2128
        self.assertEqual(source_stat, target_stat)
 
2129
 
 
2130
        # Explicitly disallowing hardlinks should prevent them.
 
2131
        target2 = self.make_branch_and_tree('target2')
 
2132
        build_tree(revision_tree, target2, source, hardlink=False)
 
2133
        target2.lock_read()
 
2134
        self.addCleanup(target2.unlock)
 
2135
        self.assertEqual([], list(target2.iter_changes(revision_tree)))
 
2136
        source_stat = os.stat('source/file1')
 
2137
        target2_stat = os.stat('target2/file1')
 
2138
        self.assertNotEqual(source_stat, target2_stat)
 
2139
 
 
2140
    def test_build_tree_accelerator_tree_moved(self):
 
2141
        source = self.make_branch_and_tree('source')
 
2142
        self.build_tree_contents([('source/file1', 'A')])
 
2143
        source.add(['file1'], ['file1-id'])
 
2144
        source.commit('commit files')
 
2145
        source.rename_one('file1', 'file2')
 
2146
        source.lock_read()
 
2147
        self.addCleanup(source.unlock)
 
2148
        target = self.make_branch_and_tree('target')
 
2149
        revision_tree = source.basis_tree()
 
2150
        revision_tree.lock_read()
 
2151
        self.addCleanup(revision_tree.unlock)
 
2152
        build_tree(revision_tree, target, source)
 
2153
        target.lock_read()
 
2154
        self.addCleanup(target.unlock)
 
2155
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2156
 
 
2157
    def test_build_tree_hardlinks_preserve_execute(self):
 
2158
        self.requireFeature(HardlinkFeature)
 
2159
        source = self.create_ab_tree()
 
2160
        tt = TreeTransform(source)
 
2161
        trans_id = tt.trans_id_tree_file_id('file1-id')
 
2162
        tt.set_executability(True, trans_id)
 
2163
        tt.apply()
 
2164
        self.assertTrue(source.is_executable('file1-id'))
 
2165
        target = self.make_branch_and_tree('target')
 
2166
        revision_tree = source.basis_tree()
 
2167
        revision_tree.lock_read()
 
2168
        self.addCleanup(revision_tree.unlock)
 
2169
        build_tree(revision_tree, target, source, hardlink=True)
 
2170
        target.lock_read()
 
2171
        self.addCleanup(target.unlock)
 
2172
        self.assertEqual([], list(target.iter_changes(revision_tree)))
 
2173
        self.assertTrue(source.is_executable('file1-id'))
 
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
 
 
2223
    def test_case_insensitive_build_tree_inventory(self):
 
2224
        if (features.CaseInsensitiveFilesystemFeature.available()
 
2225
            or features.CaseInsCasePresFilenameFeature.available()):
 
2226
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
 
2227
        source = self.make_branch_and_tree('source')
 
2228
        self.build_tree(['source/file', 'source/FILE'])
 
2229
        source.add(['file', 'FILE'], ['lower-id', 'upper-id'])
 
2230
        source.commit('added files')
 
2231
        # Don't try this at home, kids!
 
2232
        # Force the tree to report that it is case insensitive
 
2233
        target = self.make_branch_and_tree('target')
 
2234
        target.case_sensitive = False
 
2235
        build_tree(source.basis_tree(), target, source, delta_from_tree=True)
 
2236
        self.assertEqual('file.moved', target.id2path('lower-id'))
 
2237
        self.assertEqual('FILE', target.id2path('upper-id'))
 
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
 
 
2275
 
 
2276
class TestCommitTransform(tests.TestCaseWithTransport):
 
2277
 
 
2278
    def get_branch(self):
 
2279
        tree = self.make_branch_and_tree('tree')
 
2280
        tree.lock_write()
 
2281
        self.addCleanup(tree.unlock)
 
2282
        tree.commit('empty commit')
 
2283
        return tree.branch
 
2284
 
 
2285
    def get_branch_and_transform(self):
 
2286
        branch = self.get_branch()
 
2287
        tt = TransformPreview(branch.basis_tree())
 
2288
        self.addCleanup(tt.finalize)
 
2289
        return branch, tt
 
2290
 
 
2291
    def test_commit_wrong_basis(self):
 
2292
        branch = self.get_branch()
 
2293
        basis = branch.repository.revision_tree(
 
2294
            _mod_revision.NULL_REVISION)
 
2295
        tt = TransformPreview(basis)
 
2296
        self.addCleanup(tt.finalize)
 
2297
        e = self.assertRaises(ValueError, tt.commit, branch, '')
 
2298
        self.assertEqual('TreeTransform not based on branch basis: null:',
 
2299
                         str(e))
 
2300
 
 
2301
    def test_empy_commit(self):
 
2302
        branch, tt = self.get_branch_and_transform()
 
2303
        rev = tt.commit(branch, 'my message')
 
2304
        self.assertEqual(2, branch.revno())
 
2305
        repo = branch.repository
 
2306
        self.assertEqual('my message', repo.get_revision(rev).message)
 
2307
 
 
2308
    def test_merge_parents(self):
 
2309
        branch, tt = self.get_branch_and_transform()
 
2310
        rev = tt.commit(branch, 'my message', ['rev1b', 'rev1c'])
 
2311
        self.assertEqual(['rev1b', 'rev1c'],
 
2312
                         branch.basis_tree().get_parent_ids()[1:])
 
2313
 
 
2314
    def test_first_commit(self):
 
2315
        branch = self.make_branch('branch')
 
2316
        branch.lock_write()
 
2317
        self.addCleanup(branch.unlock)
 
2318
        tt = TransformPreview(branch.basis_tree())
 
2319
        self.addCleanup(tt.finalize)
 
2320
        tt.new_directory('', ROOT_PARENT, 'TREE_ROOT')
 
2321
        rev = tt.commit(branch, 'my message')
 
2322
        self.assertEqual([], branch.basis_tree().get_parent_ids())
 
2323
        self.assertNotEqual(_mod_revision.NULL_REVISION,
 
2324
                            branch.last_revision())
 
2325
 
 
2326
    def test_first_commit_with_merge_parents(self):
 
2327
        branch = self.make_branch('branch')
 
2328
        branch.lock_write()
 
2329
        self.addCleanup(branch.unlock)
 
2330
        tt = TransformPreview(branch.basis_tree())
 
2331
        self.addCleanup(tt.finalize)
 
2332
        e = self.assertRaises(ValueError, tt.commit, branch,
 
2333
                          'my message', ['rev1b-id'])
 
2334
        self.assertEqual('Cannot supply merge parents for first commit.',
 
2335
                         str(e))
 
2336
        self.assertEqual(_mod_revision.NULL_REVISION, branch.last_revision())
 
2337
 
 
2338
    def test_add_files(self):
 
2339
        branch, tt = self.get_branch_and_transform()
 
2340
        tt.new_file('file', tt.root, 'contents', 'file-id')
 
2341
        trans_id = tt.new_directory('dir', tt.root, 'dir-id')
 
2342
        if SymlinkFeature.available():
 
2343
            tt.new_symlink('symlink', trans_id, 'target', 'symlink-id')
 
2344
        rev = tt.commit(branch, 'message')
 
2345
        tree = branch.basis_tree()
 
2346
        self.assertEqual('file', tree.id2path('file-id'))
 
2347
        self.assertEqual('contents', tree.get_file_text('file-id'))
 
2348
        self.assertEqual('dir', tree.id2path('dir-id'))
 
2349
        if SymlinkFeature.available():
 
2350
            self.assertEqual('dir/symlink', tree.id2path('symlink-id'))
 
2351
            self.assertEqual('target', tree.get_symlink_target('symlink-id'))
 
2352
 
 
2353
    def test_add_unversioned(self):
 
2354
        branch, tt = self.get_branch_and_transform()
 
2355
        tt.new_file('file', tt.root, 'contents')
 
2356
        self.assertRaises(errors.StrictCommitFailed, tt.commit, branch,
 
2357
                          'message', strict=True)
 
2358
 
 
2359
    def test_modify_strict(self):
 
2360
        branch, tt = self.get_branch_and_transform()
 
2361
        tt.new_file('file', tt.root, 'contents', 'file-id')
 
2362
        tt.commit(branch, 'message', strict=True)
 
2363
        tt = TransformPreview(branch.basis_tree())
 
2364
        self.addCleanup(tt.finalize)
 
2365
        trans_id = tt.trans_id_file_id('file-id')
 
2366
        tt.delete_contents(trans_id)
 
2367
        tt.create_file('contents', trans_id)
 
2368
        tt.commit(branch, 'message', strict=True)
 
2369
 
 
2370
    def test_commit_malformed(self):
 
2371
        """Committing a malformed transform should raise an exception.
 
2372
 
 
2373
        In this case, we are adding a file without adding its parent.
 
2374
        """
 
2375
        branch, tt = self.get_branch_and_transform()
 
2376
        parent_id = tt.trans_id_file_id('parent-id')
 
2377
        tt.new_file('file', parent_id, 'contents', 'file-id')
 
2378
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
 
2379
                          'message')
 
2380
 
 
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'])
 
2412
 
 
2413
 
 
2414
class TestFileMover(tests.TestCaseWithTransport):
 
2415
 
 
2416
    def test_file_mover(self):
 
2417
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
 
2418
        mover = _FileMover()
 
2419
        mover.rename('a', 'q')
 
2420
        self.assertPathExists('q')
 
2421
        self.assertPathDoesNotExist('a')
 
2422
        self.assertPathExists('q/b')
 
2423
        self.assertPathExists('c')
 
2424
        self.assertPathExists('c/d')
 
2425
 
 
2426
    def test_pre_delete_rollback(self):
 
2427
        self.build_tree(['a/'])
 
2428
        mover = _FileMover()
 
2429
        mover.pre_delete('a', 'q')
 
2430
        self.assertPathExists('q')
 
2431
        self.assertPathDoesNotExist('a')
 
2432
        mover.rollback()
 
2433
        self.assertPathDoesNotExist('q')
 
2434
        self.assertPathExists('a')
 
2435
 
 
2436
    def test_apply_deletions(self):
 
2437
        self.build_tree(['a/', 'b/'])
 
2438
        mover = _FileMover()
 
2439
        mover.pre_delete('a', 'q')
 
2440
        mover.pre_delete('b', 'r')
 
2441
        self.assertPathExists('q')
 
2442
        self.assertPathExists('r')
 
2443
        self.assertPathDoesNotExist('a')
 
2444
        self.assertPathDoesNotExist('b')
 
2445
        mover.apply_deletions()
 
2446
        self.assertPathDoesNotExist('q')
 
2447
        self.assertPathDoesNotExist('r')
 
2448
        self.assertPathDoesNotExist('a')
 
2449
        self.assertPathDoesNotExist('b')
 
2450
 
 
2451
    def test_file_mover_rollback(self):
 
2452
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
 
2453
        mover = _FileMover()
 
2454
        mover.rename('c/d', 'c/f')
 
2455
        mover.rename('c/e', 'c/d')
 
2456
        try:
 
2457
            mover.rename('a', 'c')
 
2458
        except errors.FileExists, e:
 
2459
            mover.rollback()
 
2460
        self.assertPathExists('a')
 
2461
        self.assertPathExists('c/d')
 
2462
 
 
2463
 
 
2464
class Bogus(Exception):
 
2465
    pass
 
2466
 
 
2467
 
 
2468
class TestTransformRollback(tests.TestCaseWithTransport):
 
2469
 
 
2470
    class ExceptionFileMover(_FileMover):
 
2471
 
 
2472
        def __init__(self, bad_source=None, bad_target=None):
 
2473
            _FileMover.__init__(self)
 
2474
            self.bad_source = bad_source
 
2475
            self.bad_target = bad_target
 
2476
 
 
2477
        def rename(self, source, target):
 
2478
            if (self.bad_source is not None and
 
2479
                source.endswith(self.bad_source)):
 
2480
                raise Bogus
 
2481
            elif (self.bad_target is not None and
 
2482
                target.endswith(self.bad_target)):
 
2483
                raise Bogus
 
2484
            else:
 
2485
                _FileMover.rename(self, source, target)
 
2486
 
 
2487
    def test_rollback_rename(self):
 
2488
        tree = self.make_branch_and_tree('.')
 
2489
        self.build_tree(['a/', 'a/b'])
 
2490
        tt = TreeTransform(tree)
 
2491
        self.addCleanup(tt.finalize)
 
2492
        a_id = tt.trans_id_tree_path('a')
 
2493
        tt.adjust_path('c', tt.root, a_id)
 
2494
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
 
2495
        self.assertRaises(Bogus, tt.apply,
 
2496
                          _mover=self.ExceptionFileMover(bad_source='a'))
 
2497
        self.assertPathExists('a')
 
2498
        self.assertPathExists('a/b')
 
2499
        tt.apply()
 
2500
        self.assertPathExists('c')
 
2501
        self.assertPathExists('c/d')
 
2502
 
 
2503
    def test_rollback_rename_into_place(self):
 
2504
        tree = self.make_branch_and_tree('.')
 
2505
        self.build_tree(['a/', 'a/b'])
 
2506
        tt = TreeTransform(tree)
 
2507
        self.addCleanup(tt.finalize)
 
2508
        a_id = tt.trans_id_tree_path('a')
 
2509
        tt.adjust_path('c', tt.root, a_id)
 
2510
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
 
2511
        self.assertRaises(Bogus, tt.apply,
 
2512
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
 
2513
        self.assertPathExists('a')
 
2514
        self.assertPathExists('a/b')
 
2515
        tt.apply()
 
2516
        self.assertPathExists('c')
 
2517
        self.assertPathExists('c/d')
 
2518
 
 
2519
    def test_rollback_deletion(self):
 
2520
        tree = self.make_branch_and_tree('.')
 
2521
        self.build_tree(['a/', 'a/b'])
 
2522
        tt = TreeTransform(tree)
 
2523
        self.addCleanup(tt.finalize)
 
2524
        a_id = tt.trans_id_tree_path('a')
 
2525
        tt.delete_contents(a_id)
 
2526
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
 
2527
        self.assertRaises(Bogus, tt.apply,
 
2528
                          _mover=self.ExceptionFileMover(bad_target='d'))
 
2529
        self.assertPathExists('a')
 
2530
        self.assertPathExists('a/b')
 
2531
 
 
2532
 
 
2533
class TestFinalizeRobustness(tests.TestCaseWithTransport):
 
2534
    """Ensure treetransform creation errors can be safely cleaned up after"""
 
2535
 
 
2536
    def _override_globals_in_method(self, instance, method_name, globals):
 
2537
        """Replace method on instance with one with updated globals"""
 
2538
        import types
 
2539
        func = getattr(instance, method_name).im_func
 
2540
        new_globals = dict(func.func_globals)
 
2541
        new_globals.update(globals)
 
2542
        new_func = types.FunctionType(func.func_code, new_globals,
 
2543
            func.func_name, func.func_defaults)
 
2544
        setattr(instance, method_name,
 
2545
            types.MethodType(new_func, instance, instance.__class__))
 
2546
        self.addCleanup(delattr, instance, method_name)
 
2547
 
 
2548
    @staticmethod
 
2549
    def _fake_open_raises_before(name, mode):
 
2550
        """Like open() but raises before doing anything"""
 
2551
        raise RuntimeError
 
2552
 
 
2553
    @staticmethod
 
2554
    def _fake_open_raises_after(name, mode):
 
2555
        """Like open() but raises after creating file without returning"""
 
2556
        open(name, mode).close()
 
2557
        raise RuntimeError
 
2558
 
 
2559
    def create_transform_and_root_trans_id(self):
 
2560
        """Setup a transform creating a file in limbo"""
 
2561
        tree = self.make_branch_and_tree('.')
 
2562
        tt = TreeTransform(tree)
 
2563
        return tt, tt.create_path("a", tt.root)
 
2564
 
 
2565
    def create_transform_and_subdir_trans_id(self):
 
2566
        """Setup a transform creating a directory containing a file in limbo"""
 
2567
        tree = self.make_branch_and_tree('.')
 
2568
        tt = TreeTransform(tree)
 
2569
        d_trans_id = tt.create_path("d", tt.root)
 
2570
        tt.create_directory(d_trans_id)
 
2571
        f_trans_id = tt.create_path("a", d_trans_id)
 
2572
        tt.adjust_path("a", d_trans_id, f_trans_id)
 
2573
        return tt, f_trans_id
 
2574
 
 
2575
    def test_root_create_file_open_raises_before_creation(self):
 
2576
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2577
        self._override_globals_in_method(tt, "create_file",
 
2578
            {"open": self._fake_open_raises_before})
 
2579
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2580
        path = tt._limbo_name(trans_id)
 
2581
        self.assertPathDoesNotExist(path)
 
2582
        tt.finalize()
 
2583
        self.assertPathDoesNotExist(tt._limbodir)
 
2584
 
 
2585
    def test_root_create_file_open_raises_after_creation(self):
 
2586
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2587
        self._override_globals_in_method(tt, "create_file",
 
2588
            {"open": self._fake_open_raises_after})
 
2589
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2590
        path = tt._limbo_name(trans_id)
 
2591
        self.assertPathExists(path)
 
2592
        tt.finalize()
 
2593
        self.assertPathDoesNotExist(path)
 
2594
        self.assertPathDoesNotExist(tt._limbodir)
 
2595
 
 
2596
    def test_subdir_create_file_open_raises_before_creation(self):
 
2597
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
2598
        self._override_globals_in_method(tt, "create_file",
 
2599
            {"open": self._fake_open_raises_before})
 
2600
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2601
        path = tt._limbo_name(trans_id)
 
2602
        self.assertPathDoesNotExist(path)
 
2603
        tt.finalize()
 
2604
        self.assertPathDoesNotExist(tt._limbodir)
 
2605
 
 
2606
    def test_subdir_create_file_open_raises_after_creation(self):
 
2607
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
2608
        self._override_globals_in_method(tt, "create_file",
 
2609
            {"open": self._fake_open_raises_after})
 
2610
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2611
        path = tt._limbo_name(trans_id)
 
2612
        self.assertPathExists(path)
 
2613
        tt.finalize()
 
2614
        self.assertPathDoesNotExist(path)
 
2615
        self.assertPathDoesNotExist(tt._limbodir)
 
2616
 
 
2617
    def test_rename_in_limbo_rename_raises_after_rename(self):
 
2618
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2619
        parent1 = tt.new_directory('parent1', tt.root)
 
2620
        child1 = tt.new_file('child1', parent1, 'contents')
 
2621
        parent2 = tt.new_directory('parent2', tt.root)
 
2622
 
 
2623
        class FakeOSModule(object):
 
2624
            def rename(self, old, new):
 
2625
                os.rename(old, new)
 
2626
                raise RuntimeError
 
2627
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
2628
            {"os": FakeOSModule()})
 
2629
        self.assertRaises(
 
2630
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
2631
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
 
2632
        self.assertPathExists(path)
 
2633
        tt.finalize()
 
2634
        self.assertPathDoesNotExist(path)
 
2635
        self.assertPathDoesNotExist(tt._limbodir)
 
2636
 
 
2637
    def test_rename_in_limbo_rename_raises_before_rename(self):
 
2638
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2639
        parent1 = tt.new_directory('parent1', tt.root)
 
2640
        child1 = tt.new_file('child1', parent1, 'contents')
 
2641
        parent2 = tt.new_directory('parent2', tt.root)
 
2642
 
 
2643
        class FakeOSModule(object):
 
2644
            def rename(self, old, new):
 
2645
                raise RuntimeError
 
2646
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
2647
            {"os": FakeOSModule()})
 
2648
        self.assertRaises(
 
2649
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
2650
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
 
2651
        self.assertPathExists(path)
 
2652
        tt.finalize()
 
2653
        self.assertPathDoesNotExist(path)
 
2654
        self.assertPathDoesNotExist(tt._limbodir)
 
2655
 
 
2656
 
 
2657
class TestTransformMissingParent(tests.TestCaseWithTransport):
 
2658
 
 
2659
    def make_tt_with_versioned_dir(self):
 
2660
        wt = self.make_branch_and_tree('.')
 
2661
        self.build_tree(['dir/',])
 
2662
        wt.add(['dir'], ['dir-id'])
 
2663
        wt.commit('Create dir')
 
2664
        tt = TreeTransform(wt)
 
2665
        self.addCleanup(tt.finalize)
 
2666
        return wt, tt
 
2667
 
 
2668
    def test_resolve_create_parent_for_versioned_file(self):
 
2669
        wt, tt = self.make_tt_with_versioned_dir()
 
2670
        dir_tid = tt.trans_id_tree_file_id('dir-id')
 
2671
        file_tid = tt.new_file('file', dir_tid, 'Contents', file_id='file-id')
 
2672
        tt.delete_contents(dir_tid)
 
2673
        tt.unversion_file(dir_tid)
 
2674
        conflicts = resolve_conflicts(tt)
 
2675
        # one conflict for the missing directory, one for the unversioned
 
2676
        # parent
 
2677
        self.assertLength(2, conflicts)
 
2678
 
 
2679
    def test_non_versioned_file_create_conflict(self):
 
2680
        wt, tt = self.make_tt_with_versioned_dir()
 
2681
        dir_tid = tt.trans_id_tree_file_id('dir-id')
 
2682
        tt.new_file('file', dir_tid, 'Contents')
 
2683
        tt.delete_contents(dir_tid)
 
2684
        tt.unversion_file(dir_tid)
 
2685
        conflicts = resolve_conflicts(tt)
 
2686
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
 
2687
        self.assertLength(1, conflicts)
 
2688
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
2689
                         conflicts.pop())
 
2690
 
 
2691
 
 
2692
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
 
2693
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
 
2694
                  (False, False))
 
2695
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
 
2696
              ('', ''), ('directory', 'directory'), (False, False))
 
2697
 
 
2698
 
 
2699
class TestTransformPreview(tests.TestCaseWithTransport):
 
2700
 
 
2701
    def create_tree(self):
 
2702
        tree = self.make_branch_and_tree('.')
 
2703
        self.build_tree_contents([('a', 'content 1')])
 
2704
        tree.set_root_id('TREE_ROOT')
 
2705
        tree.add('a', 'a-id')
 
2706
        tree.commit('rev1', rev_id='rev1')
 
2707
        return tree.branch.repository.revision_tree('rev1')
 
2708
 
 
2709
    def get_empty_preview(self):
 
2710
        repository = self.make_repository('repo')
 
2711
        tree = repository.revision_tree(_mod_revision.NULL_REVISION)
 
2712
        preview = TransformPreview(tree)
 
2713
        self.addCleanup(preview.finalize)
 
2714
        return preview
 
2715
 
 
2716
    def test_transform_preview(self):
 
2717
        revision_tree = self.create_tree()
 
2718
        preview = TransformPreview(revision_tree)
 
2719
        self.addCleanup(preview.finalize)
 
2720
 
 
2721
    def test_transform_preview_tree(self):
 
2722
        revision_tree = self.create_tree()
 
2723
        preview = TransformPreview(revision_tree)
 
2724
        self.addCleanup(preview.finalize)
 
2725
        preview.get_preview_tree()
 
2726
 
 
2727
    def test_transform_new_file(self):
 
2728
        revision_tree = self.create_tree()
 
2729
        preview = TransformPreview(revision_tree)
 
2730
        self.addCleanup(preview.finalize)
 
2731
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
 
2732
        preview_tree = preview.get_preview_tree()
 
2733
        self.assertEqual(preview_tree.kind('file2-id'), 'file')
 
2734
        self.assertEqual(
 
2735
            preview_tree.get_file('file2-id').read(), 'content B\n')
 
2736
 
 
2737
    def test_diff_preview_tree(self):
 
2738
        revision_tree = self.create_tree()
 
2739
        preview = TransformPreview(revision_tree)
 
2740
        self.addCleanup(preview.finalize)
 
2741
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
 
2742
        preview_tree = preview.get_preview_tree()
 
2743
        out = StringIO()
 
2744
        show_diff_trees(revision_tree, preview_tree, out)
 
2745
        lines = out.getvalue().splitlines()
 
2746
        self.assertEqual(lines[0], "=== added file 'file2'")
 
2747
        # 3 lines of diff administrivia
 
2748
        self.assertEqual(lines[4], "+content B")
 
2749
 
 
2750
    def test_transform_conflicts(self):
 
2751
        revision_tree = self.create_tree()
 
2752
        preview = TransformPreview(revision_tree)
 
2753
        self.addCleanup(preview.finalize)
 
2754
        preview.new_file('a', preview.root, 'content 2')
 
2755
        resolve_conflicts(preview)
 
2756
        trans_id = preview.trans_id_file_id('a-id')
 
2757
        self.assertEqual('a.moved', preview.final_name(trans_id))
 
2758
 
 
2759
    def get_tree_and_preview_tree(self):
 
2760
        revision_tree = self.create_tree()
 
2761
        preview = TransformPreview(revision_tree)
 
2762
        self.addCleanup(preview.finalize)
 
2763
        a_trans_id = preview.trans_id_file_id('a-id')
 
2764
        preview.delete_contents(a_trans_id)
 
2765
        preview.create_file('b content', a_trans_id)
 
2766
        preview_tree = preview.get_preview_tree()
 
2767
        return revision_tree, preview_tree
 
2768
 
 
2769
    def test_iter_changes(self):
 
2770
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2771
        root = revision_tree.get_root_id()
 
2772
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
 
2773
                          (root, root), ('a', 'a'), ('file', 'file'),
 
2774
                          (False, False))],
 
2775
                          list(preview_tree.iter_changes(revision_tree)))
 
2776
 
 
2777
    def test_include_unchanged_succeeds(self):
 
2778
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2779
        changes = preview_tree.iter_changes(revision_tree,
 
2780
                                            include_unchanged=True)
 
2781
        root = revision_tree.get_root_id()
 
2782
 
 
2783
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2784
 
 
2785
    def test_specific_files(self):
 
2786
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2787
        changes = preview_tree.iter_changes(revision_tree,
 
2788
                                            specific_files=[''])
 
2789
        self.assertEqual([A_ENTRY], list(changes))
 
2790
 
 
2791
    def test_want_unversioned(self):
 
2792
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2793
        changes = preview_tree.iter_changes(revision_tree,
 
2794
                                            want_unversioned=True)
 
2795
        self.assertEqual([A_ENTRY], list(changes))
 
2796
 
 
2797
    def test_ignore_extra_trees_no_specific_files(self):
 
2798
        # extra_trees is harmless without specific_files, so we'll silently
 
2799
        # accept it, even though we won't use it.
 
2800
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2801
        preview_tree.iter_changes(revision_tree, extra_trees=[preview_tree])
 
2802
 
 
2803
    def test_ignore_require_versioned_no_specific_files(self):
 
2804
        # require_versioned is meaningless without specific_files.
 
2805
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2806
        preview_tree.iter_changes(revision_tree, require_versioned=False)
 
2807
 
 
2808
    def test_ignore_pb(self):
 
2809
        # pb could be supported, but TT.iter_changes doesn't support it.
 
2810
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
2811
        preview_tree.iter_changes(revision_tree)
 
2812
 
 
2813
    def test_kind(self):
 
2814
        revision_tree = self.create_tree()
 
2815
        preview = TransformPreview(revision_tree)
 
2816
        self.addCleanup(preview.finalize)
 
2817
        preview.new_file('file', preview.root, 'contents', 'file-id')
 
2818
        preview.new_directory('directory', preview.root, 'dir-id')
 
2819
        preview_tree = preview.get_preview_tree()
 
2820
        self.assertEqual('file', preview_tree.kind('file-id'))
 
2821
        self.assertEqual('directory', preview_tree.kind('dir-id'))
 
2822
 
 
2823
    def test_get_file_mtime(self):
 
2824
        preview = self.get_empty_preview()
 
2825
        file_trans_id = preview.new_file('file', preview.root, 'contents',
 
2826
                                         'file-id')
 
2827
        limbo_path = preview._limbo_name(file_trans_id)
 
2828
        preview_tree = preview.get_preview_tree()
 
2829
        self.assertEqual(os.stat(limbo_path).st_mtime,
 
2830
                         preview_tree.get_file_mtime('file-id'))
 
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
 
 
2856
    def test_get_file(self):
 
2857
        preview = self.get_empty_preview()
 
2858
        preview.new_file('file', preview.root, 'contents', 'file-id')
 
2859
        preview_tree = preview.get_preview_tree()
 
2860
        tree_file = preview_tree.get_file('file-id')
 
2861
        try:
 
2862
            self.assertEqual('contents', tree_file.read())
 
2863
        finally:
 
2864
            tree_file.close()
 
2865
 
 
2866
    def test_get_symlink_target(self):
 
2867
        self.requireFeature(SymlinkFeature)
 
2868
        preview = self.get_empty_preview()
 
2869
        preview.new_symlink('symlink', preview.root, 'target', 'symlink-id')
 
2870
        preview_tree = preview.get_preview_tree()
 
2871
        self.assertEqual('target',
 
2872
                         preview_tree.get_symlink_target('symlink-id'))
 
2873
 
 
2874
    def test_all_file_ids(self):
 
2875
        tree = self.make_branch_and_tree('tree')
 
2876
        self.build_tree(['tree/a', 'tree/b', 'tree/c'])
 
2877
        tree.add(['a', 'b', 'c'], ['a-id', 'b-id', 'c-id'])
 
2878
        preview = TransformPreview(tree)
 
2879
        self.addCleanup(preview.finalize)
 
2880
        preview.unversion_file(preview.trans_id_file_id('b-id'))
 
2881
        c_trans_id = preview.trans_id_file_id('c-id')
 
2882
        preview.unversion_file(c_trans_id)
 
2883
        preview.version_file('c-id', c_trans_id)
 
2884
        preview_tree = preview.get_preview_tree()
 
2885
        self.assertEqual(set(['a-id', 'c-id', tree.get_root_id()]),
 
2886
                         preview_tree.all_file_ids())
 
2887
 
 
2888
    def test_path2id_deleted_unchanged(self):
 
2889
        tree = self.make_branch_and_tree('tree')
 
2890
        self.build_tree(['tree/unchanged', 'tree/deleted'])
 
2891
        tree.add(['unchanged', 'deleted'], ['unchanged-id', 'deleted-id'])
 
2892
        preview = TransformPreview(tree)
 
2893
        self.addCleanup(preview.finalize)
 
2894
        preview.unversion_file(preview.trans_id_file_id('deleted-id'))
 
2895
        preview_tree = preview.get_preview_tree()
 
2896
        self.assertEqual('unchanged-id', preview_tree.path2id('unchanged'))
 
2897
        self.assertIs(None, preview_tree.path2id('deleted'))
 
2898
 
 
2899
    def test_path2id_created(self):
 
2900
        tree = self.make_branch_and_tree('tree')
 
2901
        self.build_tree(['tree/unchanged'])
 
2902
        tree.add(['unchanged'], ['unchanged-id'])
 
2903
        preview = TransformPreview(tree)
 
2904
        self.addCleanup(preview.finalize)
 
2905
        preview.new_file('new', preview.trans_id_file_id('unchanged-id'),
 
2906
            'contents', 'new-id')
 
2907
        preview_tree = preview.get_preview_tree()
 
2908
        self.assertEqual('new-id', preview_tree.path2id('unchanged/new'))
 
2909
 
 
2910
    def test_path2id_moved(self):
 
2911
        tree = self.make_branch_and_tree('tree')
 
2912
        self.build_tree(['tree/old_parent/', 'tree/old_parent/child'])
 
2913
        tree.add(['old_parent', 'old_parent/child'],
 
2914
                 ['old_parent-id', 'child-id'])
 
2915
        preview = TransformPreview(tree)
 
2916
        self.addCleanup(preview.finalize)
 
2917
        new_parent = preview.new_directory('new_parent', preview.root,
 
2918
                                           'new_parent-id')
 
2919
        preview.adjust_path('child', new_parent,
 
2920
                            preview.trans_id_file_id('child-id'))
 
2921
        preview_tree = preview.get_preview_tree()
 
2922
        self.assertIs(None, preview_tree.path2id('old_parent/child'))
 
2923
        self.assertEqual('child-id', preview_tree.path2id('new_parent/child'))
 
2924
 
 
2925
    def test_path2id_renamed_parent(self):
 
2926
        tree = self.make_branch_and_tree('tree')
 
2927
        self.build_tree(['tree/old_name/', 'tree/old_name/child'])
 
2928
        tree.add(['old_name', 'old_name/child'],
 
2929
                 ['parent-id', 'child-id'])
 
2930
        preview = TransformPreview(tree)
 
2931
        self.addCleanup(preview.finalize)
 
2932
        preview.adjust_path('new_name', preview.root,
 
2933
                            preview.trans_id_file_id('parent-id'))
 
2934
        preview_tree = preview.get_preview_tree()
 
2935
        self.assertIs(None, preview_tree.path2id('old_name/child'))
 
2936
        self.assertEqual('child-id', preview_tree.path2id('new_name/child'))
 
2937
 
 
2938
    def assertMatchingIterEntries(self, tt, specific_file_ids=None):
 
2939
        preview_tree = tt.get_preview_tree()
 
2940
        preview_result = list(preview_tree.iter_entries_by_dir(
 
2941
                              specific_file_ids))
 
2942
        tree = tt._tree
 
2943
        tt.apply()
 
2944
        actual_result = list(tree.iter_entries_by_dir(specific_file_ids))
 
2945
        self.assertEqual(actual_result, preview_result)
 
2946
 
 
2947
    def test_iter_entries_by_dir_new(self):
 
2948
        tree = self.make_branch_and_tree('tree')
 
2949
        tt = TreeTransform(tree)
 
2950
        tt.new_file('new', tt.root, 'contents', 'new-id')
 
2951
        self.assertMatchingIterEntries(tt)
 
2952
 
 
2953
    def test_iter_entries_by_dir_deleted(self):
 
2954
        tree = self.make_branch_and_tree('tree')
 
2955
        self.build_tree(['tree/deleted'])
 
2956
        tree.add('deleted', 'deleted-id')
 
2957
        tt = TreeTransform(tree)
 
2958
        tt.delete_contents(tt.trans_id_file_id('deleted-id'))
 
2959
        self.assertMatchingIterEntries(tt)
 
2960
 
 
2961
    def test_iter_entries_by_dir_unversioned(self):
 
2962
        tree = self.make_branch_and_tree('tree')
 
2963
        self.build_tree(['tree/removed'])
 
2964
        tree.add('removed', 'removed-id')
 
2965
        tt = TreeTransform(tree)
 
2966
        tt.unversion_file(tt.trans_id_file_id('removed-id'))
 
2967
        self.assertMatchingIterEntries(tt)
 
2968
 
 
2969
    def test_iter_entries_by_dir_moved(self):
 
2970
        tree = self.make_branch_and_tree('tree')
 
2971
        self.build_tree(['tree/moved', 'tree/new_parent/'])
 
2972
        tree.add(['moved', 'new_parent'], ['moved-id', 'new_parent-id'])
 
2973
        tt = TreeTransform(tree)
 
2974
        tt.adjust_path('moved', tt.trans_id_file_id('new_parent-id'),
 
2975
                       tt.trans_id_file_id('moved-id'))
 
2976
        self.assertMatchingIterEntries(tt)
 
2977
 
 
2978
    def test_iter_entries_by_dir_specific_file_ids(self):
 
2979
        tree = self.make_branch_and_tree('tree')
 
2980
        tree.set_root_id('tree-root-id')
 
2981
        self.build_tree(['tree/parent/', 'tree/parent/child'])
 
2982
        tree.add(['parent', 'parent/child'], ['parent-id', 'child-id'])
 
2983
        tt = TreeTransform(tree)
 
2984
        self.assertMatchingIterEntries(tt, ['tree-root-id', 'child-id'])
 
2985
 
 
2986
    def test_symlink_content_summary(self):
 
2987
        self.requireFeature(SymlinkFeature)
 
2988
        preview = self.get_empty_preview()
 
2989
        preview.new_symlink('path', preview.root, 'target', 'path-id')
 
2990
        summary = preview.get_preview_tree().path_content_summary('path')
 
2991
        self.assertEqual(('symlink', None, None, 'target'), summary)
 
2992
 
 
2993
    def test_missing_content_summary(self):
 
2994
        preview = self.get_empty_preview()
 
2995
        summary = preview.get_preview_tree().path_content_summary('path')
 
2996
        self.assertEqual(('missing', None, None, None), summary)
 
2997
 
 
2998
    def test_deleted_content_summary(self):
 
2999
        tree = self.make_branch_and_tree('tree')
 
3000
        self.build_tree(['tree/path/'])
 
3001
        tree.add('path')
 
3002
        preview = TransformPreview(tree)
 
3003
        self.addCleanup(preview.finalize)
 
3004
        preview.delete_contents(preview.trans_id_tree_path('path'))
 
3005
        summary = preview.get_preview_tree().path_content_summary('path')
 
3006
        self.assertEqual(('missing', None, None, None), summary)
 
3007
 
 
3008
    def test_file_content_summary_executable(self):
 
3009
        preview = self.get_empty_preview()
 
3010
        path_id = preview.new_file('path', preview.root, 'contents', 'path-id')
 
3011
        preview.set_executability(True, path_id)
 
3012
        summary = preview.get_preview_tree().path_content_summary('path')
 
3013
        self.assertEqual(4, len(summary))
 
3014
        self.assertEqual('file', summary[0])
 
3015
        # size must be known
 
3016
        self.assertEqual(len('contents'), summary[1])
 
3017
        # executable
 
3018
        self.assertEqual(True, summary[2])
 
3019
        # will not have hash (not cheap to determine)
 
3020
        self.assertIs(None, summary[3])
 
3021
 
 
3022
    def test_change_executability(self):
 
3023
        tree = self.make_branch_and_tree('tree')
 
3024
        self.build_tree(['tree/path'])
 
3025
        tree.add('path')
 
3026
        preview = TransformPreview(tree)
 
3027
        self.addCleanup(preview.finalize)
 
3028
        path_id = preview.trans_id_tree_path('path')
 
3029
        preview.set_executability(True, path_id)
 
3030
        summary = preview.get_preview_tree().path_content_summary('path')
 
3031
        self.assertEqual(True, summary[2])
 
3032
 
 
3033
    def test_file_content_summary_non_exec(self):
 
3034
        preview = self.get_empty_preview()
 
3035
        preview.new_file('path', preview.root, 'contents', 'path-id')
 
3036
        summary = preview.get_preview_tree().path_content_summary('path')
 
3037
        self.assertEqual(4, len(summary))
 
3038
        self.assertEqual('file', summary[0])
 
3039
        # size must be known
 
3040
        self.assertEqual(len('contents'), summary[1])
 
3041
        # not executable
 
3042
        self.assertEqual(False, summary[2])
 
3043
        # will not have hash (not cheap to determine)
 
3044
        self.assertIs(None, summary[3])
 
3045
 
 
3046
    def test_dir_content_summary(self):
 
3047
        preview = self.get_empty_preview()
 
3048
        preview.new_directory('path', preview.root, 'path-id')
 
3049
        summary = preview.get_preview_tree().path_content_summary('path')
 
3050
        self.assertEqual(('directory', None, None, None), summary)
 
3051
 
 
3052
    def test_tree_content_summary(self):
 
3053
        preview = self.get_empty_preview()
 
3054
        path = preview.new_directory('path', preview.root, 'path-id')
 
3055
        preview.set_tree_reference('rev-1', path)
 
3056
        summary = preview.get_preview_tree().path_content_summary('path')
 
3057
        self.assertEqual(4, len(summary))
 
3058
        self.assertEqual('tree-reference', summary[0])
 
3059
 
 
3060
    def test_annotate(self):
 
3061
        tree = self.make_branch_and_tree('tree')
 
3062
        self.build_tree_contents([('tree/file', 'a\n')])
 
3063
        tree.add('file', 'file-id')
 
3064
        tree.commit('a', rev_id='one')
 
3065
        self.build_tree_contents([('tree/file', 'a\nb\n')])
 
3066
        preview = TransformPreview(tree)
 
3067
        self.addCleanup(preview.finalize)
 
3068
        file_trans_id = preview.trans_id_file_id('file-id')
 
3069
        preview.delete_contents(file_trans_id)
 
3070
        preview.create_file('a\nb\nc\n', file_trans_id)
 
3071
        preview_tree = preview.get_preview_tree()
 
3072
        expected = [
 
3073
            ('one', 'a\n'),
 
3074
            ('me:', 'b\n'),
 
3075
            ('me:', 'c\n'),
 
3076
        ]
 
3077
        annotation = preview_tree.annotate_iter('file-id', 'me:')
 
3078
        self.assertEqual(expected, annotation)
 
3079
 
 
3080
    def test_annotate_missing(self):
 
3081
        preview = self.get_empty_preview()
 
3082
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
 
3083
        preview_tree = preview.get_preview_tree()
 
3084
        expected = [
 
3085
            ('me:', 'a\n'),
 
3086
            ('me:', 'b\n'),
 
3087
            ('me:', 'c\n'),
 
3088
         ]
 
3089
        annotation = preview_tree.annotate_iter('file-id', 'me:')
 
3090
        self.assertEqual(expected, annotation)
 
3091
 
 
3092
    def test_annotate_rename(self):
 
3093
        tree = self.make_branch_and_tree('tree')
 
3094
        self.build_tree_contents([('tree/file', 'a\n')])
 
3095
        tree.add('file', 'file-id')
 
3096
        tree.commit('a', rev_id='one')
 
3097
        preview = TransformPreview(tree)
 
3098
        self.addCleanup(preview.finalize)
 
3099
        file_trans_id = preview.trans_id_file_id('file-id')
 
3100
        preview.adjust_path('newname', preview.root, file_trans_id)
 
3101
        preview_tree = preview.get_preview_tree()
 
3102
        expected = [
 
3103
            ('one', 'a\n'),
 
3104
        ]
 
3105
        annotation = preview_tree.annotate_iter('file-id', 'me:')
 
3106
        self.assertEqual(expected, annotation)
 
3107
 
 
3108
    def test_annotate_deleted(self):
 
3109
        tree = self.make_branch_and_tree('tree')
 
3110
        self.build_tree_contents([('tree/file', 'a\n')])
 
3111
        tree.add('file', 'file-id')
 
3112
        tree.commit('a', rev_id='one')
 
3113
        self.build_tree_contents([('tree/file', 'a\nb\n')])
 
3114
        preview = TransformPreview(tree)
 
3115
        self.addCleanup(preview.finalize)
 
3116
        file_trans_id = preview.trans_id_file_id('file-id')
 
3117
        preview.delete_contents(file_trans_id)
 
3118
        preview_tree = preview.get_preview_tree()
 
3119
        annotation = preview_tree.annotate_iter('file-id', 'me:')
 
3120
        self.assertIs(None, annotation)
 
3121
 
 
3122
    def test_stored_kind(self):
 
3123
        preview = self.get_empty_preview()
 
3124
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
 
3125
        preview_tree = preview.get_preview_tree()
 
3126
        self.assertEqual('file', preview_tree.stored_kind('file-id'))
 
3127
 
 
3128
    def test_is_executable(self):
 
3129
        preview = self.get_empty_preview()
 
3130
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
 
3131
        preview.set_executability(True, preview.trans_id_file_id('file-id'))
 
3132
        preview_tree = preview.get_preview_tree()
 
3133
        self.assertEqual(True, preview_tree.is_executable('file-id'))
 
3134
 
 
3135
    def test_get_set_parent_ids(self):
 
3136
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
 
3137
        self.assertEqual([], preview_tree.get_parent_ids())
 
3138
        preview_tree.set_parent_ids(['rev-1'])
 
3139
        self.assertEqual(['rev-1'], preview_tree.get_parent_ids())
 
3140
 
 
3141
    def test_plan_file_merge(self):
 
3142
        work_a = self.make_branch_and_tree('wta')
 
3143
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
 
3144
        work_a.add('file', 'file-id')
 
3145
        base_id = work_a.commit('base version')
 
3146
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
 
3147
        preview = TransformPreview(work_a)
 
3148
        self.addCleanup(preview.finalize)
 
3149
        trans_id = preview.trans_id_file_id('file-id')
 
3150
        preview.delete_contents(trans_id)
 
3151
        preview.create_file('b\nc\nd\ne\n', trans_id)
 
3152
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
 
3153
        tree_a = preview.get_preview_tree()
 
3154
        tree_a.set_parent_ids([base_id])
 
3155
        self.assertEqual([
 
3156
            ('killed-a', 'a\n'),
 
3157
            ('killed-b', 'b\n'),
 
3158
            ('unchanged', 'c\n'),
 
3159
            ('unchanged', 'd\n'),
 
3160
            ('new-a', 'e\n'),
 
3161
            ('new-b', 'f\n'),
 
3162
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
 
3163
 
 
3164
    def test_plan_file_merge_revision_tree(self):
 
3165
        work_a = self.make_branch_and_tree('wta')
 
3166
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
 
3167
        work_a.add('file', 'file-id')
 
3168
        base_id = work_a.commit('base version')
 
3169
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
 
3170
        preview = TransformPreview(work_a.basis_tree())
 
3171
        self.addCleanup(preview.finalize)
 
3172
        trans_id = preview.trans_id_file_id('file-id')
 
3173
        preview.delete_contents(trans_id)
 
3174
        preview.create_file('b\nc\nd\ne\n', trans_id)
 
3175
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
 
3176
        tree_a = preview.get_preview_tree()
 
3177
        tree_a.set_parent_ids([base_id])
 
3178
        self.assertEqual([
 
3179
            ('killed-a', 'a\n'),
 
3180
            ('killed-b', 'b\n'),
 
3181
            ('unchanged', 'c\n'),
 
3182
            ('unchanged', 'd\n'),
 
3183
            ('new-a', 'e\n'),
 
3184
            ('new-b', 'f\n'),
 
3185
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
 
3186
 
 
3187
    def test_walkdirs(self):
 
3188
        preview = self.get_empty_preview()
 
3189
        root = preview.new_directory('', ROOT_PARENT, 'tree-root')
 
3190
        # FIXME: new_directory should mark root.
 
3191
        preview.fixup_new_roots()
 
3192
        preview_tree = preview.get_preview_tree()
 
3193
        file_trans_id = preview.new_file('a', preview.root, 'contents',
 
3194
                                         'a-id')
 
3195
        expected = [(('', 'tree-root'),
 
3196
                    [('a', 'a', 'file', None, 'a-id', 'file')])]
 
3197
        self.assertEqual(expected, list(preview_tree.walkdirs()))
 
3198
 
 
3199
    def test_extras(self):
 
3200
        work_tree = self.make_branch_and_tree('tree')
 
3201
        self.build_tree(['tree/removed-file', 'tree/existing-file',
 
3202
                         'tree/not-removed-file'])
 
3203
        work_tree.add(['removed-file', 'not-removed-file'])
 
3204
        preview = TransformPreview(work_tree)
 
3205
        self.addCleanup(preview.finalize)
 
3206
        preview.new_file('new-file', preview.root, 'contents')
 
3207
        preview.new_file('new-versioned-file', preview.root, 'contents',
 
3208
                         'new-versioned-id')
 
3209
        tree = preview.get_preview_tree()
 
3210
        preview.unversion_file(preview.trans_id_tree_path('removed-file'))
 
3211
        self.assertEqual(set(['new-file', 'removed-file', 'existing-file']),
 
3212
                         set(tree.extras()))
 
3213
 
 
3214
    def test_merge_into_preview(self):
 
3215
        work_tree = self.make_branch_and_tree('tree')
 
3216
        self.build_tree_contents([('tree/file','b\n')])
 
3217
        work_tree.add('file', 'file-id')
 
3218
        work_tree.commit('first commit')
 
3219
        child_tree = work_tree.bzrdir.sprout('child').open_workingtree()
 
3220
        self.build_tree_contents([('child/file','b\nc\n')])
 
3221
        child_tree.commit('child commit')
 
3222
        child_tree.lock_write()
 
3223
        self.addCleanup(child_tree.unlock)
 
3224
        work_tree.lock_write()
 
3225
        self.addCleanup(work_tree.unlock)
 
3226
        preview = TransformPreview(work_tree)
 
3227
        self.addCleanup(preview.finalize)
 
3228
        file_trans_id = preview.trans_id_file_id('file-id')
 
3229
        preview.delete_contents(file_trans_id)
 
3230
        preview.create_file('a\nb\n', file_trans_id)
 
3231
        preview_tree = preview.get_preview_tree()
 
3232
        merger = Merger.from_revision_ids(None, preview_tree,
 
3233
                                          child_tree.branch.last_revision(),
 
3234
                                          other_branch=child_tree.branch,
 
3235
                                          tree_branch=work_tree.branch)
 
3236
        merger.merge_type = Merge3Merger
 
3237
        tt = merger.make_merger().make_preview_transform()
 
3238
        self.addCleanup(tt.finalize)
 
3239
        final_tree = tt.get_preview_tree()
 
3240
        self.assertEqual('a\nb\nc\n', final_tree.get_file_text('file-id'))
 
3241
 
 
3242
    def test_merge_preview_into_workingtree(self):
 
3243
        tree = self.make_branch_and_tree('tree')
 
3244
        tree.set_root_id('TREE_ROOT')
 
3245
        tt = TransformPreview(tree)
 
3246
        self.addCleanup(tt.finalize)
 
3247
        tt.new_file('name', tt.root, 'content', 'file-id')
 
3248
        tree2 = self.make_branch_and_tree('tree2')
 
3249
        tree2.set_root_id('TREE_ROOT')
 
3250
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
 
3251
                                         None, tree.basis_tree())
 
3252
        merger.merge_type = Merge3Merger
 
3253
        merger.do_merge()
 
3254
 
 
3255
    def test_merge_preview_into_workingtree_handles_conflicts(self):
 
3256
        tree = self.make_branch_and_tree('tree')
 
3257
        self.build_tree_contents([('tree/foo', 'bar')])
 
3258
        tree.add('foo', 'foo-id')
 
3259
        tree.commit('foo')
 
3260
        tt = TransformPreview(tree)
 
3261
        self.addCleanup(tt.finalize)
 
3262
        trans_id = tt.trans_id_file_id('foo-id')
 
3263
        tt.delete_contents(trans_id)
 
3264
        tt.create_file('baz', trans_id)
 
3265
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
 
3266
        self.build_tree_contents([('tree2/foo', 'qux')])
 
3267
        pb = None
 
3268
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
 
3269
                                         pb, tree.basis_tree())
 
3270
        merger.merge_type = Merge3Merger
 
3271
        merger.do_merge()
 
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
 
 
3291
    def test_is_executable(self):
 
3292
        tree = self.make_branch_and_tree('tree')
 
3293
        preview = TransformPreview(tree)
 
3294
        self.addCleanup(preview.finalize)
 
3295
        preview.new_file('foo', preview.root, 'bar', 'baz-id')
 
3296
        preview_tree = preview.get_preview_tree()
 
3297
        self.assertEqual(False, preview_tree.is_executable('baz-id',
 
3298
                                                           'tree/foo'))
 
3299
        self.assertEqual(False, preview_tree.is_executable('baz-id'))
 
3300
 
 
3301
    def test_commit_preview_tree(self):
 
3302
        tree = self.make_branch_and_tree('tree')
 
3303
        rev_id = tree.commit('rev1')
 
3304
        tree.branch.lock_write()
 
3305
        self.addCleanup(tree.branch.unlock)
 
3306
        tt = TransformPreview(tree)
 
3307
        tt.new_file('file', tt.root, 'contents', 'file_id')
 
3308
        self.addCleanup(tt.finalize)
 
3309
        preview = tt.get_preview_tree()
 
3310
        preview.set_parent_ids([rev_id])
 
3311
        builder = tree.branch.get_commit_builder([rev_id])
 
3312
        list(builder.record_iter_changes(preview, rev_id, tt.iter_changes()))
 
3313
        builder.finish_inventory()
 
3314
        rev2_id = builder.commit('rev2')
 
3315
        rev2_tree = tree.branch.repository.revision_tree(rev2_id)
 
3316
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
 
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
 
 
3329
 
 
3330
class FakeSerializer(object):
 
3331
    """Serializer implementation that simply returns the input.
 
3332
 
 
3333
    The input is returned in the order used by pack.ContainerPushParser.
 
3334
    """
 
3335
    @staticmethod
 
3336
    def bytes_record(bytes, names):
 
3337
        return names, bytes
 
3338
 
 
3339
 
 
3340
class TestSerializeTransform(tests.TestCaseWithTransport):
 
3341
 
 
3342
    _test_needs_features = [features.UnicodeFilenameFeature]
 
3343
 
 
3344
    def get_preview(self, tree=None):
 
3345
        if tree is None:
 
3346
            tree = self.make_branch_and_tree('tree')
 
3347
        tt = TransformPreview(tree)
 
3348
        self.addCleanup(tt.finalize)
 
3349
        return tt
 
3350
 
 
3351
    def assertSerializesTo(self, expected, tt):
 
3352
        records = list(tt.serialize(FakeSerializer()))
 
3353
        self.assertEqual(expected, records)
 
3354
 
 
3355
    @staticmethod
 
3356
    def default_attribs():
 
3357
        return {
 
3358
            '_id_number': 1,
 
3359
            '_new_name': {},
 
3360
            '_new_parent': {},
 
3361
            '_new_executability': {},
 
3362
            '_new_id': {},
 
3363
            '_tree_path_ids': {'': 'new-0'},
 
3364
            '_removed_id': [],
 
3365
            '_removed_contents': [],
 
3366
            '_non_present_ids': {},
 
3367
            }
 
3368
 
 
3369
    def make_records(self, attribs, contents):
 
3370
        records = [
 
3371
            (((('attribs'),),), bencode.bencode(attribs))]
 
3372
        records.extend([(((n, k),), c) for n, k, c in contents])
 
3373
        return records
 
3374
 
 
3375
    def creation_records(self):
 
3376
        attribs = self.default_attribs()
 
3377
        attribs['_id_number'] = 3
 
3378
        attribs['_new_name'] = {
 
3379
            'new-1': u'foo\u1234'.encode('utf-8'), 'new-2': 'qux'}
 
3380
        attribs['_new_id'] = {'new-1': 'baz', 'new-2': 'quxx'}
 
3381
        attribs['_new_parent'] = {'new-1': 'new-0', 'new-2': 'new-0'}
 
3382
        attribs['_new_executability'] = {'new-1': 1}
 
3383
        contents = [
 
3384
            ('new-1', 'file', 'i 1\nbar\n'),
 
3385
            ('new-2', 'directory', ''),
 
3386
            ]
 
3387
        return self.make_records(attribs, contents)
 
3388
 
 
3389
    def test_serialize_creation(self):
 
3390
        tt = self.get_preview()
 
3391
        tt.new_file(u'foo\u1234', tt.root, 'bar', 'baz', True)
 
3392
        tt.new_directory('qux', tt.root, 'quxx')
 
3393
        self.assertSerializesTo(self.creation_records(), tt)
 
3394
 
 
3395
    def test_deserialize_creation(self):
 
3396
        tt = self.get_preview()
 
3397
        tt.deserialize(iter(self.creation_records()))
 
3398
        self.assertEqual(3, tt._id_number)
 
3399
        self.assertEqual({'new-1': u'foo\u1234',
 
3400
                          'new-2': 'qux'}, tt._new_name)
 
3401
        self.assertEqual({'new-1': 'baz', 'new-2': 'quxx'}, tt._new_id)
 
3402
        self.assertEqual({'new-1': tt.root, 'new-2': tt.root}, tt._new_parent)
 
3403
        self.assertEqual({'baz': 'new-1', 'quxx': 'new-2'}, tt._r_new_id)
 
3404
        self.assertEqual({'new-1': True}, tt._new_executability)
 
3405
        self.assertEqual({'new-1': 'file',
 
3406
                          'new-2': 'directory'}, tt._new_contents)
 
3407
        foo_limbo = open(tt._limbo_name('new-1'), 'rb')
 
3408
        try:
 
3409
            foo_content = foo_limbo.read()
 
3410
        finally:
 
3411
            foo_limbo.close()
 
3412
        self.assertEqual('bar', foo_content)
 
3413
 
 
3414
    def symlink_creation_records(self):
 
3415
        attribs = self.default_attribs()
 
3416
        attribs['_id_number'] = 2
 
3417
        attribs['_new_name'] = {'new-1': u'foo\u1234'.encode('utf-8')}
 
3418
        attribs['_new_parent'] = {'new-1': 'new-0'}
 
3419
        contents = [('new-1', 'symlink', u'bar\u1234'.encode('utf-8'))]
 
3420
        return self.make_records(attribs, contents)
 
3421
 
 
3422
    def test_serialize_symlink_creation(self):
 
3423
        self.requireFeature(features.SymlinkFeature)
 
3424
        tt = self.get_preview()
 
3425
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
 
3426
        self.assertSerializesTo(self.symlink_creation_records(), tt)
 
3427
 
 
3428
    def test_deserialize_symlink_creation(self):
 
3429
        self.requireFeature(features.SymlinkFeature)
 
3430
        tt = self.get_preview()
 
3431
        tt.deserialize(iter(self.symlink_creation_records()))
 
3432
        abspath = tt._limbo_name('new-1')
 
3433
        foo_content = osutils.readlink(abspath)
 
3434
        self.assertEqual(u'bar\u1234', foo_content)
 
3435
 
 
3436
    def make_destruction_preview(self):
 
3437
        tree = self.make_branch_and_tree('.')
 
3438
        self.build_tree([u'foo\u1234', 'bar'])
 
3439
        tree.add([u'foo\u1234', 'bar'], ['foo-id', 'bar-id'])
 
3440
        return self.get_preview(tree)
 
3441
 
 
3442
    def destruction_records(self):
 
3443
        attribs = self.default_attribs()
 
3444
        attribs['_id_number'] = 3
 
3445
        attribs['_removed_id'] = ['new-1']
 
3446
        attribs['_removed_contents'] = ['new-2']
 
3447
        attribs['_tree_path_ids'] = {
 
3448
            '': 'new-0',
 
3449
            u'foo\u1234'.encode('utf-8'): 'new-1',
 
3450
            'bar': 'new-2',
 
3451
            }
 
3452
        return self.make_records(attribs, [])
 
3453
 
 
3454
    def test_serialize_destruction(self):
 
3455
        tt = self.make_destruction_preview()
 
3456
        foo_trans_id = tt.trans_id_tree_file_id('foo-id')
 
3457
        tt.unversion_file(foo_trans_id)
 
3458
        bar_trans_id = tt.trans_id_tree_file_id('bar-id')
 
3459
        tt.delete_contents(bar_trans_id)
 
3460
        self.assertSerializesTo(self.destruction_records(), tt)
 
3461
 
 
3462
    def test_deserialize_destruction(self):
 
3463
        tt = self.make_destruction_preview()
 
3464
        tt.deserialize(iter(self.destruction_records()))
 
3465
        self.assertEqual({u'foo\u1234': 'new-1',
 
3466
                          'bar': 'new-2',
 
3467
                          '': tt.root}, tt._tree_path_ids)
 
3468
        self.assertEqual({'new-1': u'foo\u1234',
 
3469
                          'new-2': 'bar',
 
3470
                          tt.root: ''}, tt._tree_id_paths)
 
3471
        self.assertEqual(set(['new-1']), tt._removed_id)
 
3472
        self.assertEqual(set(['new-2']), tt._removed_contents)
 
3473
 
 
3474
    def missing_records(self):
 
3475
        attribs = self.default_attribs()
 
3476
        attribs['_id_number'] = 2
 
3477
        attribs['_non_present_ids'] = {
 
3478
            'boo': 'new-1',}
 
3479
        return self.make_records(attribs, [])
 
3480
 
 
3481
    def test_serialize_missing(self):
 
3482
        tt = self.get_preview()
 
3483
        boo_trans_id = tt.trans_id_file_id('boo')
 
3484
        self.assertSerializesTo(self.missing_records(), tt)
 
3485
 
 
3486
    def test_deserialize_missing(self):
 
3487
        tt = self.get_preview()
 
3488
        tt.deserialize(iter(self.missing_records()))
 
3489
        self.assertEqual({'boo': 'new-1'}, tt._non_present_ids)
 
3490
 
 
3491
    def make_modification_preview(self):
 
3492
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
 
3493
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
3494
        tree = self.make_branch_and_tree('tree')
 
3495
        self.build_tree_contents([('tree/file', LINES_ONE)])
 
3496
        tree.add('file', 'file-id')
 
3497
        return self.get_preview(tree), LINES_TWO
 
3498
 
 
3499
    def modification_records(self):
 
3500
        attribs = self.default_attribs()
 
3501
        attribs['_id_number'] = 2
 
3502
        attribs['_tree_path_ids'] = {
 
3503
            'file': 'new-1',
 
3504
            '': 'new-0',}
 
3505
        attribs['_removed_contents'] = ['new-1']
 
3506
        contents = [('new-1', 'file',
 
3507
                     'i 1\nz\n\nc 0 1 1 1\ni 1\nx\n\nc 0 3 3 1\n')]
 
3508
        return self.make_records(attribs, contents)
 
3509
 
 
3510
    def test_serialize_modification(self):
 
3511
        tt, LINES = self.make_modification_preview()
 
3512
        trans_id = tt.trans_id_file_id('file-id')
 
3513
        tt.delete_contents(trans_id)
 
3514
        tt.create_file(LINES, trans_id)
 
3515
        self.assertSerializesTo(self.modification_records(), tt)
 
3516
 
 
3517
    def test_deserialize_modification(self):
 
3518
        tt, LINES = self.make_modification_preview()
 
3519
        tt.deserialize(iter(self.modification_records()))
 
3520
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
 
3521
 
 
3522
    def make_kind_change_preview(self):
 
3523
        LINES = 'a\nb\nc\nd\n'
 
3524
        tree = self.make_branch_and_tree('tree')
 
3525
        self.build_tree(['tree/foo/'])
 
3526
        tree.add('foo', 'foo-id')
 
3527
        return self.get_preview(tree), LINES
 
3528
 
 
3529
    def kind_change_records(self):
 
3530
        attribs = self.default_attribs()
 
3531
        attribs['_id_number'] = 2
 
3532
        attribs['_tree_path_ids'] = {
 
3533
            'foo': 'new-1',
 
3534
            '': 'new-0',}
 
3535
        attribs['_removed_contents'] = ['new-1']
 
3536
        contents = [('new-1', 'file',
 
3537
                     'i 4\na\nb\nc\nd\n\n')]
 
3538
        return self.make_records(attribs, contents)
 
3539
 
 
3540
    def test_serialize_kind_change(self):
 
3541
        tt, LINES = self.make_kind_change_preview()
 
3542
        trans_id = tt.trans_id_file_id('foo-id')
 
3543
        tt.delete_contents(trans_id)
 
3544
        tt.create_file(LINES, trans_id)
 
3545
        self.assertSerializesTo(self.kind_change_records(), tt)
 
3546
 
 
3547
    def test_deserialize_kind_change(self):
 
3548
        tt, LINES = self.make_kind_change_preview()
 
3549
        tt.deserialize(iter(self.kind_change_records()))
 
3550
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
 
3551
 
 
3552
    def make_add_contents_preview(self):
 
3553
        LINES = 'a\nb\nc\nd\n'
 
3554
        tree = self.make_branch_and_tree('tree')
 
3555
        self.build_tree(['tree/foo'])
 
3556
        tree.add('foo')
 
3557
        os.unlink('tree/foo')
 
3558
        return self.get_preview(tree), LINES
 
3559
 
 
3560
    def add_contents_records(self):
 
3561
        attribs = self.default_attribs()
 
3562
        attribs['_id_number'] = 2
 
3563
        attribs['_tree_path_ids'] = {
 
3564
            'foo': 'new-1',
 
3565
            '': 'new-0',}
 
3566
        contents = [('new-1', 'file',
 
3567
                     'i 4\na\nb\nc\nd\n\n')]
 
3568
        return self.make_records(attribs, contents)
 
3569
 
 
3570
    def test_serialize_add_contents(self):
 
3571
        tt, LINES = self.make_add_contents_preview()
 
3572
        trans_id = tt.trans_id_tree_path('foo')
 
3573
        tt.create_file(LINES, trans_id)
 
3574
        self.assertSerializesTo(self.add_contents_records(), tt)
 
3575
 
 
3576
    def test_deserialize_add_contents(self):
 
3577
        tt, LINES = self.make_add_contents_preview()
 
3578
        tt.deserialize(iter(self.add_contents_records()))
 
3579
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
 
3580
 
 
3581
    def test_get_parents_lines(self):
 
3582
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
 
3583
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
3584
        tree = self.make_branch_and_tree('tree')
 
3585
        self.build_tree_contents([('tree/file', LINES_ONE)])
 
3586
        tree.add('file', 'file-id')
 
3587
        tt = self.get_preview(tree)
 
3588
        trans_id = tt.trans_id_tree_path('file')
 
3589
        self.assertEqual((['aa\n', 'bb\n', 'cc\n', 'dd\n'],),
 
3590
            tt._get_parents_lines(trans_id))
 
3591
 
 
3592
    def test_get_parents_texts(self):
 
3593
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
 
3594
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
3595
        tree = self.make_branch_and_tree('tree')
 
3596
        self.build_tree_contents([('tree/file', LINES_ONE)])
 
3597
        tree.add('file', 'file-id')
 
3598
        tt = self.get_preview(tree)
 
3599
        trans_id = tt.trans_id_tree_path('file')
 
3600
        self.assertEqual((LINES_ONE,),
 
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)