/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_transform.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2020-07-28 02:47:10 UTC
  • mfrom: (7519.1.1 merge-3.1)
  • Revision ID: breezy.the.bot@gmail.com-20200728024710-a2ylds219f1lsl62
Merge lp:brz/3.1.

Merged from https://code.launchpad.net/~jelmer/brz/merge-3.1/+merge/388173

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
import codecs
 
18
import errno
 
19
from io import BytesIO, StringIO
17
20
import os
18
 
from StringIO import StringIO
19
21
import sys
20
22
import time
21
23
 
22
 
from bzrlib import (
 
24
from .. import (
23
25
    bencode,
24
26
    errors,
25
27
    filters,
26
 
    generate_ids,
27
28
    osutils,
28
29
    revision as _mod_revision,
29
30
    rules,
30
31
    tests,
 
32
    trace,
 
33
    transform,
31
34
    urlutils,
32
35
    )
33
 
from bzrlib.bzrdir import BzrDir
34
 
from bzrlib.conflicts import (
 
36
from ..bzr import (
 
37
    generate_ids,
 
38
    )
 
39
from ..conflicts import (
35
40
    DeletingParent,
36
41
    DuplicateEntry,
37
42
    DuplicateID,
40
45
    ParentLoop,
41
46
    UnversionedParent,
42
47
)
43
 
from bzrlib.diff import show_diff_trees
44
 
from bzrlib.errors import (
 
48
from ..controldir import ControlDir
 
49
from ..diff import show_diff_trees
 
50
from ..errors import (
45
51
    DuplicateKey,
46
52
    ExistingLimbo,
47
53
    ExistingPendingDeletion,
48
 
    ImmortalLimbo,
49
54
    ImmortalPendingDeletion,
50
55
    LockError,
51
 
    MalformedTransform,
52
 
    NoSuchFile,
53
 
    ReusingTransform,
54
56
)
55
 
from bzrlib.osutils import (
 
57
from ..osutils import (
56
58
    file_kind,
57
59
    pathjoin,
58
60
)
59
 
from bzrlib.merge import Merge3Merger, Merger
60
 
from bzrlib.tests import (
 
61
from ..merge import Merge3Merger, Merger
 
62
from ..mutabletree import MutableTree
 
63
from . import (
 
64
    features,
 
65
    TestCaseInTempDir,
 
66
    TestSkipped,
 
67
    )
 
68
from .features import (
61
69
    HardlinkFeature,
62
70
    SymlinkFeature,
63
 
    TestCase,
64
 
    TestCaseInTempDir,
65
 
    TestSkipped,
66
 
)
67
 
from bzrlib.transform import (
 
71
    )
 
72
from ..transform import (
68
73
    build_tree,
69
74
    create_from_tree,
70
75
    cook_conflicts,
71
76
    _FileMover,
72
77
    FinalPaths,
73
 
    get_backup_name,
74
78
    resolve_conflicts,
75
79
    resolve_checkout,
76
80
    ROOT_PARENT,
77
 
    TransformPreview,
78
 
    TreeTransform,
 
81
    ImmortalLimbo,
 
82
    MalformedTransform,
 
83
    NoFinalPath,
 
84
    ReusingTransform,
 
85
    TransformRenameFailed,
79
86
)
80
87
 
81
88
 
82
 
class TestTreeTransform(tests.TestCaseWithTransport):
83
 
 
84
 
    def setUp(self):
85
 
        super(TestTreeTransform, self).setUp()
86
 
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
87
 
        os.chdir('..')
88
 
 
89
 
    def get_transform(self):
90
 
        transform = TreeTransform(self.wt)
91
 
        self.addCleanup(transform.finalize)
92
 
        return transform, transform.root
93
 
 
94
 
    def test_existing_limbo(self):
95
 
        transform, root = self.get_transform()
96
 
        limbo_name = transform._limbodir
97
 
        deletion_path = transform._deletiondir
98
 
        os.mkdir(pathjoin(limbo_name, 'hehe'))
99
 
        self.assertRaises(ImmortalLimbo, transform.apply)
100
 
        self.assertRaises(LockError, self.wt.unlock)
101
 
        self.assertRaises(ExistingLimbo, self.get_transform)
102
 
        self.assertRaises(LockError, self.wt.unlock)
103
 
        os.rmdir(pathjoin(limbo_name, 'hehe'))
104
 
        os.rmdir(limbo_name)
105
 
        os.rmdir(deletion_path)
106
 
        transform, root = self.get_transform()
107
 
        transform.apply()
108
 
 
109
 
    def test_existing_pending_deletion(self):
110
 
        transform, root = self.get_transform()
111
 
        deletion_path = self._limbodir = urlutils.local_path_from_url(
112
 
            transform._tree._transport.abspath('pending-deletion'))
113
 
        os.mkdir(pathjoin(deletion_path, 'blocking-directory'))
114
 
        self.assertRaises(ImmortalPendingDeletion, transform.apply)
115
 
        self.assertRaises(LockError, self.wt.unlock)
116
 
        self.assertRaises(ExistingPendingDeletion, self.get_transform)
117
 
 
118
 
    def test_build(self):
119
 
        transform, root = self.get_transform()
120
 
        self.wt.lock_tree_write()
121
 
        self.addCleanup(self.wt.unlock)
122
 
        self.assertIs(transform.get_tree_parent(root), ROOT_PARENT)
123
 
        imaginary_id = transform.trans_id_tree_path('imaginary')
124
 
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
125
 
        self.assertEqual(imaginary_id, imaginary_id2)
126
 
        self.assertEqual(transform.get_tree_parent(imaginary_id), root)
127
 
        self.assertEqual(transform.final_kind(root), 'directory')
128
 
        self.assertEqual(transform.final_file_id(root), self.wt.get_root_id())
129
 
        trans_id = transform.create_path('name', root)
130
 
        self.assertIs(transform.final_file_id(trans_id), None)
131
 
        self.assertRaises(NoSuchFile, transform.final_kind, trans_id)
132
 
        transform.create_file('contents', trans_id)
133
 
        transform.set_executability(True, trans_id)
134
 
        transform.version_file('my_pretties', trans_id)
135
 
        self.assertRaises(DuplicateKey, transform.version_file,
136
 
                          'my_pretties', trans_id)
137
 
        self.assertEqual(transform.final_file_id(trans_id), 'my_pretties')
138
 
        self.assertEqual(transform.final_parent(trans_id), root)
139
 
        self.assertIs(transform.final_parent(root), ROOT_PARENT)
140
 
        self.assertIs(transform.get_tree_parent(root), ROOT_PARENT)
141
 
        oz_id = transform.create_path('oz', root)
142
 
        transform.create_directory(oz_id)
143
 
        transform.version_file('ozzie', oz_id)
144
 
        trans_id2 = transform.create_path('name2', root)
145
 
        transform.create_file('contents', trans_id2)
146
 
        transform.set_executability(False, trans_id2)
147
 
        transform.version_file('my_pretties2', trans_id2)
148
 
        modified_paths = transform.apply().modified_paths
149
 
        self.assertEqual('contents', self.wt.get_file_byname('name').read())
150
 
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
151
 
        self.assertIs(self.wt.is_executable('my_pretties'), True)
152
 
        self.assertIs(self.wt.is_executable('my_pretties2'), False)
153
 
        self.assertEqual('directory', file_kind(self.wt.abspath('oz')))
154
 
        self.assertEqual(len(modified_paths), 3)
155
 
        tree_mod_paths = [self.wt.id2abspath(f) for f in
156
 
                          ('ozzie', 'my_pretties', 'my_pretties2')]
157
 
        self.assertSubset(tree_mod_paths, modified_paths)
158
 
        # is it safe to finalize repeatedly?
159
 
        transform.finalize()
160
 
        transform.finalize()
161
 
 
162
 
    def test_create_files_same_timestamp(self):
163
 
        transform, root = self.get_transform()
164
 
        self.wt.lock_tree_write()
165
 
        self.addCleanup(self.wt.unlock)
166
 
        # Roll back the clock, so that we know everything is being set to the
167
 
        # exact time
168
 
        transform._creation_mtime = creation_mtime = time.time() - 20.0
169
 
        transform.create_file('content-one',
170
 
                              transform.create_path('one', root))
171
 
        time.sleep(1) # *ugly*
172
 
        transform.create_file('content-two',
173
 
                              transform.create_path('two', root))
174
 
        transform.apply()
175
 
        fo, st1 = self.wt.get_file_with_stat(None, path='one', filtered=False)
176
 
        fo.close()
177
 
        fo, st2 = self.wt.get_file_with_stat(None, path='two', filtered=False)
178
 
        fo.close()
179
 
        # We only guarantee 2s resolution
180
 
        self.assertTrue(abs(creation_mtime - st1.st_mtime) < 2.0,
181
 
            "%s != %s within 2 seconds" % (creation_mtime, st1.st_mtime))
182
 
        # But if we have more than that, all files should get the same result
183
 
        self.assertEqual(st1.st_mtime, st2.st_mtime)
184
 
 
185
 
    def test_change_root_id(self):
186
 
        transform, root = self.get_transform()
187
 
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
188
 
        transform.new_directory('', ROOT_PARENT, 'new-root-id')
189
 
        transform.delete_contents(root)
190
 
        transform.unversion_file(root)
191
 
        transform.fixup_new_roots()
192
 
        transform.apply()
193
 
        self.assertEqual('new-root-id', self.wt.get_root_id())
194
 
 
195
 
    def test_change_root_id_add_files(self):
196
 
        transform, root = self.get_transform()
197
 
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
198
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
199
 
        transform.new_file('file', new_trans_id, ['new-contents\n'],
200
 
                           'new-file-id')
201
 
        transform.delete_contents(root)
202
 
        transform.unversion_file(root)
203
 
        transform.fixup_new_roots()
204
 
        transform.apply()
205
 
        self.assertEqual('new-root-id', self.wt.get_root_id())
206
 
        self.assertEqual('new-file-id', self.wt.path2id('file'))
207
 
        self.assertFileEqual('new-contents\n', self.wt.abspath('file'))
208
 
 
209
 
    def test_add_two_roots(self):
210
 
        transform, root = self.get_transform()
211
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
212
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
213
 
        self.assertRaises(ValueError, transform.fixup_new_roots)
214
 
 
215
 
    def test_hardlink(self):
216
 
        self.requireFeature(HardlinkFeature)
217
 
        transform, root = self.get_transform()
218
 
        transform.new_file('file1', root, 'contents')
219
 
        transform.apply()
220
 
        target = self.make_branch_and_tree('target')
221
 
        target_transform = TreeTransform(target)
222
 
        trans_id = target_transform.create_path('file1', target_transform.root)
223
 
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
224
 
        target_transform.apply()
225
 
        self.failUnlessExists('target/file1')
226
 
        source_stat = os.stat(self.wt.abspath('file1'))
227
 
        target_stat = os.stat('target/file1')
228
 
        self.assertEqual(source_stat, target_stat)
229
 
 
230
 
    def test_convenience(self):
231
 
        transform, root = self.get_transform()
232
 
        self.wt.lock_tree_write()
233
 
        self.addCleanup(self.wt.unlock)
234
 
        trans_id = transform.new_file('name', root, 'contents',
235
 
                                      'my_pretties', True)
236
 
        oz = transform.new_directory('oz', root, 'oz-id')
237
 
        dorothy = transform.new_directory('dorothy', oz, 'dorothy-id')
238
 
        toto = transform.new_file('toto', dorothy, 'toto-contents',
239
 
                                  'toto-id', False)
240
 
 
241
 
        self.assertEqual(len(transform.find_conflicts()), 0)
242
 
        transform.apply()
243
 
        self.assertRaises(ReusingTransform, transform.find_conflicts)
244
 
        self.assertEqual('contents', file(self.wt.abspath('name')).read())
245
 
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
246
 
        self.assertIs(self.wt.is_executable('my_pretties'), True)
247
 
        self.assertEqual(self.wt.path2id('oz'), 'oz-id')
248
 
        self.assertEqual(self.wt.path2id('oz/dorothy'), 'dorothy-id')
249
 
        self.assertEqual(self.wt.path2id('oz/dorothy/toto'), 'toto-id')
250
 
 
251
 
        self.assertEqual('toto-contents',
252
 
                         self.wt.get_file_byname('oz/dorothy/toto').read())
253
 
        self.assertIs(self.wt.is_executable('toto-id'), False)
254
 
 
255
 
    def test_tree_reference(self):
256
 
        transform, root = self.get_transform()
257
 
        tree = transform._tree
258
 
        trans_id = transform.new_directory('reference', root, 'subtree-id')
259
 
        transform.set_tree_reference('subtree-revision', trans_id)
260
 
        transform.apply()
261
 
        tree.lock_read()
262
 
        self.addCleanup(tree.unlock)
263
 
        self.assertEqual('subtree-revision',
264
 
                         tree.inventory['subtree-id'].reference_revision)
265
 
 
266
 
    def test_conflicts(self):
267
 
        transform, root = self.get_transform()
268
 
        trans_id = transform.new_file('name', root, 'contents',
269
 
                                      'my_pretties')
270
 
        self.assertEqual(len(transform.find_conflicts()), 0)
271
 
        trans_id2 = transform.new_file('name', root, 'Crontents', 'toto')
272
 
        self.assertEqual(transform.find_conflicts(),
273
 
                         [('duplicate', trans_id, trans_id2, 'name')])
274
 
        self.assertRaises(MalformedTransform, transform.apply)
275
 
        transform.adjust_path('name', trans_id, trans_id2)
276
 
        self.assertEqual(transform.find_conflicts(),
277
 
                         [('non-directory parent', trans_id)])
278
 
        tinman_id = transform.trans_id_tree_path('tinman')
279
 
        transform.adjust_path('name', tinman_id, trans_id2)
280
 
        self.assertEqual(transform.find_conflicts(),
281
 
                         [('unversioned parent', tinman_id),
282
 
                          ('missing parent', tinman_id)])
283
 
        lion_id = transform.create_path('lion', root)
284
 
        self.assertEqual(transform.find_conflicts(),
285
 
                         [('unversioned parent', tinman_id),
286
 
                          ('missing parent', tinman_id)])
287
 
        transform.adjust_path('name', lion_id, trans_id2)
288
 
        self.assertEqual(transform.find_conflicts(),
289
 
                         [('unversioned parent', lion_id),
290
 
                          ('missing parent', lion_id)])
291
 
        transform.version_file("Courage", lion_id)
292
 
        self.assertEqual(transform.find_conflicts(),
293
 
                         [('missing parent', lion_id),
294
 
                          ('versioning no contents', lion_id)])
295
 
        transform.adjust_path('name2', root, trans_id2)
296
 
        self.assertEqual(transform.find_conflicts(),
297
 
                         [('versioning no contents', lion_id)])
298
 
        transform.create_file('Contents, okay?', lion_id)
299
 
        transform.adjust_path('name2', trans_id2, trans_id2)
300
 
        self.assertEqual(transform.find_conflicts(),
301
 
                         [('parent loop', trans_id2),
302
 
                          ('non-directory parent', trans_id2)])
303
 
        transform.adjust_path('name2', root, trans_id2)
304
 
        oz_id = transform.new_directory('oz', root)
305
 
        transform.set_executability(True, oz_id)
306
 
        self.assertEqual(transform.find_conflicts(),
307
 
                         [('unversioned executability', oz_id)])
308
 
        transform.version_file('oz-id', oz_id)
309
 
        self.assertEqual(transform.find_conflicts(),
310
 
                         [('non-file executability', oz_id)])
311
 
        transform.set_executability(None, oz_id)
312
 
        tip_id = transform.new_file('tip', oz_id, 'ozma', 'tip-id')
313
 
        transform.apply()
314
 
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
315
 
        self.assertEqual('contents', file(self.wt.abspath('name')).read())
316
 
        transform2, root = self.get_transform()
317
 
        oz_id = transform2.trans_id_tree_file_id('oz-id')
318
 
        newtip = transform2.new_file('tip', oz_id, 'other', 'tip-id')
319
 
        result = transform2.find_conflicts()
320
 
        fp = FinalPaths(transform2)
321
 
        self.assert_('oz/tip' in transform2._tree_path_ids)
322
 
        self.assertEqual(fp.get_path(newtip), pathjoin('oz', 'tip'))
323
 
        self.assertEqual(len(result), 2)
324
 
        self.assertEqual((result[0][0], result[0][1]),
325
 
                         ('duplicate', newtip))
326
 
        self.assertEqual((result[1][0], result[1][2]),
327
 
                         ('duplicate id', newtip))
328
 
        transform2.finalize()
329
 
        transform3 = TreeTransform(self.wt)
330
 
        self.addCleanup(transform3.finalize)
331
 
        oz_id = transform3.trans_id_tree_file_id('oz-id')
332
 
        transform3.delete_contents(oz_id)
333
 
        self.assertEqual(transform3.find_conflicts(),
334
 
                         [('missing parent', oz_id)])
335
 
        root_id = transform3.root
336
 
        tip_id = transform3.trans_id_tree_file_id('tip-id')
337
 
        transform3.adjust_path('tip', root_id, tip_id)
338
 
        transform3.apply()
339
 
 
340
 
    def test_conflict_on_case_insensitive(self):
341
 
        tree = self.make_branch_and_tree('tree')
342
 
        # Don't try this at home, kids!
343
 
        # Force the tree to report that it is case sensitive, for conflict
344
 
        # resolution tests
345
 
        tree.case_sensitive = True
346
 
        transform = TreeTransform(tree)
347
 
        self.addCleanup(transform.finalize)
348
 
        transform.new_file('file', transform.root, 'content')
349
 
        transform.new_file('FiLe', transform.root, 'content')
350
 
        result = transform.find_conflicts()
351
 
        self.assertEqual([], result)
352
 
        transform.finalize()
353
 
        # Force the tree to report that it is case insensitive, for conflict
354
 
        # generation tests
355
 
        tree.case_sensitive = False
356
 
        transform = TreeTransform(tree)
357
 
        self.addCleanup(transform.finalize)
358
 
        transform.new_file('file', transform.root, 'content')
359
 
        transform.new_file('FiLe', transform.root, 'content')
360
 
        result = transform.find_conflicts()
361
 
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
362
 
 
363
 
    def test_conflict_on_case_insensitive_existing(self):
364
 
        tree = self.make_branch_and_tree('tree')
365
 
        self.build_tree(['tree/FiLe'])
366
 
        # Don't try this at home, kids!
367
 
        # Force the tree to report that it is case sensitive, for conflict
368
 
        # resolution tests
369
 
        tree.case_sensitive = True
370
 
        transform = TreeTransform(tree)
371
 
        self.addCleanup(transform.finalize)
372
 
        transform.new_file('file', transform.root, 'content')
373
 
        result = transform.find_conflicts()
374
 
        self.assertEqual([], result)
375
 
        transform.finalize()
376
 
        # Force the tree to report that it is case insensitive, for conflict
377
 
        # generation tests
378
 
        tree.case_sensitive = False
379
 
        transform = TreeTransform(tree)
380
 
        self.addCleanup(transform.finalize)
381
 
        transform.new_file('file', transform.root, 'content')
382
 
        result = transform.find_conflicts()
383
 
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
384
 
 
385
 
    def test_resolve_case_insensitive_conflict(self):
386
 
        tree = self.make_branch_and_tree('tree')
387
 
        # Don't try this at home, kids!
388
 
        # Force the tree to report that it is case insensitive, for conflict
389
 
        # resolution tests
390
 
        tree.case_sensitive = False
391
 
        transform = TreeTransform(tree)
392
 
        self.addCleanup(transform.finalize)
393
 
        transform.new_file('file', transform.root, 'content')
394
 
        transform.new_file('FiLe', transform.root, 'content')
395
 
        resolve_conflicts(transform)
396
 
        transform.apply()
397
 
        self.failUnlessExists('tree/file')
398
 
        self.failUnlessExists('tree/FiLe.moved')
399
 
 
400
 
    def test_resolve_checkout_case_conflict(self):
401
 
        tree = self.make_branch_and_tree('tree')
402
 
        # Don't try this at home, kids!
403
 
        # Force the tree to report that it is case insensitive, for conflict
404
 
        # resolution tests
405
 
        tree.case_sensitive = False
406
 
        transform = TreeTransform(tree)
407
 
        self.addCleanup(transform.finalize)
408
 
        transform.new_file('file', transform.root, 'content')
409
 
        transform.new_file('FiLe', transform.root, 'content')
410
 
        resolve_conflicts(transform,
411
 
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
412
 
        transform.apply()
413
 
        self.failUnlessExists('tree/file')
414
 
        self.failUnlessExists('tree/FiLe.moved')
415
 
 
416
 
    def test_apply_case_conflict(self):
417
 
        """Ensure that a transform with case conflicts can always be applied"""
418
 
        tree = self.make_branch_and_tree('tree')
419
 
        transform = TreeTransform(tree)
420
 
        self.addCleanup(transform.finalize)
421
 
        transform.new_file('file', transform.root, 'content')
422
 
        transform.new_file('FiLe', transform.root, 'content')
423
 
        dir = transform.new_directory('dir', transform.root)
424
 
        transform.new_file('dirfile', dir, 'content')
425
 
        transform.new_file('dirFiLe', dir, 'content')
426
 
        resolve_conflicts(transform)
427
 
        transform.apply()
428
 
        self.failUnlessExists('tree/file')
429
 
        if not os.path.exists('tree/FiLe.moved'):
430
 
            self.failUnlessExists('tree/FiLe')
431
 
        self.failUnlessExists('tree/dir/dirfile')
432
 
        if not os.path.exists('tree/dir/dirFiLe.moved'):
433
 
            self.failUnlessExists('tree/dir/dirFiLe')
434
 
 
435
 
    def test_case_insensitive_limbo(self):
436
 
        tree = self.make_branch_and_tree('tree')
437
 
        # Don't try this at home, kids!
438
 
        # Force the tree to report that it is case insensitive
439
 
        tree.case_sensitive = False
440
 
        transform = TreeTransform(tree)
441
 
        self.addCleanup(transform.finalize)
442
 
        dir = transform.new_directory('dir', transform.root)
443
 
        first = transform.new_file('file', dir, 'content')
444
 
        second = transform.new_file('FiLe', dir, 'content')
445
 
        self.assertContainsRe(transform._limbo_name(first), 'new-1/file')
446
 
        self.assertNotContainsRe(transform._limbo_name(second), 'new-1/FiLe')
447
 
 
448
 
    def test_adjust_path_updates_child_limbo_names(self):
449
 
        tree = self.make_branch_and_tree('tree')
450
 
        transform = TreeTransform(tree)
451
 
        self.addCleanup(transform.finalize)
452
 
        foo_id = transform.new_directory('foo', transform.root)
453
 
        bar_id = transform.new_directory('bar', foo_id)
454
 
        baz_id = transform.new_directory('baz', bar_id)
455
 
        qux_id = transform.new_directory('qux', baz_id)
456
 
        transform.adjust_path('quxx', foo_id, bar_id)
457
 
        self.assertStartsWith(transform._limbo_name(qux_id),
458
 
                              transform._limbo_name(bar_id))
459
 
 
460
 
    def test_add_del(self):
461
 
        start, root = self.get_transform()
462
 
        start.new_directory('a', root, 'a')
463
 
        start.apply()
464
 
        transform, root = self.get_transform()
465
 
        transform.delete_versioned(transform.trans_id_tree_file_id('a'))
466
 
        transform.new_directory('a', root, 'a')
467
 
        transform.apply()
468
 
 
469
 
    def test_unversioning(self):
470
 
        create_tree, root = self.get_transform()
471
 
        parent_id = create_tree.new_directory('parent', root, 'parent-id')
472
 
        create_tree.new_file('child', parent_id, 'child', 'child-id')
473
 
        create_tree.apply()
474
 
        unversion = TreeTransform(self.wt)
475
 
        self.addCleanup(unversion.finalize)
476
 
        parent = unversion.trans_id_tree_path('parent')
477
 
        unversion.unversion_file(parent)
478
 
        self.assertEqual(unversion.find_conflicts(),
479
 
                         [('unversioned parent', parent_id)])
480
 
        file_id = unversion.trans_id_tree_file_id('child-id')
481
 
        unversion.unversion_file(file_id)
482
 
        unversion.apply()
483
 
 
484
 
    def test_name_invariants(self):
485
 
        create_tree, root = self.get_transform()
486
 
        # prepare tree
487
 
        root = create_tree.root
488
 
        create_tree.new_file('name1', root, 'hello1', 'name1')
489
 
        create_tree.new_file('name2', root, 'hello2', 'name2')
490
 
        ddir = create_tree.new_directory('dying_directory', root, 'ddir')
491
 
        create_tree.new_file('dying_file', ddir, 'goodbye1', 'dfile')
492
 
        create_tree.new_file('moving_file', ddir, 'later1', 'mfile')
493
 
        create_tree.new_file('moving_file2', root, 'later2', 'mfile2')
494
 
        create_tree.apply()
495
 
 
496
 
        mangle_tree,root = self.get_transform()
497
 
        root = mangle_tree.root
498
 
        #swap names
499
 
        name1 = mangle_tree.trans_id_tree_file_id('name1')
500
 
        name2 = mangle_tree.trans_id_tree_file_id('name2')
501
 
        mangle_tree.adjust_path('name2', root, name1)
502
 
        mangle_tree.adjust_path('name1', root, name2)
503
 
 
504
 
        #tests for deleting parent directories
505
 
        ddir = mangle_tree.trans_id_tree_file_id('ddir')
506
 
        mangle_tree.delete_contents(ddir)
507
 
        dfile = mangle_tree.trans_id_tree_file_id('dfile')
508
 
        mangle_tree.delete_versioned(dfile)
509
 
        mangle_tree.unversion_file(dfile)
510
 
        mfile = mangle_tree.trans_id_tree_file_id('mfile')
511
 
        mangle_tree.adjust_path('mfile', root, mfile)
512
 
 
513
 
        #tests for adding parent directories
514
 
        newdir = mangle_tree.new_directory('new_directory', root, 'newdir')
515
 
        mfile2 = mangle_tree.trans_id_tree_file_id('mfile2')
516
 
        mangle_tree.adjust_path('mfile2', newdir, mfile2)
517
 
        mangle_tree.new_file('newfile', newdir, 'hello3', 'dfile')
518
 
        self.assertEqual(mangle_tree.final_file_id(mfile2), 'mfile2')
519
 
        self.assertEqual(mangle_tree.final_parent(mfile2), newdir)
520
 
        self.assertEqual(mangle_tree.final_file_id(mfile2), 'mfile2')
521
 
        mangle_tree.apply()
522
 
        self.assertEqual(file(self.wt.abspath('name1')).read(), 'hello2')
523
 
        self.assertEqual(file(self.wt.abspath('name2')).read(), 'hello1')
524
 
        mfile2_path = self.wt.abspath(pathjoin('new_directory','mfile2'))
525
 
        self.assertEqual(mangle_tree.final_parent(mfile2), newdir)
526
 
        self.assertEqual(file(mfile2_path).read(), 'later2')
527
 
        self.assertEqual(self.wt.id2path('mfile2'), 'new_directory/mfile2')
528
 
        self.assertEqual(self.wt.path2id('new_directory/mfile2'), 'mfile2')
529
 
        newfile_path = self.wt.abspath(pathjoin('new_directory','newfile'))
530
 
        self.assertEqual(file(newfile_path).read(), 'hello3')
531
 
        self.assertEqual(self.wt.path2id('dying_directory'), 'ddir')
532
 
        self.assertIs(self.wt.path2id('dying_directory/dying_file'), None)
533
 
        mfile2_path = self.wt.abspath(pathjoin('new_directory','mfile2'))
534
 
 
535
 
    def test_both_rename(self):
536
 
        create_tree,root = self.get_transform()
537
 
        newdir = create_tree.new_directory('selftest', root, 'selftest-id')
538
 
        create_tree.new_file('blackbox.py', newdir, 'hello1', 'blackbox-id')
539
 
        create_tree.apply()
540
 
        mangle_tree,root = self.get_transform()
541
 
        selftest = mangle_tree.trans_id_tree_file_id('selftest-id')
542
 
        blackbox = mangle_tree.trans_id_tree_file_id('blackbox-id')
543
 
        mangle_tree.adjust_path('test', root, selftest)
544
 
        mangle_tree.adjust_path('test_too_much', root, selftest)
545
 
        mangle_tree.set_executability(True, blackbox)
546
 
        mangle_tree.apply()
547
 
 
548
 
    def test_both_rename2(self):
549
 
        create_tree,root = self.get_transform()
550
 
        bzrlib = create_tree.new_directory('bzrlib', root, 'bzrlib-id')
551
 
        tests = create_tree.new_directory('tests', bzrlib, 'tests-id')
552
 
        blackbox = create_tree.new_directory('blackbox', tests, 'blackbox-id')
553
 
        create_tree.new_file('test_too_much.py', blackbox, 'hello1',
554
 
                             'test_too_much-id')
555
 
        create_tree.apply()
556
 
        mangle_tree,root = self.get_transform()
557
 
        bzrlib = mangle_tree.trans_id_tree_file_id('bzrlib-id')
558
 
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
559
 
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
560
 
        mangle_tree.adjust_path('selftest', bzrlib, tests)
561
 
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
562
 
        mangle_tree.set_executability(True, test_too_much)
563
 
        mangle_tree.apply()
564
 
 
565
 
    def test_both_rename3(self):
566
 
        create_tree,root = self.get_transform()
567
 
        tests = create_tree.new_directory('tests', root, 'tests-id')
568
 
        create_tree.new_file('test_too_much.py', tests, 'hello1',
569
 
                             'test_too_much-id')
570
 
        create_tree.apply()
571
 
        mangle_tree,root = self.get_transform()
572
 
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
573
 
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
574
 
        mangle_tree.adjust_path('selftest', root, tests)
575
 
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
576
 
        mangle_tree.set_executability(True, test_too_much)
577
 
        mangle_tree.apply()
578
 
 
579
 
    def test_move_dangling_ie(self):
580
 
        create_tree, root = self.get_transform()
581
 
        # prepare tree
582
 
        root = create_tree.root
583
 
        create_tree.new_file('name1', root, 'hello1', 'name1')
584
 
        create_tree.apply()
585
 
        delete_contents, root = self.get_transform()
586
 
        file = delete_contents.trans_id_tree_file_id('name1')
587
 
        delete_contents.delete_contents(file)
588
 
        delete_contents.apply()
589
 
        move_id, root = self.get_transform()
590
 
        name1 = move_id.trans_id_tree_file_id('name1')
591
 
        newdir = move_id.new_directory('dir', root, 'newdir')
592
 
        move_id.adjust_path('name2', newdir, name1)
593
 
        move_id.apply()
594
 
 
595
 
    def test_replace_dangling_ie(self):
596
 
        create_tree, root = self.get_transform()
597
 
        # prepare tree
598
 
        root = create_tree.root
599
 
        create_tree.new_file('name1', root, 'hello1', 'name1')
600
 
        create_tree.apply()
601
 
        delete_contents = TreeTransform(self.wt)
602
 
        self.addCleanup(delete_contents.finalize)
603
 
        file = delete_contents.trans_id_tree_file_id('name1')
604
 
        delete_contents.delete_contents(file)
605
 
        delete_contents.apply()
606
 
        delete_contents.finalize()
607
 
        replace = TreeTransform(self.wt)
608
 
        self.addCleanup(replace.finalize)
609
 
        name2 = replace.new_file('name2', root, 'hello2', 'name1')
610
 
        conflicts = replace.find_conflicts()
611
 
        name1 = replace.trans_id_tree_file_id('name1')
612
 
        self.assertEqual(conflicts, [('duplicate id', name1, name2)])
613
 
        resolve_conflicts(replace)
614
 
        replace.apply()
615
 
 
616
 
    def _test_symlinks(self, link_name1,link_target1,
617
 
                       link_name2, link_target2):
618
 
 
619
 
        def ozpath(p): return 'oz/' + p
620
 
 
621
 
        self.requireFeature(SymlinkFeature)
622
 
        transform, root = self.get_transform()
623
 
        oz_id = transform.new_directory('oz', root, 'oz-id')
624
 
        wizard = transform.new_symlink(link_name1, oz_id, link_target1,
625
 
                                       'wizard-id')
626
 
        wiz_id = transform.create_path(link_name2, oz_id)
627
 
        transform.create_symlink(link_target2, wiz_id)
628
 
        transform.version_file('wiz-id2', wiz_id)
629
 
        transform.set_executability(True, wiz_id)
630
 
        self.assertEqual(transform.find_conflicts(),
631
 
                         [('non-file executability', wiz_id)])
632
 
        transform.set_executability(None, wiz_id)
633
 
        transform.apply()
634
 
        self.assertEqual(self.wt.path2id(ozpath(link_name1)), 'wizard-id')
635
 
        self.assertEqual('symlink',
636
 
                         file_kind(self.wt.abspath(ozpath(link_name1))))
637
 
        self.assertEqual(link_target2,
638
 
                         osutils.readlink(self.wt.abspath(ozpath(link_name2))))
639
 
        self.assertEqual(link_target1,
640
 
                         osutils.readlink(self.wt.abspath(ozpath(link_name1))))
641
 
 
642
 
    def test_symlinks(self):
643
 
        self._test_symlinks('wizard', 'wizard-target',
644
 
                            'wizard2', 'behind_curtain')
645
 
 
646
 
    def test_symlinks_unicode(self):
647
 
        self.requireFeature(tests.UnicodeFilenameFeature)
648
 
        self._test_symlinks(u'\N{Euro Sign}wizard',
649
 
                            u'wizard-targ\N{Euro Sign}t',
650
 
                            u'\N{Euro Sign}wizard2',
651
 
                            u'b\N{Euro Sign}hind_curtain')
652
 
 
653
 
    def test_unable_create_symlink(self):
654
 
        def tt_helper():
655
 
            wt = self.make_branch_and_tree('.')
656
 
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
657
 
            try:
658
 
                tt.new_symlink('foo', tt.root, 'bar')
659
 
                tt.apply()
660
 
            finally:
661
 
                wt.unlock()
662
 
        os_symlink = getattr(os, 'symlink', None)
663
 
        os.symlink = None
664
 
        try:
665
 
            err = self.assertRaises(errors.UnableCreateSymlink, tt_helper)
666
 
            self.assertEquals(
667
 
                "Unable to create symlink 'foo' on this platform",
668
 
                str(err))
669
 
        finally:
670
 
            if os_symlink:
671
 
                os.symlink = os_symlink
672
 
 
673
 
    def get_conflicted(self):
674
 
        create,root = self.get_transform()
675
 
        create.new_file('dorothy', root, 'dorothy', 'dorothy-id')
676
 
        oz = create.new_directory('oz', root, 'oz-id')
677
 
        create.new_directory('emeraldcity', oz, 'emerald-id')
678
 
        create.apply()
679
 
        conflicts,root = self.get_transform()
680
 
        # set up duplicate entry, duplicate id
681
 
        new_dorothy = conflicts.new_file('dorothy', root, 'dorothy',
682
 
                                         'dorothy-id')
683
 
        old_dorothy = conflicts.trans_id_tree_file_id('dorothy-id')
684
 
        oz = conflicts.trans_id_tree_file_id('oz-id')
685
 
        # set up DeletedParent parent conflict
686
 
        conflicts.delete_versioned(oz)
687
 
        emerald = conflicts.trans_id_tree_file_id('emerald-id')
688
 
        # set up MissingParent conflict
689
 
        munchkincity = conflicts.trans_id_file_id('munchkincity-id')
690
 
        conflicts.adjust_path('munchkincity', root, munchkincity)
691
 
        conflicts.new_directory('auntem', munchkincity, 'auntem-id')
692
 
        # set up parent loop
693
 
        conflicts.adjust_path('emeraldcity', emerald, emerald)
694
 
        return conflicts, emerald, oz, old_dorothy, new_dorothy
695
 
 
696
 
    def test_conflict_resolution(self):
697
 
        conflicts, emerald, oz, old_dorothy, new_dorothy =\
698
 
            self.get_conflicted()
699
 
        resolve_conflicts(conflicts)
700
 
        self.assertEqual(conflicts.final_name(old_dorothy), 'dorothy.moved')
701
 
        self.assertIs(conflicts.final_file_id(old_dorothy), None)
702
 
        self.assertEqual(conflicts.final_name(new_dorothy), 'dorothy')
703
 
        self.assertEqual(conflicts.final_file_id(new_dorothy), 'dorothy-id')
704
 
        self.assertEqual(conflicts.final_parent(emerald), oz)
705
 
        conflicts.apply()
706
 
 
707
 
    def test_cook_conflicts(self):
708
 
        tt, emerald, oz, old_dorothy, new_dorothy = self.get_conflicted()
709
 
        raw_conflicts = resolve_conflicts(tt)
710
 
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
711
 
        duplicate = DuplicateEntry('Moved existing file to', 'dorothy.moved',
712
 
                                   'dorothy', None, 'dorothy-id')
713
 
        self.assertEqual(cooked_conflicts[0], duplicate)
714
 
        duplicate_id = DuplicateID('Unversioned existing file',
715
 
                                   'dorothy.moved', 'dorothy', None,
716
 
                                   'dorothy-id')
717
 
        self.assertEqual(cooked_conflicts[1], duplicate_id)
718
 
        missing_parent = MissingParent('Created directory', 'munchkincity',
719
 
                                       'munchkincity-id')
720
 
        deleted_parent = DeletingParent('Not deleting', 'oz', 'oz-id')
721
 
        self.assertEqual(cooked_conflicts[2], missing_parent)
722
 
        unversioned_parent = UnversionedParent('Versioned directory',
723
 
                                               'munchkincity',
724
 
                                               'munchkincity-id')
725
 
        unversioned_parent2 = UnversionedParent('Versioned directory', 'oz',
726
 
                                               'oz-id')
727
 
        self.assertEqual(cooked_conflicts[3], unversioned_parent)
728
 
        parent_loop = ParentLoop('Cancelled move', 'oz/emeraldcity',
729
 
                                 'oz/emeraldcity', 'emerald-id', 'emerald-id')
730
 
        self.assertEqual(cooked_conflicts[4], deleted_parent)
731
 
        self.assertEqual(cooked_conflicts[5], unversioned_parent2)
732
 
        self.assertEqual(cooked_conflicts[6], parent_loop)
733
 
        self.assertEqual(len(cooked_conflicts), 7)
734
 
        tt.finalize()
735
 
 
736
 
    def test_string_conflicts(self):
737
 
        tt, emerald, oz, old_dorothy, new_dorothy = self.get_conflicted()
738
 
        raw_conflicts = resolve_conflicts(tt)
739
 
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
740
 
        tt.finalize()
741
 
        conflicts_s = [str(c) for c in cooked_conflicts]
742
 
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
743
 
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
744
 
                                         'Moved existing file to '
745
 
                                         'dorothy.moved.')
746
 
        self.assertEqual(conflicts_s[1], 'Conflict adding id to dorothy.  '
747
 
                                         'Unversioned existing file '
748
 
                                         'dorothy.moved.')
749
 
        self.assertEqual(conflicts_s[2], 'Conflict adding files to'
750
 
                                         ' munchkincity.  Created directory.')
751
 
        self.assertEqual(conflicts_s[3], 'Conflict because munchkincity is not'
752
 
                                         ' versioned, but has versioned'
753
 
                                         ' children.  Versioned directory.')
754
 
        self.assertEqualDiff(conflicts_s[4], "Conflict: can't delete oz because it"
755
 
                                         " is not empty.  Not deleting.")
756
 
        self.assertEqual(conflicts_s[5], 'Conflict because oz is not'
757
 
                                         ' versioned, but has versioned'
758
 
                                         ' children.  Versioned directory.')
759
 
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
760
 
                                         ' oz/emeraldcity. Cancelled move.')
761
 
 
762
 
    def prepare_wrong_parent_kind(self):
763
 
        tt, root = self.get_transform()
764
 
        tt.new_file('parent', root, 'contents', 'parent-id')
765
 
        tt.apply()
766
 
        tt, root = self.get_transform()
767
 
        parent_id = tt.trans_id_file_id('parent-id')
768
 
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
769
 
        return tt
770
 
 
771
 
    def test_find_conflicts_wrong_parent_kind(self):
772
 
        tt = self.prepare_wrong_parent_kind()
773
 
        tt.find_conflicts()
774
 
 
775
 
    def test_resolve_conflicts_wrong_existing_parent_kind(self):
776
 
        tt = self.prepare_wrong_parent_kind()
777
 
        raw_conflicts = resolve_conflicts(tt)
778
 
        self.assertEqual(set([('non-directory parent', 'Created directory',
779
 
                         'new-3')]), raw_conflicts)
780
 
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
781
 
        self.assertEqual([NonDirectoryParent('Created directory', 'parent.new',
782
 
        'parent-id')], cooked_conflicts)
783
 
        tt.apply()
784
 
        self.assertEqual(None, self.wt.path2id('parent'))
785
 
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
786
 
 
787
 
    def test_resolve_conflicts_wrong_new_parent_kind(self):
788
 
        tt, root = self.get_transform()
789
 
        parent_id = tt.new_directory('parent', root, 'parent-id')
790
 
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
791
 
        tt.apply()
792
 
        tt, root = self.get_transform()
793
 
        parent_id = tt.trans_id_file_id('parent-id')
794
 
        tt.delete_contents(parent_id)
795
 
        tt.create_file('contents', parent_id)
796
 
        raw_conflicts = resolve_conflicts(tt)
797
 
        self.assertEqual(set([('non-directory parent', 'Created directory',
798
 
                         'new-3')]), raw_conflicts)
799
 
        tt.apply()
800
 
        self.assertEqual(None, self.wt.path2id('parent'))
801
 
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
802
 
 
803
 
    def test_resolve_conflicts_wrong_parent_kind_unversioned(self):
804
 
        tt, root = self.get_transform()
805
 
        parent_id = tt.new_directory('parent', root)
806
 
        tt.new_file('child,', parent_id, 'contents2')
807
 
        tt.apply()
808
 
        tt, root = self.get_transform()
809
 
        parent_id = tt.trans_id_tree_path('parent')
810
 
        tt.delete_contents(parent_id)
811
 
        tt.create_file('contents', parent_id)
812
 
        resolve_conflicts(tt)
813
 
        tt.apply()
814
 
        self.assertIs(None, self.wt.path2id('parent'))
815
 
        self.assertIs(None, self.wt.path2id('parent.new'))
816
 
 
817
 
    def test_moving_versioned_directories(self):
818
 
        create, root = self.get_transform()
819
 
        kansas = create.new_directory('kansas', root, 'kansas-id')
820
 
        create.new_directory('house', kansas, 'house-id')
821
 
        create.new_directory('oz', root, 'oz-id')
822
 
        create.apply()
823
 
        cyclone, root = self.get_transform()
824
 
        oz = cyclone.trans_id_tree_file_id('oz-id')
825
 
        house = cyclone.trans_id_tree_file_id('house-id')
826
 
        cyclone.adjust_path('house', oz, house)
827
 
        cyclone.apply()
828
 
 
829
 
    def test_moving_root(self):
830
 
        create, root = self.get_transform()
831
 
        fun = create.new_directory('fun', root, 'fun-id')
832
 
        create.new_directory('sun', root, 'sun-id')
833
 
        create.new_directory('moon', root, 'moon')
834
 
        create.apply()
835
 
        transform, root = self.get_transform()
836
 
        transform.adjust_root_path('oldroot', fun)
837
 
        new_root = transform.trans_id_tree_path('')
838
 
        transform.version_file('new-root', new_root)
839
 
        transform.apply()
840
 
 
841
 
    def test_renames(self):
842
 
        create, root = self.get_transform()
843
 
        old = create.new_directory('old-parent', root, 'old-id')
844
 
        intermediate = create.new_directory('intermediate', old, 'im-id')
845
 
        myfile = create.new_file('myfile', intermediate, 'myfile-text',
846
 
                                 'myfile-id')
847
 
        create.apply()
848
 
        rename, root = self.get_transform()
849
 
        old = rename.trans_id_file_id('old-id')
850
 
        rename.adjust_path('new', root, old)
851
 
        myfile = rename.trans_id_file_id('myfile-id')
852
 
        rename.set_executability(True, myfile)
853
 
        rename.apply()
854
 
 
855
 
    def test_set_executability_order(self):
856
 
        """Ensure that executability behaves the same, no matter what order.
857
 
 
858
 
        - create file and set executability simultaneously
859
 
        - create file and set executability afterward
860
 
        - unsetting the executability of a file whose executability has not been
861
 
        declared should throw an exception (this may happen when a
862
 
        merge attempts to create a file with a duplicate ID)
863
 
        """
864
 
        transform, root = self.get_transform()
865
 
        wt = transform._tree
866
 
        wt.lock_read()
867
 
        self.addCleanup(wt.unlock)
868
 
        transform.new_file('set_on_creation', root, 'Set on creation', 'soc',
869
 
                           True)
870
 
        sac = transform.new_file('set_after_creation', root,
871
 
                                 'Set after creation', 'sac')
872
 
        transform.set_executability(True, sac)
873
 
        uws = transform.new_file('unset_without_set', root, 'Unset badly',
874
 
                                 'uws')
875
 
        self.assertRaises(KeyError, transform.set_executability, None, uws)
876
 
        transform.apply()
877
 
        self.assertTrue(wt.is_executable('soc'))
878
 
        self.assertTrue(wt.is_executable('sac'))
879
 
 
880
 
    def test_preserve_mode(self):
881
 
        """File mode is preserved when replacing content"""
882
 
        if sys.platform == 'win32':
883
 
            raise TestSkipped('chmod has no effect on win32')
884
 
        transform, root = self.get_transform()
885
 
        transform.new_file('file1', root, 'contents', 'file1-id', True)
886
 
        transform.apply()
887
 
        self.wt.lock_write()
888
 
        self.addCleanup(self.wt.unlock)
889
 
        self.assertTrue(self.wt.is_executable('file1-id'))
890
 
        transform, root = self.get_transform()
891
 
        file1_id = transform.trans_id_tree_file_id('file1-id')
892
 
        transform.delete_contents(file1_id)
893
 
        transform.create_file('contents2', file1_id)
894
 
        transform.apply()
895
 
        self.assertTrue(self.wt.is_executable('file1-id'))
896
 
 
897
 
    def test__set_mode_stats_correctly(self):
898
 
        """_set_mode stats to determine file mode."""
899
 
        if sys.platform == 'win32':
900
 
            raise TestSkipped('chmod has no effect on win32')
901
 
 
902
 
        stat_paths = []
903
 
        real_stat = os.stat
904
 
        def instrumented_stat(path):
905
 
            stat_paths.append(path)
906
 
            return real_stat(path)
907
 
 
908
 
        transform, root = self.get_transform()
909
 
 
910
 
        bar1_id = transform.new_file('bar', root, 'bar contents 1\n',
911
 
                                     file_id='bar-id-1', executable=False)
912
 
        transform.apply()
913
 
 
914
 
        transform, root = self.get_transform()
915
 
        bar1_id = transform.trans_id_tree_path('bar')
916
 
        bar2_id = transform.trans_id_tree_path('bar2')
917
 
        try:
918
 
            os.stat = instrumented_stat
919
 
            transform.create_file('bar2 contents\n', bar2_id, mode_id=bar1_id)
920
 
        finally:
921
 
            os.stat = real_stat
922
 
            transform.finalize()
923
 
 
924
 
        bar1_abspath = self.wt.abspath('bar')
925
 
        self.assertEqual([bar1_abspath], stat_paths)
926
 
 
927
 
    def test_iter_changes(self):
928
 
        self.wt.set_root_id('eert_toor')
929
 
        transform, root = self.get_transform()
930
 
        transform.new_file('old', root, 'blah', 'id-1', True)
931
 
        transform.apply()
932
 
        transform, root = self.get_transform()
933
 
        try:
934
 
            self.assertEqual([], list(transform.iter_changes()))
935
 
            old = transform.trans_id_tree_file_id('id-1')
936
 
            transform.unversion_file(old)
937
 
            self.assertEqual([('id-1', ('old', None), False, (True, False),
938
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
939
 
                (True, True))], list(transform.iter_changes()))
940
 
            transform.new_directory('new', root, 'id-1')
941
 
            self.assertEqual([('id-1', ('old', 'new'), True, (True, True),
942
 
                ('eert_toor', 'eert_toor'), ('old', 'new'),
943
 
                ('file', 'directory'),
944
 
                (True, False))], list(transform.iter_changes()))
945
 
        finally:
946
 
            transform.finalize()
947
 
 
948
 
    def test_iter_changes_new(self):
949
 
        self.wt.set_root_id('eert_toor')
950
 
        transform, root = self.get_transform()
951
 
        transform.new_file('old', root, 'blah')
952
 
        transform.apply()
953
 
        transform, root = self.get_transform()
954
 
        try:
955
 
            old = transform.trans_id_tree_path('old')
956
 
            transform.version_file('id-1', old)
957
 
            self.assertEqual([('id-1', (None, 'old'), False, (False, True),
958
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
959
 
                (False, False))], list(transform.iter_changes()))
960
 
        finally:
961
 
            transform.finalize()
962
 
 
963
 
    def test_iter_changes_modifications(self):
964
 
        self.wt.set_root_id('eert_toor')
965
 
        transform, root = self.get_transform()
966
 
        transform.new_file('old', root, 'blah', 'id-1')
967
 
        transform.new_file('new', root, 'blah')
968
 
        transform.new_directory('subdir', root, 'subdir-id')
969
 
        transform.apply()
970
 
        transform, root = self.get_transform()
971
 
        try:
972
 
            old = transform.trans_id_tree_path('old')
973
 
            subdir = transform.trans_id_tree_file_id('subdir-id')
974
 
            new = transform.trans_id_tree_path('new')
975
 
            self.assertEqual([], list(transform.iter_changes()))
976
 
 
977
 
            #content deletion
978
 
            transform.delete_contents(old)
979
 
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
980
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', None),
981
 
                (False, False))], list(transform.iter_changes()))
982
 
 
983
 
            #content change
984
 
            transform.create_file('blah', old)
985
 
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
986
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
987
 
                (False, False))], list(transform.iter_changes()))
988
 
            transform.cancel_deletion(old)
989
 
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
990
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
991
 
                (False, False))], list(transform.iter_changes()))
992
 
            transform.cancel_creation(old)
993
 
 
994
 
            # move file_id to a different file
995
 
            self.assertEqual([], list(transform.iter_changes()))
996
 
            transform.unversion_file(old)
997
 
            transform.version_file('id-1', new)
998
 
            transform.adjust_path('old', root, new)
999
 
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
1000
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
1001
 
                (False, False))], list(transform.iter_changes()))
1002
 
            transform.cancel_versioning(new)
1003
 
            transform._removed_id = set()
1004
 
 
1005
 
            #execute bit
1006
 
            self.assertEqual([], list(transform.iter_changes()))
1007
 
            transform.set_executability(True, old)
1008
 
            self.assertEqual([('id-1', ('old', 'old'), False, (True, True),
1009
 
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
1010
 
                (False, True))], list(transform.iter_changes()))
1011
 
            transform.set_executability(None, old)
1012
 
 
1013
 
            # filename
1014
 
            self.assertEqual([], list(transform.iter_changes()))
1015
 
            transform.adjust_path('new', root, old)
1016
 
            transform._new_parent = {}
1017
 
            self.assertEqual([('id-1', ('old', 'new'), False, (True, True),
1018
 
                ('eert_toor', 'eert_toor'), ('old', 'new'), ('file', 'file'),
1019
 
                (False, False))], list(transform.iter_changes()))
1020
 
            transform._new_name = {}
1021
 
 
1022
 
            # parent directory
1023
 
            self.assertEqual([], list(transform.iter_changes()))
1024
 
            transform.adjust_path('new', subdir, old)
1025
 
            transform._new_name = {}
1026
 
            self.assertEqual([('id-1', ('old', 'subdir/old'), False,
1027
 
                (True, True), ('eert_toor', 'subdir-id'), ('old', 'old'),
1028
 
                ('file', 'file'), (False, False))],
1029
 
                list(transform.iter_changes()))
1030
 
            transform._new_path = {}
1031
 
 
1032
 
        finally:
1033
 
            transform.finalize()
1034
 
 
1035
 
    def test_iter_changes_modified_bleed(self):
1036
 
        self.wt.set_root_id('eert_toor')
1037
 
        """Modified flag should not bleed from one change to another"""
1038
 
        # unfortunately, we have no guarantee that file1 (which is modified)
1039
 
        # will be applied before file2.  And if it's applied after file2, it
1040
 
        # obviously can't bleed into file2's change output.  But for now, it
1041
 
        # works.
1042
 
        transform, root = self.get_transform()
1043
 
        transform.new_file('file1', root, 'blah', 'id-1')
1044
 
        transform.new_file('file2', root, 'blah', 'id-2')
1045
 
        transform.apply()
1046
 
        transform, root = self.get_transform()
1047
 
        try:
1048
 
            transform.delete_contents(transform.trans_id_file_id('id-1'))
1049
 
            transform.set_executability(True,
1050
 
            transform.trans_id_file_id('id-2'))
1051
 
            self.assertEqual([('id-1', (u'file1', u'file1'), True, (True, True),
1052
 
                ('eert_toor', 'eert_toor'), ('file1', u'file1'),
1053
 
                ('file', None), (False, False)),
1054
 
                ('id-2', (u'file2', u'file2'), False, (True, True),
1055
 
                ('eert_toor', 'eert_toor'), ('file2', u'file2'),
1056
 
                ('file', 'file'), (False, True))],
1057
 
                list(transform.iter_changes()))
1058
 
        finally:
1059
 
            transform.finalize()
1060
 
 
1061
 
    def test_iter_changes_move_missing(self):
1062
 
        """Test moving ids with no files around"""
1063
 
        self.wt.set_root_id('toor_eert')
1064
 
        # Need two steps because versioning a non-existant file is a conflict.
1065
 
        transform, root = self.get_transform()
1066
 
        transform.new_directory('floater', root, 'floater-id')
1067
 
        transform.apply()
1068
 
        transform, root = self.get_transform()
1069
 
        transform.delete_contents(transform.trans_id_tree_path('floater'))
1070
 
        transform.apply()
1071
 
        transform, root = self.get_transform()
1072
 
        floater = transform.trans_id_tree_path('floater')
1073
 
        try:
1074
 
            transform.adjust_path('flitter', root, floater)
1075
 
            self.assertEqual([('floater-id', ('floater', 'flitter'), False,
1076
 
            (True, True), ('toor_eert', 'toor_eert'), ('floater', 'flitter'),
1077
 
            (None, None), (False, False))], list(transform.iter_changes()))
1078
 
        finally:
1079
 
            transform.finalize()
1080
 
 
1081
 
    def test_iter_changes_pointless(self):
1082
 
        """Ensure that no-ops are not treated as modifications"""
1083
 
        self.wt.set_root_id('eert_toor')
1084
 
        transform, root = self.get_transform()
1085
 
        transform.new_file('old', root, 'blah', 'id-1')
1086
 
        transform.new_directory('subdir', root, 'subdir-id')
1087
 
        transform.apply()
1088
 
        transform, root = self.get_transform()
1089
 
        try:
1090
 
            old = transform.trans_id_tree_path('old')
1091
 
            subdir = transform.trans_id_tree_file_id('subdir-id')
1092
 
            self.assertEqual([], list(transform.iter_changes()))
1093
 
            transform.delete_contents(subdir)
1094
 
            transform.create_directory(subdir)
1095
 
            transform.set_executability(False, old)
1096
 
            transform.unversion_file(old)
1097
 
            transform.version_file('id-1', old)
1098
 
            transform.adjust_path('old', root, old)
1099
 
            self.assertEqual([], list(transform.iter_changes()))
1100
 
        finally:
1101
 
            transform.finalize()
1102
 
 
1103
 
    def test_rename_count(self):
1104
 
        transform, root = self.get_transform()
1105
 
        transform.new_file('name1', root, 'contents')
1106
 
        self.assertEqual(transform.rename_count, 0)
1107
 
        transform.apply()
1108
 
        self.assertEqual(transform.rename_count, 1)
1109
 
        transform2, root = self.get_transform()
1110
 
        transform2.adjust_path('name2', root,
1111
 
                               transform2.trans_id_tree_path('name1'))
1112
 
        self.assertEqual(transform2.rename_count, 0)
1113
 
        transform2.apply()
1114
 
        self.assertEqual(transform2.rename_count, 2)
1115
 
 
1116
 
    def test_change_parent(self):
1117
 
        """Ensure that after we change a parent, the results are still right.
1118
 
 
1119
 
        Renames and parent changes on pending transforms can happen as part
1120
 
        of conflict resolution, and are explicitly permitted by the
1121
 
        TreeTransform API.
1122
 
 
1123
 
        This test ensures they work correctly with the rename-avoidance
1124
 
        optimization.
1125
 
        """
1126
 
        transform, root = self.get_transform()
1127
 
        parent1 = transform.new_directory('parent1', root)
1128
 
        child1 = transform.new_file('child1', parent1, 'contents')
1129
 
        parent2 = transform.new_directory('parent2', root)
1130
 
        transform.adjust_path('child1', parent2, child1)
1131
 
        transform.apply()
1132
 
        self.failIfExists(self.wt.abspath('parent1/child1'))
1133
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1134
 
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1135
 
        # no rename for child1 (counting only renames during apply)
1136
 
        self.failUnlessEqual(2, transform.rename_count)
1137
 
 
1138
 
    def test_cancel_parent(self):
1139
 
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1140
 
 
1141
 
        This is like the test_change_parent, except that we cancel the parent
1142
 
        before adjusting the path.  The transform must detect that the
1143
 
        directory is non-empty, and move children to safe locations.
1144
 
        """
1145
 
        transform, root = self.get_transform()
1146
 
        parent1 = transform.new_directory('parent1', root)
1147
 
        child1 = transform.new_file('child1', parent1, 'contents')
1148
 
        child2 = transform.new_file('child2', parent1, 'contents')
1149
 
        try:
1150
 
            transform.cancel_creation(parent1)
1151
 
        except OSError:
1152
 
            self.fail('Failed to move child1 before deleting parent1')
1153
 
        transform.cancel_creation(child2)
1154
 
        transform.create_directory(parent1)
1155
 
        try:
1156
 
            transform.cancel_creation(parent1)
1157
 
        # If the transform incorrectly believes that child2 is still in
1158
 
        # parent1's limbo directory, it will try to rename it and fail
1159
 
        # because was already moved by the first cancel_creation.
1160
 
        except OSError:
1161
 
            self.fail('Transform still thinks child2 is a child of parent1')
1162
 
        parent2 = transform.new_directory('parent2', root)
1163
 
        transform.adjust_path('child1', parent2, child1)
1164
 
        transform.apply()
1165
 
        self.failIfExists(self.wt.abspath('parent1'))
1166
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1167
 
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1168
 
        self.failUnlessEqual(2, transform.rename_count)
1169
 
 
1170
 
    def test_adjust_and_cancel(self):
1171
 
        """Make sure adjust_path keeps track of limbo children properly"""
1172
 
        transform, root = self.get_transform()
1173
 
        parent1 = transform.new_directory('parent1', root)
1174
 
        child1 = transform.new_file('child1', parent1, 'contents')
1175
 
        parent2 = transform.new_directory('parent2', root)
1176
 
        transform.adjust_path('child1', parent2, child1)
1177
 
        transform.cancel_creation(child1)
1178
 
        try:
1179
 
            transform.cancel_creation(parent1)
1180
 
        # if the transform thinks child1 is still in parent1's limbo
1181
 
        # directory, it will attempt to move it and fail.
1182
 
        except OSError:
1183
 
            self.fail('Transform still thinks child1 is a child of parent1')
1184
 
        transform.finalize()
1185
 
 
1186
 
    def test_noname_contents(self):
1187
 
        """TreeTransform should permit deferring naming files."""
1188
 
        transform, root = self.get_transform()
1189
 
        parent = transform.trans_id_file_id('parent-id')
1190
 
        try:
1191
 
            transform.create_directory(parent)
1192
 
        except KeyError:
1193
 
            self.fail("Can't handle contents with no name")
1194
 
        transform.finalize()
1195
 
 
1196
 
    def test_noname_contents_nested(self):
1197
 
        """TreeTransform should permit deferring naming files."""
1198
 
        transform, root = self.get_transform()
1199
 
        parent = transform.trans_id_file_id('parent-id')
1200
 
        try:
1201
 
            transform.create_directory(parent)
1202
 
        except KeyError:
1203
 
            self.fail("Can't handle contents with no name")
1204
 
        child = transform.new_directory('child', parent)
1205
 
        transform.adjust_path('parent', root, parent)
1206
 
        transform.apply()
1207
 
        self.failUnlessExists(self.wt.abspath('parent/child'))
1208
 
        self.assertEqual(1, transform.rename_count)
1209
 
 
1210
 
    def test_reuse_name(self):
1211
 
        """Avoid reusing the same limbo name for different files"""
1212
 
        transform, root = self.get_transform()
1213
 
        parent = transform.new_directory('parent', root)
1214
 
        child1 = transform.new_directory('child', parent)
1215
 
        try:
1216
 
            child2 = transform.new_directory('child', parent)
1217
 
        except OSError:
1218
 
            self.fail('Tranform tried to use the same limbo name twice')
1219
 
        transform.adjust_path('child2', parent, child2)
1220
 
        transform.apply()
1221
 
        # limbo/new-1 => parent, limbo/new-3 => parent/child2
1222
 
        # child2 is put into top-level limbo because child1 has already
1223
 
        # claimed the direct limbo path when child2 is created.  There is no
1224
 
        # advantage in renaming files once they're in top-level limbo, except
1225
 
        # as part of apply.
1226
 
        self.assertEqual(2, transform.rename_count)
1227
 
 
1228
 
    def test_reuse_when_first_moved(self):
1229
 
        """Don't avoid direct paths when it is safe to use them"""
1230
 
        transform, root = self.get_transform()
1231
 
        parent = transform.new_directory('parent', root)
1232
 
        child1 = transform.new_directory('child', parent)
1233
 
        transform.adjust_path('child1', parent, child1)
1234
 
        child2 = transform.new_directory('child', parent)
1235
 
        transform.apply()
1236
 
        # limbo/new-1 => parent
1237
 
        self.assertEqual(1, transform.rename_count)
1238
 
 
1239
 
    def test_reuse_after_cancel(self):
1240
 
        """Don't avoid direct paths when it is safe to use them"""
1241
 
        transform, root = self.get_transform()
1242
 
        parent2 = transform.new_directory('parent2', root)
1243
 
        child1 = transform.new_directory('child1', parent2)
1244
 
        transform.cancel_creation(parent2)
1245
 
        transform.create_directory(parent2)
1246
 
        child2 = transform.new_directory('child1', parent2)
1247
 
        transform.adjust_path('child2', parent2, child1)
1248
 
        transform.apply()
1249
 
        # limbo/new-1 => parent2, limbo/new-2 => parent2/child1
1250
 
        self.assertEqual(2, transform.rename_count)
1251
 
 
1252
 
    def test_finalize_order(self):
1253
 
        """Finalize must be done in child-to-parent order"""
1254
 
        transform, root = self.get_transform()
1255
 
        parent = transform.new_directory('parent', root)
1256
 
        child = transform.new_directory('child', parent)
1257
 
        try:
1258
 
            transform.finalize()
1259
 
        except OSError:
1260
 
            self.fail('Tried to remove parent before child1')
1261
 
 
1262
 
    def test_cancel_with_cancelled_child_should_succeed(self):
1263
 
        transform, root = self.get_transform()
1264
 
        parent = transform.new_directory('parent', root)
1265
 
        child = transform.new_directory('child', parent)
1266
 
        transform.cancel_creation(child)
1267
 
        transform.cancel_creation(parent)
1268
 
        transform.finalize()
1269
 
 
1270
 
    def test_rollback_on_directory_clash(self):
1271
 
        def tt_helper():
1272
 
            wt = self.make_branch_and_tree('.')
1273
 
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1274
 
            try:
1275
 
                foo = tt.new_directory('foo', tt.root)
1276
 
                tt.new_file('bar', foo, 'foobar')
1277
 
                baz = tt.new_directory('baz', tt.root)
1278
 
                tt.new_file('qux', baz, 'quux')
1279
 
                # Ask for a rename 'foo' -> 'baz'
1280
 
                tt.adjust_path('baz', tt.root, foo)
1281
 
                # Lie to tt that we've already resolved all conflicts.
1282
 
                tt.apply(no_conflicts=True)
1283
 
            except:
1284
 
                wt.unlock()
1285
 
                raise
1286
 
        # The rename will fail because the target directory is not empty (but
1287
 
        # raises FileExists anyway).
1288
 
        err = self.assertRaises(errors.FileExists, tt_helper)
1289
 
        self.assertContainsRe(str(err),
1290
 
            "^File exists: .+/baz")
1291
 
 
1292
 
    def test_two_directories_clash(self):
1293
 
        def tt_helper():
1294
 
            wt = self.make_branch_and_tree('.')
1295
 
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1296
 
            try:
1297
 
                foo_1 = tt.new_directory('foo', tt.root)
1298
 
                tt.new_directory('bar', foo_1)
1299
 
                # Adding the same directory with a different content
1300
 
                foo_2 = tt.new_directory('foo', tt.root)
1301
 
                tt.new_directory('baz', foo_2)
1302
 
                # Lie to tt that we've already resolved all conflicts.
1303
 
                tt.apply(no_conflicts=True)
1304
 
            except:
1305
 
                wt.unlock()
1306
 
                raise
1307
 
        err = self.assertRaises(errors.FileExists, tt_helper)
1308
 
        self.assertContainsRe(str(err),
1309
 
            "^File exists: .+/foo")
1310
 
 
1311
 
    def test_two_directories_clash_finalize(self):
1312
 
        def tt_helper():
1313
 
            wt = self.make_branch_and_tree('.')
1314
 
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1315
 
            try:
1316
 
                foo_1 = tt.new_directory('foo', tt.root)
1317
 
                tt.new_directory('bar', foo_1)
1318
 
                # Adding the same directory with a different content
1319
 
                foo_2 = tt.new_directory('foo', tt.root)
1320
 
                tt.new_directory('baz', foo_2)
1321
 
                # Lie to tt that we've already resolved all conflicts.
1322
 
                tt.apply(no_conflicts=True)
1323
 
            except:
1324
 
                tt.finalize()
1325
 
                raise
1326
 
        err = self.assertRaises(errors.FileExists, tt_helper)
1327
 
        self.assertContainsRe(str(err),
1328
 
            "^File exists: .+/foo")
1329
 
 
1330
 
    def test_file_to_directory(self):
1331
 
        wt = self.make_branch_and_tree('.')
1332
 
        self.build_tree(['foo'])
1333
 
        wt.add(['foo'])
1334
 
        wt.commit("one")
1335
 
        tt = TreeTransform(wt)
1336
 
        self.addCleanup(tt.finalize)
1337
 
        foo_trans_id = tt.trans_id_tree_path("foo")
1338
 
        tt.delete_contents(foo_trans_id)
1339
 
        tt.create_directory(foo_trans_id)
1340
 
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1341
 
        tt.create_file(["aa\n"], bar_trans_id)
1342
 
        tt.version_file("bar-1", bar_trans_id)
1343
 
        tt.apply()
1344
 
        self.failUnlessExists("foo/bar")
1345
 
        wt.lock_read()
1346
 
        try:
1347
 
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1348
 
                    "directory")
1349
 
        finally:
1350
 
            wt.unlock()
1351
 
        wt.commit("two")
1352
 
        changes = wt.changes_from(wt.basis_tree())
1353
 
        self.assertFalse(changes.has_changed(), changes)
1354
 
 
1355
 
    def test_file_to_symlink(self):
1356
 
        self.requireFeature(SymlinkFeature)
1357
 
        wt = self.make_branch_and_tree('.')
1358
 
        self.build_tree(['foo'])
1359
 
        wt.add(['foo'])
1360
 
        wt.commit("one")
1361
 
        tt = TreeTransform(wt)
1362
 
        self.addCleanup(tt.finalize)
1363
 
        foo_trans_id = tt.trans_id_tree_path("foo")
1364
 
        tt.delete_contents(foo_trans_id)
1365
 
        tt.create_symlink("bar", foo_trans_id)
1366
 
        tt.apply()
1367
 
        self.failUnlessExists("foo")
1368
 
        wt.lock_read()
1369
 
        self.addCleanup(wt.unlock)
1370
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1371
 
                "symlink")
1372
 
 
1373
 
    def test_dir_to_file(self):
1374
 
        wt = self.make_branch_and_tree('.')
1375
 
        self.build_tree(['foo/', 'foo/bar'])
1376
 
        wt.add(['foo', 'foo/bar'])
1377
 
        wt.commit("one")
1378
 
        tt = TreeTransform(wt)
1379
 
        self.addCleanup(tt.finalize)
1380
 
        foo_trans_id = tt.trans_id_tree_path("foo")
1381
 
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1382
 
        tt.delete_contents(foo_trans_id)
1383
 
        tt.delete_versioned(bar_trans_id)
1384
 
        tt.create_file(["aa\n"], foo_trans_id)
1385
 
        tt.apply()
1386
 
        self.failUnlessExists("foo")
1387
 
        wt.lock_read()
1388
 
        self.addCleanup(wt.unlock)
1389
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1390
 
                "file")
1391
 
 
1392
 
    def test_dir_to_hardlink(self):
1393
 
        self.requireFeature(HardlinkFeature)
1394
 
        wt = self.make_branch_and_tree('.')
1395
 
        self.build_tree(['foo/', 'foo/bar'])
1396
 
        wt.add(['foo', 'foo/bar'])
1397
 
        wt.commit("one")
1398
 
        tt = TreeTransform(wt)
1399
 
        self.addCleanup(tt.finalize)
1400
 
        foo_trans_id = tt.trans_id_tree_path("foo")
1401
 
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1402
 
        tt.delete_contents(foo_trans_id)
1403
 
        tt.delete_versioned(bar_trans_id)
1404
 
        self.build_tree(['baz'])
1405
 
        tt.create_hardlink("baz", foo_trans_id)
1406
 
        tt.apply()
1407
 
        self.failUnlessExists("foo")
1408
 
        self.failUnlessExists("baz")
1409
 
        wt.lock_read()
1410
 
        self.addCleanup(wt.unlock)
1411
 
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1412
 
                "file")
1413
 
 
1414
 
    def test_no_final_path(self):
1415
 
        transform, root = self.get_transform()
1416
 
        trans_id = transform.trans_id_file_id('foo')
1417
 
        transform.create_file('bar', trans_id)
1418
 
        transform.cancel_creation(trans_id)
1419
 
        transform.apply()
1420
 
 
1421
 
    def test_create_from_tree(self):
1422
 
        tree1 = self.make_branch_and_tree('tree1')
1423
 
        self.build_tree_contents([('tree1/foo/',), ('tree1/bar', 'baz')])
1424
 
        tree1.add(['foo', 'bar'], ['foo-id', 'bar-id'])
1425
 
        tree2 = self.make_branch_and_tree('tree2')
1426
 
        tt = TreeTransform(tree2)
1427
 
        foo_trans_id = tt.create_path('foo', tt.root)
1428
 
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
1429
 
        bar_trans_id = tt.create_path('bar', tt.root)
1430
 
        create_from_tree(tt, bar_trans_id, tree1, 'bar-id')
1431
 
        tt.apply()
1432
 
        self.assertEqual('directory', osutils.file_kind('tree2/foo'))
1433
 
        self.assertFileEqual('baz', 'tree2/bar')
1434
 
 
1435
 
    def test_create_from_tree_bytes(self):
1436
 
        """Provided lines are used instead of tree content."""
1437
 
        tree1 = self.make_branch_and_tree('tree1')
1438
 
        self.build_tree_contents([('tree1/foo', 'bar'),])
1439
 
        tree1.add('foo', 'foo-id')
1440
 
        tree2 = self.make_branch_and_tree('tree2')
1441
 
        tt = TreeTransform(tree2)
1442
 
        foo_trans_id = tt.create_path('foo', tt.root)
1443
 
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id', bytes='qux')
1444
 
        tt.apply()
1445
 
        self.assertFileEqual('qux', 'tree2/foo')
1446
 
 
1447
 
    def test_create_from_tree_symlink(self):
1448
 
        self.requireFeature(SymlinkFeature)
1449
 
        tree1 = self.make_branch_and_tree('tree1')
1450
 
        os.symlink('bar', 'tree1/foo')
1451
 
        tree1.add('foo', 'foo-id')
1452
 
        tt = TreeTransform(self.make_branch_and_tree('tree2'))
1453
 
        foo_trans_id = tt.create_path('foo', tt.root)
1454
 
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
1455
 
        tt.apply()
1456
 
        self.assertEqual('bar', os.readlink('tree2/foo'))
1457
 
 
1458
 
 
1459
89
class TransformGroup(object):
1460
90
 
1461
91
    def __init__(self, dirname, root_id):
1462
92
        self.name = dirname
1463
93
        os.mkdir(dirname)
1464
 
        self.wt = BzrDir.create_standalone_workingtree(dirname)
 
94
        self.wt = ControlDir.create_standalone_workingtree(dirname)
1465
95
        self.wt.set_root_id(root_id)
1466
96
        self.b = self.wt.branch
1467
 
        self.tt = TreeTransform(self.wt)
1468
 
        self.root = self.tt.trans_id_tree_file_id(self.wt.get_root_id())
 
97
        self.tt = self.wt.transform()
 
98
        self.root = self.tt.trans_id_tree_path('')
1469
99
 
1470
100
 
1471
101
def conflict_text(tree, merge):
1472
 
    template = '%s TREE\n%s%s\n%s%s MERGE-SOURCE\n'
1473
 
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
 
102
    template = b'%s TREE\n%s%s\n%s%s MERGE-SOURCE\n'
 
103
    return template % (b'<' * 7, tree, b'=' * 7, merge, b'>' * 7)
1474
104
 
1475
105
 
1476
106
class TestTransformMerge(TestCaseInTempDir):
1478
108
    def test_text_merge(self):
1479
109
        root_id = generate_ids.gen_root_id()
1480
110
        base = TransformGroup("base", root_id)
1481
 
        base.tt.new_file('a', base.root, 'a\nb\nc\nd\be\n', 'a')
1482
 
        base.tt.new_file('b', base.root, 'b1', 'b')
1483
 
        base.tt.new_file('c', base.root, 'c', 'c')
1484
 
        base.tt.new_file('d', base.root, 'd', 'd')
1485
 
        base.tt.new_file('e', base.root, 'e', 'e')
1486
 
        base.tt.new_file('f', base.root, 'f', 'f')
1487
 
        base.tt.new_directory('g', base.root, 'g')
1488
 
        base.tt.new_directory('h', base.root, 'h')
 
111
        base.tt.new_file('a', base.root, [b'a\nb\nc\nd\be\n'], b'a')
 
112
        base.tt.new_file('b', base.root, [b'b1'], b'b')
 
113
        base.tt.new_file('c', base.root, [b'c'], b'c')
 
114
        base.tt.new_file('d', base.root, [b'd'], b'd')
 
115
        base.tt.new_file('e', base.root, [b'e'], b'e')
 
116
        base.tt.new_file('f', base.root, [b'f'], b'f')
 
117
        base.tt.new_directory('g', base.root, b'g')
 
118
        base.tt.new_directory('h', base.root, b'h')
1489
119
        base.tt.apply()
1490
120
        other = TransformGroup("other", root_id)
1491
 
        other.tt.new_file('a', other.root, 'y\nb\nc\nd\be\n', 'a')
1492
 
        other.tt.new_file('b', other.root, 'b2', 'b')
1493
 
        other.tt.new_file('c', other.root, 'c2', 'c')
1494
 
        other.tt.new_file('d', other.root, 'd', 'd')
1495
 
        other.tt.new_file('e', other.root, 'e2', 'e')
1496
 
        other.tt.new_file('f', other.root, 'f', 'f')
1497
 
        other.tt.new_file('g', other.root, 'g', 'g')
1498
 
        other.tt.new_file('h', other.root, 'h\ni\nj\nk\n', 'h')
1499
 
        other.tt.new_file('i', other.root, 'h\ni\nj\nk\n', 'i')
 
121
        other.tt.new_file('a', other.root, [b'y\nb\nc\nd\be\n'], b'a')
 
122
        other.tt.new_file('b', other.root, [b'b2'], b'b')
 
123
        other.tt.new_file('c', other.root, [b'c2'], b'c')
 
124
        other.tt.new_file('d', other.root, [b'd'], b'd')
 
125
        other.tt.new_file('e', other.root, [b'e2'], b'e')
 
126
        other.tt.new_file('f', other.root, [b'f'], b'f')
 
127
        other.tt.new_file('g', other.root, [b'g'], b'g')
 
128
        other.tt.new_file('h', other.root, [b'h\ni\nj\nk\n'], b'h')
 
129
        other.tt.new_file('i', other.root, [b'h\ni\nj\nk\n'], b'i')
1500
130
        other.tt.apply()
1501
131
        this = TransformGroup("this", root_id)
1502
 
        this.tt.new_file('a', this.root, 'a\nb\nc\nd\bz\n', 'a')
1503
 
        this.tt.new_file('b', this.root, 'b', 'b')
1504
 
        this.tt.new_file('c', this.root, 'c', 'c')
1505
 
        this.tt.new_file('d', this.root, 'd2', 'd')
1506
 
        this.tt.new_file('e', this.root, 'e2', 'e')
1507
 
        this.tt.new_file('f', this.root, 'f', 'f')
1508
 
        this.tt.new_file('g', this.root, 'g', 'g')
1509
 
        this.tt.new_file('h', this.root, '1\n2\n3\n4\n', 'h')
1510
 
        this.tt.new_file('i', this.root, '1\n2\n3\n4\n', 'i')
 
132
        this.tt.new_file('a', this.root, [b'a\nb\nc\nd\bz\n'], b'a')
 
133
        this.tt.new_file('b', this.root, [b'b'], b'b')
 
134
        this.tt.new_file('c', this.root, [b'c'], b'c')
 
135
        this.tt.new_file('d', this.root, [b'd2'], b'd')
 
136
        this.tt.new_file('e', this.root, [b'e2'], b'e')
 
137
        this.tt.new_file('f', this.root, [b'f'], b'f')
 
138
        this.tt.new_file('g', this.root, [b'g'], b'g')
 
139
        this.tt.new_file('h', this.root, [b'1\n2\n3\n4\n'], b'h')
 
140
        this.tt.new_file('i', this.root, [b'1\n2\n3\n4\n'], b'i')
1511
141
        this.tt.apply()
1512
142
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1513
143
 
1514
144
        # textual merge
1515
 
        self.assertEqual(this.wt.get_file('a').read(), 'y\nb\nc\nd\bz\n')
 
145
        with this.wt.get_file(this.wt.id2path(b'a')) as f:
 
146
            self.assertEqual(f.read(), b'y\nb\nc\nd\bz\n')
1516
147
        # three-way text conflict
1517
 
        self.assertEqual(this.wt.get_file('b').read(),
1518
 
                         conflict_text('b', 'b2'))
 
148
        with this.wt.get_file(this.wt.id2path(b'b')) as f:
 
149
            self.assertEqual(f.read(), conflict_text(b'b', b'b2'))
1519
150
        # OTHER wins
1520
 
        self.assertEqual(this.wt.get_file('c').read(), 'c2')
 
151
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'c')).read(), b'c2')
1521
152
        # THIS wins
1522
 
        self.assertEqual(this.wt.get_file('d').read(), 'd2')
 
153
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'd')).read(), b'd2')
1523
154
        # Ambigious clean merge
1524
 
        self.assertEqual(this.wt.get_file('e').read(), 'e2')
 
155
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'e')).read(), b'e2')
1525
156
        # No change
1526
 
        self.assertEqual(this.wt.get_file('f').read(), 'f')
 
157
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'f')).read(), b'f')
1527
158
        # Correct correct results when THIS == OTHER
1528
 
        self.assertEqual(this.wt.get_file('g').read(), 'g')
 
159
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'g')).read(), b'g')
1529
160
        # Text conflict when THIS & OTHER are text and BASE is dir
1530
 
        self.assertEqual(this.wt.get_file('h').read(),
1531
 
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1532
 
        self.assertEqual(this.wt.get_file_byname('h.THIS').read(),
1533
 
                         '1\n2\n3\n4\n')
1534
 
        self.assertEqual(this.wt.get_file_byname('h.OTHER').read(),
1535
 
                         'h\ni\nj\nk\n')
 
161
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'h')).read(),
 
162
                         conflict_text(b'1\n2\n3\n4\n', b'h\ni\nj\nk\n'))
 
163
        self.assertEqual(this.wt.get_file('h.THIS').read(),
 
164
                         b'1\n2\n3\n4\n')
 
165
        self.assertEqual(this.wt.get_file('h.OTHER').read(),
 
166
                         b'h\ni\nj\nk\n')
1536
167
        self.assertEqual(file_kind(this.wt.abspath('h.BASE')), 'directory')
1537
 
        self.assertEqual(this.wt.get_file('i').read(),
1538
 
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1539
 
        self.assertEqual(this.wt.get_file_byname('i.THIS').read(),
1540
 
                         '1\n2\n3\n4\n')
1541
 
        self.assertEqual(this.wt.get_file_byname('i.OTHER').read(),
1542
 
                         'h\ni\nj\nk\n')
 
168
        self.assertEqual(this.wt.get_file(this.wt.id2path(b'i')).read(),
 
169
                         conflict_text(b'1\n2\n3\n4\n', b'h\ni\nj\nk\n'))
 
170
        self.assertEqual(this.wt.get_file('i.THIS').read(),
 
171
                         b'1\n2\n3\n4\n')
 
172
        self.assertEqual(this.wt.get_file('i.OTHER').read(),
 
173
                         b'h\ni\nj\nk\n')
1543
174
        self.assertEqual(os.path.exists(this.wt.abspath('i.BASE')), False)
1544
175
        modified = ['a', 'b', 'c', 'h', 'i']
1545
176
        merge_modified = this.wt.merge_modified()
1546
177
        self.assertSubset(merge_modified, modified)
1547
178
        self.assertEqual(len(merge_modified), len(modified))
1548
 
        file(this.wt.id2abspath('a'), 'wb').write('booga')
 
179
        with open(this.wt.abspath(this.wt.id2path(b'a')), 'wb') as f:
 
180
            f.write(b'booga')
1549
181
        modified.pop(0)
1550
182
        merge_modified = this.wt.merge_modified()
1551
183
        self.assertSubset(merge_modified, modified)
1560
192
        this = TransformGroup("THIS", root_id)
1561
193
        other = TransformGroup("OTHER", root_id)
1562
194
        for tg in this, base, other:
1563
 
            tg.tt.new_directory('a', tg.root, 'a')
1564
 
            tg.tt.new_symlink('b', tg.root, 'b', 'b')
1565
 
            tg.tt.new_file('c', tg.root, 'c', 'c')
1566
 
            tg.tt.new_symlink('d', tg.root, tg.name, 'd')
 
195
            tg.tt.new_directory('a', tg.root, b'a')
 
196
            tg.tt.new_symlink('b', tg.root, 'b', b'b')
 
197
            tg.tt.new_file('c', tg.root, [b'c'], b'c')
 
198
            tg.tt.new_symlink('d', tg.root, tg.name, b'd')
1567
199
        targets = ((base, 'base-e', 'base-f', None, None),
1568
200
                   (this, 'other-e', 'this-f', 'other-g', 'this-h'),
1569
201
                   (other, 'other-e', None, 'other-g', 'other-h'))
1571
203
            for link, target in (('e', e_target), ('f', f_target),
1572
204
                                 ('g', g_target), ('h', h_target)):
1573
205
                if target is not None:
1574
 
                    tg.tt.new_symlink(link, tg.root, target, link)
 
206
                    tg.tt.new_symlink(link, tg.root, target,
 
207
                                      link.encode('ascii'))
1575
208
 
1576
209
        for tg in this, base, other:
1577
210
            tg.tt.apply()
1580
213
        self.assertIs(os.path.islink(this.wt.abspath('b')), True)
1581
214
        self.assertIs(os.path.isfile(this.wt.abspath('c')), True)
1582
215
        for suffix in ('THIS', 'BASE', 'OTHER'):
1583
 
            self.assertEqual(os.readlink(this.wt.abspath('d.'+suffix)), suffix)
 
216
            self.assertEqual(os.readlink(
 
217
                this.wt.abspath('d.' + suffix)), suffix)
1584
218
        self.assertIs(os.path.lexists(this.wt.abspath('d')), False)
1585
 
        self.assertEqual(this.wt.id2path('d'), 'd.OTHER')
1586
 
        self.assertEqual(this.wt.id2path('f'), 'f.THIS')
 
219
        self.assertEqual(this.wt.id2path(b'd'), 'd.OTHER')
 
220
        self.assertEqual(this.wt.id2path(b'f'), 'f.THIS')
1587
221
        self.assertEqual(os.readlink(this.wt.abspath('e')), 'other-e')
1588
222
        self.assertIs(os.path.lexists(this.wt.abspath('e.THIS')), False)
1589
223
        self.assertIs(os.path.lexists(this.wt.abspath('e.OTHER')), False)
1600
234
        base = TransformGroup("BASE", root_id)
1601
235
        this = TransformGroup("THIS", root_id)
1602
236
        other = TransformGroup("OTHER", root_id)
1603
 
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1604
 
                                   for t in [base, this, other]]
1605
 
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1606
 
                                   for t in [base, this, other]]
1607
 
        base.tt.new_directory('c', base_a, 'c')
1608
 
        this.tt.new_directory('c1', this_a, 'c')
1609
 
        other.tt.new_directory('c', other_b, 'c')
1610
 
 
1611
 
        base.tt.new_directory('d', base_a, 'd')
1612
 
        this.tt.new_directory('d1', this_b, 'd')
1613
 
        other.tt.new_directory('d', other_a, 'd')
1614
 
 
1615
 
        base.tt.new_directory('e', base_a, 'e')
1616
 
        this.tt.new_directory('e', this_a, 'e')
1617
 
        other.tt.new_directory('e1', other_b, 'e')
1618
 
 
1619
 
        base.tt.new_directory('f', base_a, 'f')
1620
 
        this.tt.new_directory('f1', this_b, 'f')
1621
 
        other.tt.new_directory('f1', other_b, 'f')
 
237
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, b'a')
 
238
                                   for t in [base, this, other]]
 
239
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, b'b')
 
240
                                   for t in [base, this, other]]
 
241
        base.tt.new_directory('c', base_a, b'c')
 
242
        this.tt.new_directory('c1', this_a, b'c')
 
243
        other.tt.new_directory('c', other_b, b'c')
 
244
 
 
245
        base.tt.new_directory('d', base_a, b'd')
 
246
        this.tt.new_directory('d1', this_b, b'd')
 
247
        other.tt.new_directory('d', other_a, b'd')
 
248
 
 
249
        base.tt.new_directory('e', base_a, b'e')
 
250
        this.tt.new_directory('e', this_a, b'e')
 
251
        other.tt.new_directory('e1', other_b, b'e')
 
252
 
 
253
        base.tt.new_directory('f', base_a, b'f')
 
254
        this.tt.new_directory('f1', this_b, b'f')
 
255
        other.tt.new_directory('f1', other_b, b'f')
1622
256
 
1623
257
        for tg in [this, base, other]:
1624
258
            tg.tt.apply()
1625
259
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1626
 
        self.assertEqual(this.wt.id2path('c'), pathjoin('b/c1'))
1627
 
        self.assertEqual(this.wt.id2path('d'), pathjoin('b/d1'))
1628
 
        self.assertEqual(this.wt.id2path('e'), pathjoin('b/e1'))
1629
 
        self.assertEqual(this.wt.id2path('f'), pathjoin('b/f1'))
 
260
        self.assertEqual(this.wt.id2path(b'c'), pathjoin('b/c1'))
 
261
        self.assertEqual(this.wt.id2path(b'd'), pathjoin('b/d1'))
 
262
        self.assertEqual(this.wt.id2path(b'e'), pathjoin('b/e1'))
 
263
        self.assertEqual(this.wt.id2path(b'f'), pathjoin('b/f1'))
1630
264
 
1631
265
    def test_filename_merge_conflicts(self):
1632
266
        root_id = generate_ids.gen_root_id()
1633
267
        base = TransformGroup("BASE", root_id)
1634
268
        this = TransformGroup("THIS", root_id)
1635
269
        other = TransformGroup("OTHER", root_id)
1636
 
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1637
 
                                   for t in [base, this, other]]
1638
 
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1639
 
                                   for t in [base, this, other]]
1640
 
 
1641
 
        base.tt.new_file('g', base_a, 'g', 'g')
1642
 
        other.tt.new_file('g1', other_b, 'g1', 'g')
1643
 
 
1644
 
        base.tt.new_file('h', base_a, 'h', 'h')
1645
 
        this.tt.new_file('h1', this_b, 'h1', 'h')
1646
 
 
1647
 
        base.tt.new_file('i', base.root, 'i', 'i')
1648
 
        other.tt.new_directory('i1', this_b, 'i')
 
270
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, b'a')
 
271
                                   for t in [base, this, other]]
 
272
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, b'b')
 
273
                                   for t in [base, this, other]]
 
274
 
 
275
        base.tt.new_file('g', base_a, [b'g'], b'g')
 
276
        other.tt.new_file('g1', other_b, [b'g1'], b'g')
 
277
 
 
278
        base.tt.new_file('h', base_a, [b'h'], b'h')
 
279
        this.tt.new_file('h1', this_b, [b'h1'], b'h')
 
280
 
 
281
        base.tt.new_file('i', base.root, [b'i'], b'i')
 
282
        other.tt.new_directory('i1', this_b, b'i')
1649
283
 
1650
284
        for tg in [this, base, other]:
1651
285
            tg.tt.apply()
1652
286
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1653
287
 
1654
 
        self.assertEqual(this.wt.id2path('g'), pathjoin('b/g1.OTHER'))
 
288
        self.assertEqual(this.wt.id2path(b'g'), pathjoin('b/g1.OTHER'))
1655
289
        self.assertIs(os.path.lexists(this.wt.abspath('b/g1.BASE')), True)
1656
290
        self.assertIs(os.path.lexists(this.wt.abspath('b/g1.THIS')), False)
1657
 
        self.assertEqual(this.wt.id2path('h'), pathjoin('b/h1.THIS'))
 
291
        self.assertEqual(this.wt.id2path(b'h'), pathjoin('b/h1.THIS'))
1658
292
        self.assertIs(os.path.lexists(this.wt.abspath('b/h1.BASE')), True)
1659
293
        self.assertIs(os.path.lexists(this.wt.abspath('b/h1.OTHER')), False)
1660
 
        self.assertEqual(this.wt.id2path('i'), pathjoin('b/i1.OTHER'))
 
294
        self.assertEqual(this.wt.id2path(b'i'), pathjoin('b/i1.OTHER'))
1661
295
 
1662
296
 
1663
297
class TestBuildTree(tests.TestCaseWithTransport):
1665
299
    def test_build_tree_with_symlinks(self):
1666
300
        self.requireFeature(SymlinkFeature)
1667
301
        os.mkdir('a')
1668
 
        a = BzrDir.create_standalone_workingtree('a')
 
302
        a = ControlDir.create_standalone_workingtree('a')
1669
303
        os.mkdir('a/foo')
1670
 
        file('a/foo/bar', 'wb').write('contents')
 
304
        with open('a/foo/bar', 'wb') as f:
 
305
            f.write(b'contents')
1671
306
        os.symlink('a/foo/bar', 'a/foo/baz')
1672
307
        a.add(['foo', 'foo/bar', 'foo/baz'])
1673
308
        a.commit('initial commit')
1674
 
        b = BzrDir.create_standalone_workingtree('b')
 
309
        b = ControlDir.create_standalone_workingtree('b')
1675
310
        basis = a.basis_tree()
1676
311
        basis.lock_read()
1677
312
        self.addCleanup(basis.unlock)
1678
313
        build_tree(basis, b)
1679
314
        self.assertIs(os.path.isdir('b/foo'), True)
1680
 
        self.assertEqual(file('b/foo/bar', 'rb').read(), "contents")
 
315
        with open('b/foo/bar', 'rb') as f:
 
316
            self.assertEqual(f.read(), b"contents")
1681
317
        self.assertEqual(os.readlink('b/foo/baz'), 'a/foo/bar')
1682
318
 
1683
319
    def test_build_with_references(self):
1684
320
        tree = self.make_branch_and_tree('source',
1685
 
            format='dirstate-with-subtree')
 
321
                                         format='development-subtree')
1686
322
        subtree = self.make_branch_and_tree('source/subtree',
1687
 
            format='dirstate-with-subtree')
 
323
                                            format='development-subtree')
1688
324
        tree.add_reference(subtree)
1689
325
        tree.commit('a revision')
1690
326
        tree.branch.create_checkout('target')
1691
 
        self.failUnlessExists('target')
1692
 
        self.failUnlessExists('target/subtree')
 
327
        self.assertPathExists('target')
 
328
        self.assertPathExists('target/subtree')
1693
329
 
1694
330
    def test_file_conflict_handling(self):
1695
331
        """Ensure that when building trees, conflict handling is done"""
1696
332
        source = self.make_branch_and_tree('source')
1697
333
        target = self.make_branch_and_tree('target')
1698
334
        self.build_tree(['source/file', 'target/file'])
1699
 
        source.add('file', 'new-file')
 
335
        source.add('file', b'new-file')
1700
336
        source.commit('added file')
1701
337
        build_tree(source.basis_tree(), target)
1702
 
        self.assertEqual([DuplicateEntry('Moved existing file to',
1703
 
                          'file.moved', 'file', None, 'new-file')],
1704
 
                         target.conflicts())
 
338
        self.assertEqual(
 
339
            [DuplicateEntry('Moved existing file to', 'file.moved',
 
340
                            'file', None, 'new-file')],
 
341
            target.conflicts())
1705
342
        target2 = self.make_branch_and_tree('target2')
1706
 
        target_file = file('target2/file', 'wb')
1707
 
        try:
1708
 
            source_file = file('source/file', 'rb')
1709
 
            try:
1710
 
                target_file.write(source_file.read())
1711
 
            finally:
1712
 
                source_file.close()
1713
 
        finally:
1714
 
            target_file.close()
 
343
        with open('target2/file', 'wb') as target_file, \
 
344
                open('source/file', 'rb') as source_file:
 
345
            target_file.write(source_file.read())
1715
346
        build_tree(source.basis_tree(), target2)
1716
347
        self.assertEqual([], target2.conflicts())
1717
348
 
1720
351
        self.requireFeature(SymlinkFeature)
1721
352
        source = self.make_branch_and_tree('source')
1722
353
        os.symlink('foo', 'source/symlink')
1723
 
        source.add('symlink', 'new-symlink')
 
354
        source.add('symlink', b'new-symlink')
1724
355
        source.commit('added file')
1725
356
        target = self.make_branch_and_tree('target')
1726
357
        os.symlink('bar', 'target/symlink')
1727
358
        build_tree(source.basis_tree(), target)
1728
 
        self.assertEqual([DuplicateEntry('Moved existing file to',
1729
 
            'symlink.moved', 'symlink', None, 'new-symlink')],
 
359
        self.assertEqual(
 
360
            [DuplicateEntry('Moved existing file to', 'symlink.moved',
 
361
                            'symlink', None, 'new-symlink')],
1730
362
            target.conflicts())
1731
363
        target = self.make_branch_and_tree('target2')
1732
364
        os.symlink('foo', 'target2/symlink')
1738
370
        source = self.make_branch_and_tree('source')
1739
371
        target = self.make_branch_and_tree('target')
1740
372
        self.build_tree(['source/dir1/', 'source/dir1/file', 'target/dir1/'])
1741
 
        source.add(['dir1', 'dir1/file'], ['new-dir1', 'new-file'])
 
373
        source.add(['dir1', 'dir1/file'], [b'new-dir1', b'new-file'])
1742
374
        source.commit('added file')
1743
375
        build_tree(source.basis_tree(), target)
1744
376
        self.assertEqual([], target.conflicts())
1745
 
        self.failUnlessExists('target/dir1/file')
 
377
        self.assertPathExists('target/dir1/file')
1746
378
 
1747
379
        # Ensure contents are merged
1748
380
        target = self.make_branch_and_tree('target2')
1749
381
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1750
382
        build_tree(source.basis_tree(), target)
1751
383
        self.assertEqual([], target.conflicts())
1752
 
        self.failUnlessExists('target2/dir1/file2')
1753
 
        self.failUnlessExists('target2/dir1/file')
 
384
        self.assertPathExists('target2/dir1/file2')
 
385
        self.assertPathExists('target2/dir1/file')
1754
386
 
1755
387
        # Ensure new contents are suppressed for existing branches
1756
388
        target = self.make_branch_and_tree('target3')
1757
389
        self.make_branch('target3/dir1')
1758
390
        self.build_tree(['target3/dir1/file2'])
1759
391
        build_tree(source.basis_tree(), target)
1760
 
        self.failIfExists('target3/dir1/file')
1761
 
        self.failUnlessExists('target3/dir1/file2')
1762
 
        self.failUnlessExists('target3/dir1.diverted/file')
1763
 
        self.assertEqual([DuplicateEntry('Diverted to',
1764
 
            'dir1.diverted', 'dir1', 'new-dir1', None)],
 
392
        self.assertPathDoesNotExist('target3/dir1/file')
 
393
        self.assertPathExists('target3/dir1/file2')
 
394
        self.assertPathExists('target3/dir1.diverted/file')
 
395
        self.assertEqual(
 
396
            [DuplicateEntry('Diverted to', 'dir1.diverted',
 
397
                            'dir1', 'new-dir1', None)],
1765
398
            target.conflicts())
1766
399
 
1767
400
        target = self.make_branch_and_tree('target4')
1768
401
        self.build_tree(['target4/dir1/'])
1769
402
        self.make_branch('target4/dir1/file')
1770
403
        build_tree(source.basis_tree(), target)
1771
 
        self.failUnlessExists('target4/dir1/file')
 
404
        self.assertPathExists('target4/dir1/file')
1772
405
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1773
 
        self.failUnlessExists('target4/dir1/file.diverted')
1774
 
        self.assertEqual([DuplicateEntry('Diverted to',
1775
 
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
 
406
        self.assertPathExists('target4/dir1/file.diverted')
 
407
        self.assertEqual(
 
408
            [DuplicateEntry('Diverted to', 'dir1/file.diverted',
 
409
                            'dir1/file', 'new-file', None)],
1776
410
            target.conflicts())
1777
411
 
1778
412
    def test_mixed_conflict_handling(self):
1780
414
        source = self.make_branch_and_tree('source')
1781
415
        target = self.make_branch_and_tree('target')
1782
416
        self.build_tree(['source/name', 'target/name/'])
1783
 
        source.add('name', 'new-name')
 
417
        source.add('name', b'new-name')
1784
418
        source.commit('added file')
1785
419
        build_tree(source.basis_tree(), target)
1786
 
        self.assertEqual([DuplicateEntry('Moved existing file to',
1787
 
            'name.moved', 'name', None, 'new-name')], target.conflicts())
 
420
        self.assertEqual(
 
421
            [DuplicateEntry('Moved existing file to',
 
422
                            'name.moved', 'name', None, 'new-name')],
 
423
            target.conflicts())
1788
424
 
1789
425
    def test_raises_in_populated(self):
1790
426
        source = self.make_branch_and_tree('source')
1795
431
        self.build_tree(['target/name'])
1796
432
        target.add('name')
1797
433
        self.assertRaises(errors.WorkingTreeAlreadyPopulated,
1798
 
            build_tree, source.basis_tree(), target)
 
434
                          build_tree, source.basis_tree(), target)
1799
435
 
1800
436
    def test_build_tree_rename_count(self):
1801
437
        source = self.make_branch_and_tree('source')
1817
453
    def create_ab_tree(self):
1818
454
        """Create a committed test tree with two files"""
1819
455
        source = self.make_branch_and_tree('source')
1820
 
        self.build_tree_contents([('source/file1', 'A')])
1821
 
        self.build_tree_contents([('source/file2', 'B')])
1822
 
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
 
456
        self.build_tree_contents([('source/file1', b'A')])
 
457
        self.build_tree_contents([('source/file2', b'B')])
 
458
        source.add(['file1', 'file2'], [b'file1-id', b'file2-id'])
1823
459
        source.commit('commit files')
1824
460
        source.lock_write()
1825
461
        self.addCleanup(source.unlock)
1827
463
 
1828
464
    def test_build_tree_accelerator_tree(self):
1829
465
        source = self.create_ab_tree()
1830
 
        self.build_tree_contents([('source/file2', 'C')])
 
466
        self.build_tree_contents([('source/file2', b'C')])
1831
467
        calls = []
1832
468
        real_source_get_file = source.get_file
1833
 
        def get_file(file_id, path=None):
1834
 
            calls.append(file_id)
1835
 
            return real_source_get_file(file_id, path)
 
469
 
 
470
        def get_file(path):
 
471
            calls.append(path)
 
472
            return real_source_get_file(path)
1836
473
        source.get_file = get_file
1837
474
        target = self.make_branch_and_tree('target')
1838
475
        revision_tree = source.basis_tree()
1839
476
        revision_tree.lock_read()
1840
477
        self.addCleanup(revision_tree.unlock)
1841
478
        build_tree(revision_tree, target, source)
1842
 
        self.assertEqual(['file1-id'], calls)
 
479
        self.assertEqual(['file1'], calls)
1843
480
        target.lock_read()
1844
481
        self.addCleanup(target.unlock)
1845
482
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1846
483
 
 
484
    def test_build_tree_accelerator_tree_observes_sha1(self):
 
485
        source = self.create_ab_tree()
 
486
        sha1 = osutils.sha_string(b'A')
 
487
        target = self.make_branch_and_tree('target')
 
488
        target.lock_write()
 
489
        self.addCleanup(target.unlock)
 
490
        state = target.current_dirstate()
 
491
        state._cutoff_time = time.time() + 60
 
492
        build_tree(source.basis_tree(), target, source)
 
493
        entry = state._get_entry(0, path_utf8=b'file1')
 
494
        self.assertEqual(sha1, entry[1][0][1])
 
495
 
1847
496
    def test_build_tree_accelerator_tree_missing_file(self):
1848
497
        source = self.create_ab_tree()
1849
498
        os.unlink('source/file1')
1860
509
    def test_build_tree_accelerator_wrong_kind(self):
1861
510
        self.requireFeature(SymlinkFeature)
1862
511
        source = self.make_branch_and_tree('source')
1863
 
        self.build_tree_contents([('source/file1', '')])
1864
 
        self.build_tree_contents([('source/file2', '')])
1865
 
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
 
512
        self.build_tree_contents([('source/file1', b'')])
 
513
        self.build_tree_contents([('source/file2', b'')])
 
514
        source.add(['file1', 'file2'], [b'file1-id', b'file2-id'])
1866
515
        source.commit('commit files')
1867
516
        os.unlink('source/file2')
1868
 
        self.build_tree_contents([('source/file2/', 'C')])
 
517
        self.build_tree_contents([('source/file2/', b'C')])
1869
518
        os.unlink('source/file1')
1870
519
        os.symlink('file2', 'source/file1')
1871
520
        calls = []
1872
521
        real_source_get_file = source.get_file
1873
 
        def get_file(file_id, path=None):
1874
 
            calls.append(file_id)
1875
 
            return real_source_get_file(file_id, path)
 
522
 
 
523
        def get_file(path):
 
524
            calls.append(path)
 
525
            return real_source_get_file(path)
1876
526
        source.get_file = get_file
1877
527
        target = self.make_branch_and_tree('target')
1878
528
        revision_tree = source.basis_tree()
1911
561
 
1912
562
    def test_build_tree_accelerator_tree_moved(self):
1913
563
        source = self.make_branch_and_tree('source')
1914
 
        self.build_tree_contents([('source/file1', 'A')])
1915
 
        source.add(['file1'], ['file1-id'])
 
564
        self.build_tree_contents([('source/file1', b'A')])
 
565
        source.add(['file1'], [b'file1-id'])
1916
566
        source.commit('commit files')
1917
567
        source.rename_one('file1', 'file2')
1918
568
        source.lock_read()
1929
579
    def test_build_tree_hardlinks_preserve_execute(self):
1930
580
        self.requireFeature(HardlinkFeature)
1931
581
        source = self.create_ab_tree()
1932
 
        tt = TreeTransform(source)
1933
 
        trans_id = tt.trans_id_tree_file_id('file1-id')
 
582
        tt = source.transform()
 
583
        trans_id = tt.trans_id_tree_path('file1')
1934
584
        tt.set_executability(True, trans_id)
1935
585
        tt.apply()
1936
 
        self.assertTrue(source.is_executable('file1-id'))
 
586
        self.assertTrue(source.is_executable('file1'))
1937
587
        target = self.make_branch_and_tree('target')
1938
588
        revision_tree = source.basis_tree()
1939
589
        revision_tree.lock_read()
1942
592
        target.lock_read()
1943
593
        self.addCleanup(target.unlock)
1944
594
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1945
 
        self.assertTrue(source.is_executable('file1-id'))
 
595
        self.assertTrue(source.is_executable('file1'))
1946
596
 
1947
597
    def install_rot13_content_filter(self, pattern):
1948
598
        # We could use
1950
600
        # below, but that looks a bit... hard to read even if it's exactly
1951
601
        # the same thing.
1952
602
        original_registry = filters._reset_registry()
 
603
 
1953
604
        def restore_registry():
1954
605
            filters._reset_registry(original_registry)
1955
606
        self.addCleanup(restore_registry)
 
607
 
1956
608
        def rot13(chunks, context=None):
1957
 
            return [''.join(chunks).encode('rot13')]
 
609
            return [
 
610
                codecs.encode(chunk.decode('ascii'), 'rot13').encode('ascii')
 
611
                for chunk in chunks]
1958
612
        rot13filter = filters.ContentFilter(rot13, rot13)
1959
 
        filters.register_filter_stack_map('rot13', {'yes': [rot13filter]}.get)
 
613
        filters.filter_stacks_registry.register(
 
614
            'rot13', {'yes': [rot13filter]}.get)
1960
615
        os.mkdir(self.test_home_dir + '/.bazaar')
1961
616
        rules_filename = self.test_home_dir + '/.bazaar/rules'
1962
 
        f = open(rules_filename, 'wb')
1963
 
        f.write('[name %s]\nrot13=yes\n' % (pattern,))
1964
 
        f.close()
 
617
        with open(rules_filename, 'wb') as f:
 
618
            f.write(b'[name %s]\nrot13=yes\n' % (pattern,))
 
619
 
1965
620
        def uninstall_rules():
1966
621
            os.remove(rules_filename)
1967
622
            rules.reset_rules()
1974
629
        if it can).
1975
630
        """
1976
631
        self.requireFeature(HardlinkFeature)
1977
 
        self.install_rot13_content_filter('file1')
 
632
        self.install_rot13_content_filter(b'file1')
1978
633
        source = self.create_ab_tree()
1979
634
        target = self.make_branch_and_tree('target')
1980
635
        revision_tree = source.basis_tree()
1992
647
        self.assertEqualStat(source_stat, target_stat)
1993
648
 
1994
649
    def test_case_insensitive_build_tree_inventory(self):
1995
 
        if (tests.CaseInsensitiveFilesystemFeature.available()
1996
 
            or tests.CaseInsCasePresFilenameFeature.available()):
 
650
        if (features.CaseInsensitiveFilesystemFeature.available()
 
651
                or features.CaseInsCasePresFilenameFeature.available()):
1997
652
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
1998
653
        source = self.make_branch_and_tree('source')
1999
654
        self.build_tree(['source/file', 'source/FILE'])
2000
 
        source.add(['file', 'FILE'], ['lower-id', 'upper-id'])
 
655
        source.add(['file', 'FILE'], [b'lower-id', b'upper-id'])
2001
656
        source.commit('added files')
2002
657
        # Don't try this at home, kids!
2003
658
        # Force the tree to report that it is case insensitive
2004
659
        target = self.make_branch_and_tree('target')
2005
660
        target.case_sensitive = False
2006
661
        build_tree(source.basis_tree(), target, source, delta_from_tree=True)
2007
 
        self.assertEqual('file.moved', target.id2path('lower-id'))
2008
 
        self.assertEqual('FILE', target.id2path('upper-id'))
 
662
        self.assertEqual('file.moved', target.id2path(b'lower-id'))
 
663
        self.assertEqual('FILE', target.id2path(b'upper-id'))
 
664
 
 
665
    def test_build_tree_observes_sha(self):
 
666
        source = self.make_branch_and_tree('source')
 
667
        self.build_tree(['source/file1', 'source/dir/', 'source/dir/file2'])
 
668
        source.add(['file1', 'dir', 'dir/file2'],
 
669
                   [b'file1-id', b'dir-id', b'file2-id'])
 
670
        source.commit('new files')
 
671
        target = self.make_branch_and_tree('target')
 
672
        target.lock_write()
 
673
        self.addCleanup(target.unlock)
 
674
        # We make use of the fact that DirState caches its cutoff time. So we
 
675
        # set the 'safe' time to one minute in the future.
 
676
        state = target.current_dirstate()
 
677
        state._cutoff_time = time.time() + 60
 
678
        build_tree(source.basis_tree(), target)
 
679
        entry1_sha = osutils.sha_file_by_name('source/file1')
 
680
        entry2_sha = osutils.sha_file_by_name('source/dir/file2')
 
681
        # entry[1] is the state information, entry[1][0] is the state of the
 
682
        # working tree, entry[1][0][1] is the sha value for the current working
 
683
        # tree
 
684
        entry1 = state._get_entry(0, path_utf8=b'file1')
 
685
        self.assertEqual(entry1_sha, entry1[1][0][1])
 
686
        # The 'size' field must also be set.
 
687
        self.assertEqual(25, entry1[1][0][2])
 
688
        entry1_state = entry1[1][0]
 
689
        entry2 = state._get_entry(0, path_utf8=b'dir/file2')
 
690
        self.assertEqual(entry2_sha, entry2[1][0][1])
 
691
        self.assertEqual(29, entry2[1][0][2])
 
692
        entry2_state = entry2[1][0]
 
693
        # Now, make sure that we don't have to re-read the content. The
 
694
        # packed_stat should match exactly.
 
695
        self.assertEqual(entry1_sha, target.get_file_sha1('file1'))
 
696
        self.assertEqual(entry2_sha, target.get_file_sha1('dir/file2'))
 
697
        self.assertEqual(entry1_state, entry1[1][0])
 
698
        self.assertEqual(entry2_state, entry2[1][0])
2009
699
 
2010
700
 
2011
701
class TestCommitTransform(tests.TestCaseWithTransport):
2019
709
 
2020
710
    def get_branch_and_transform(self):
2021
711
        branch = self.get_branch()
2022
 
        tt = TransformPreview(branch.basis_tree())
 
712
        tt = branch.basis_tree().preview_transform()
2023
713
        self.addCleanup(tt.finalize)
2024
714
        return branch, tt
2025
715
 
2027
717
        branch = self.get_branch()
2028
718
        basis = branch.repository.revision_tree(
2029
719
            _mod_revision.NULL_REVISION)
2030
 
        tt = TransformPreview(basis)
 
720
        tt = basis.preview_transform()
2031
721
        self.addCleanup(tt.finalize)
2032
722
        e = self.assertRaises(ValueError, tt.commit, branch, '')
2033
723
        self.assertEqual('TreeTransform not based on branch basis: null:',
2042
732
 
2043
733
    def test_merge_parents(self):
2044
734
        branch, tt = self.get_branch_and_transform()
2045
 
        rev = tt.commit(branch, 'my message', ['rev1b', 'rev1c'])
2046
 
        self.assertEqual(['rev1b', 'rev1c'],
 
735
        tt.commit(branch, 'my message', [b'rev1b', b'rev1c'])
 
736
        self.assertEqual([b'rev1b', b'rev1c'],
2047
737
                         branch.basis_tree().get_parent_ids()[1:])
2048
738
 
2049
739
    def test_first_commit(self):
2050
740
        branch = self.make_branch('branch')
2051
741
        branch.lock_write()
2052
742
        self.addCleanup(branch.unlock)
2053
 
        tt = TransformPreview(branch.basis_tree())
 
743
        tt = branch.basis_tree().preview_transform()
2054
744
        self.addCleanup(tt.finalize)
2055
 
        tt.new_directory('', ROOT_PARENT, 'TREE_ROOT')
2056
 
        rev = tt.commit(branch, 'my message')
 
745
        tt.new_directory('', ROOT_PARENT, b'TREE_ROOT')
 
746
        tt.commit(branch, 'my message')
2057
747
        self.assertEqual([], branch.basis_tree().get_parent_ids())
2058
748
        self.assertNotEqual(_mod_revision.NULL_REVISION,
2059
749
                            branch.last_revision())
2062
752
        branch = self.make_branch('branch')
2063
753
        branch.lock_write()
2064
754
        self.addCleanup(branch.unlock)
2065
 
        tt = TransformPreview(branch.basis_tree())
 
755
        tt = branch.basis_tree().preview_transform()
2066
756
        self.addCleanup(tt.finalize)
2067
757
        e = self.assertRaises(ValueError, tt.commit, branch,
2068
 
                          'my message', ['rev1b-id'])
 
758
                              'my message', [b'rev1b-id'])
2069
759
        self.assertEqual('Cannot supply merge parents for first commit.',
2070
760
                         str(e))
2071
761
        self.assertEqual(_mod_revision.NULL_REVISION, branch.last_revision())
2072
762
 
2073
763
    def test_add_files(self):
2074
764
        branch, tt = self.get_branch_and_transform()
2075
 
        tt.new_file('file', tt.root, 'contents', 'file-id')
2076
 
        trans_id = tt.new_directory('dir', tt.root, 'dir-id')
 
765
        tt.new_file('file', tt.root, [b'contents'], b'file-id')
 
766
        trans_id = tt.new_directory('dir', tt.root, b'dir-id')
2077
767
        if SymlinkFeature.available():
2078
 
            tt.new_symlink('symlink', trans_id, 'target', 'symlink-id')
2079
 
        rev = tt.commit(branch, 'message')
 
768
            tt.new_symlink('symlink', trans_id, 'target', b'symlink-id')
 
769
        tt.commit(branch, 'message')
2080
770
        tree = branch.basis_tree()
2081
 
        self.assertEqual('file', tree.id2path('file-id'))
2082
 
        self.assertEqual('contents', tree.get_file_text('file-id'))
2083
 
        self.assertEqual('dir', tree.id2path('dir-id'))
 
771
        self.assertEqual('file', tree.id2path(b'file-id'))
 
772
        self.assertEqual(b'contents', tree.get_file_text('file'))
 
773
        self.assertEqual('dir', tree.id2path(b'dir-id'))
2084
774
        if SymlinkFeature.available():
2085
 
            self.assertEqual('dir/symlink', tree.id2path('symlink-id'))
2086
 
            self.assertEqual('target', tree.get_symlink_target('symlink-id'))
 
775
            self.assertEqual('dir/symlink', tree.id2path(b'symlink-id'))
 
776
            self.assertEqual('target', tree.get_symlink_target('dir/symlink'))
2087
777
 
2088
778
    def test_add_unversioned(self):
2089
779
        branch, tt = self.get_branch_and_transform()
2090
 
        tt.new_file('file', tt.root, 'contents')
 
780
        tt.new_file('file', tt.root, [b'contents'])
2091
781
        self.assertRaises(errors.StrictCommitFailed, tt.commit, branch,
2092
782
                          'message', strict=True)
2093
783
 
2094
784
    def test_modify_strict(self):
2095
785
        branch, tt = self.get_branch_and_transform()
2096
 
        tt.new_file('file', tt.root, 'contents', 'file-id')
 
786
        tt.new_file('file', tt.root, [b'contents'], b'file-id')
2097
787
        tt.commit(branch, 'message', strict=True)
2098
 
        tt = TransformPreview(branch.basis_tree())
 
788
        tt = branch.basis_tree().preview_transform()
2099
789
        self.addCleanup(tt.finalize)
2100
 
        trans_id = tt.trans_id_file_id('file-id')
 
790
        trans_id = tt.trans_id_file_id(b'file-id')
2101
791
        tt.delete_contents(trans_id)
2102
 
        tt.create_file('contents', trans_id)
 
792
        tt.create_file([b'contents'], trans_id)
2103
793
        tt.commit(branch, 'message', strict=True)
2104
794
 
2105
795
    def test_commit_malformed(self):
2108
798
        In this case, we are adding a file without adding its parent.
2109
799
        """
2110
800
        branch, tt = self.get_branch_and_transform()
2111
 
        parent_id = tt.trans_id_file_id('parent-id')
2112
 
        tt.new_file('file', parent_id, 'contents', 'file-id')
2113
 
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
 
801
        parent_id = tt.trans_id_file_id(b'parent-id')
 
802
        tt.new_file('file', parent_id, [b'contents'], b'file-id')
 
803
        self.assertRaises(MalformedTransform, tt.commit, branch,
2114
804
                          'message')
2115
805
 
2116
806
    def test_commit_rich_revision_data(self):
2117
807
        branch, tt = self.get_branch_and_transform()
2118
808
        rev_id = tt.commit(branch, 'message', timestamp=1, timezone=43201,
2119
809
                           committer='me <me@example.com>',
2120
 
                           revprops={'foo': 'bar'}, revision_id='revid-1',
 
810
                           revprops={u'foo': 'bar'}, revision_id=b'revid-1',
2121
811
                           authors=['Author1 <author1@example.com>',
2122
 
                              'Author2 <author2@example.com>',
2123
 
                               ])
2124
 
        self.assertEqual('revid-1', rev_id)
 
812
                                    'Author2 <author2@example.com>',
 
813
                                    ])
 
814
        self.assertEqual(b'revid-1', rev_id)
2125
815
        revision = branch.repository.get_revision(rev_id)
2126
816
        self.assertEqual(1, revision.timestamp)
2127
817
        self.assertEqual(43201, revision.timezone)
2146
836
        self.assertEqual('tree', revision.properties['branch-nick'])
2147
837
 
2148
838
 
2149
 
class MockTransform(object):
2150
 
 
2151
 
    def has_named_child(self, by_parent, parent_id, name):
2152
 
        for child_id in by_parent[parent_id]:
2153
 
            if child_id == '0':
2154
 
                if name == "name~":
2155
 
                    return True
2156
 
            elif name == "name.~%s~" % child_id:
2157
 
                return True
2158
 
        return False
2159
 
 
2160
 
 
2161
 
class MockEntry(object):
2162
 
    def __init__(self):
2163
 
        object.__init__(self)
2164
 
        self.name = "name"
2165
 
 
2166
 
 
2167
 
class TestGetBackupName(TestCase):
2168
 
    def test_get_backup_name(self):
2169
 
        tt = MockTransform()
2170
 
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
2171
 
        self.assertEqual(name, 'name.~1~')
2172
 
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
2173
 
        self.assertEqual(name, 'name.~2~')
2174
 
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
2175
 
        self.assertEqual(name, 'name.~1~')
2176
 
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
2177
 
        self.assertEqual(name, 'name.~1~')
2178
 
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
2179
 
        self.assertEqual(name, 'name.~4~')
2180
 
 
2181
 
 
2182
839
class TestFileMover(tests.TestCaseWithTransport):
2183
840
 
2184
841
    def test_file_mover(self):
2185
842
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2186
843
        mover = _FileMover()
2187
844
        mover.rename('a', 'q')
2188
 
        self.failUnlessExists('q')
2189
 
        self.failIfExists('a')
2190
 
        self.failUnlessExists('q/b')
2191
 
        self.failUnlessExists('c')
2192
 
        self.failUnlessExists('c/d')
 
845
        self.assertPathExists('q')
 
846
        self.assertPathDoesNotExist('a')
 
847
        self.assertPathExists('q/b')
 
848
        self.assertPathExists('c')
 
849
        self.assertPathExists('c/d')
2193
850
 
2194
851
    def test_pre_delete_rollback(self):
2195
852
        self.build_tree(['a/'])
2196
853
        mover = _FileMover()
2197
854
        mover.pre_delete('a', 'q')
2198
 
        self.failUnlessExists('q')
2199
 
        self.failIfExists('a')
 
855
        self.assertPathExists('q')
 
856
        self.assertPathDoesNotExist('a')
2200
857
        mover.rollback()
2201
 
        self.failIfExists('q')
2202
 
        self.failUnlessExists('a')
 
858
        self.assertPathDoesNotExist('q')
 
859
        self.assertPathExists('a')
2203
860
 
2204
861
    def test_apply_deletions(self):
2205
862
        self.build_tree(['a/', 'b/'])
2206
863
        mover = _FileMover()
2207
864
        mover.pre_delete('a', 'q')
2208
865
        mover.pre_delete('b', 'r')
2209
 
        self.failUnlessExists('q')
2210
 
        self.failUnlessExists('r')
2211
 
        self.failIfExists('a')
2212
 
        self.failIfExists('b')
 
866
        self.assertPathExists('q')
 
867
        self.assertPathExists('r')
 
868
        self.assertPathDoesNotExist('a')
 
869
        self.assertPathDoesNotExist('b')
2213
870
        mover.apply_deletions()
2214
 
        self.failIfExists('q')
2215
 
        self.failIfExists('r')
2216
 
        self.failIfExists('a')
2217
 
        self.failIfExists('b')
 
871
        self.assertPathDoesNotExist('q')
 
872
        self.assertPathDoesNotExist('r')
 
873
        self.assertPathDoesNotExist('a')
 
874
        self.assertPathDoesNotExist('b')
2218
875
 
2219
876
    def test_file_mover_rollback(self):
2220
877
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2223
880
        mover.rename('c/e', 'c/d')
2224
881
        try:
2225
882
            mover.rename('a', 'c')
2226
 
        except errors.FileExists, e:
 
883
        except errors.FileExists:
2227
884
            mover.rollback()
2228
 
        self.failUnlessExists('a')
2229
 
        self.failUnlessExists('c/d')
 
885
        self.assertPathExists('a')
 
886
        self.assertPathExists('c/d')
2230
887
 
2231
888
 
2232
889
class Bogus(Exception):
2244
901
 
2245
902
        def rename(self, source, target):
2246
903
            if (self.bad_source is not None and
2247
 
                source.endswith(self.bad_source)):
 
904
                    source.endswith(self.bad_source)):
2248
905
                raise Bogus
2249
906
            elif (self.bad_target is not None and
2250
 
                target.endswith(self.bad_target)):
 
907
                  target.endswith(self.bad_target)):
2251
908
                raise Bogus
2252
909
            else:
2253
910
                _FileMover.rename(self, source, target)
2255
912
    def test_rollback_rename(self):
2256
913
        tree = self.make_branch_and_tree('.')
2257
914
        self.build_tree(['a/', 'a/b'])
2258
 
        tt = TreeTransform(tree)
 
915
        tt = tree.transform()
2259
916
        self.addCleanup(tt.finalize)
2260
917
        a_id = tt.trans_id_tree_path('a')
2261
918
        tt.adjust_path('c', tt.root, a_id)
2262
919
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2263
920
        self.assertRaises(Bogus, tt.apply,
2264
921
                          _mover=self.ExceptionFileMover(bad_source='a'))
2265
 
        self.failUnlessExists('a')
2266
 
        self.failUnlessExists('a/b')
 
922
        self.assertPathExists('a')
 
923
        self.assertPathExists('a/b')
2267
924
        tt.apply()
2268
 
        self.failUnlessExists('c')
2269
 
        self.failUnlessExists('c/d')
 
925
        self.assertPathExists('c')
 
926
        self.assertPathExists('c/d')
2270
927
 
2271
928
    def test_rollback_rename_into_place(self):
2272
929
        tree = self.make_branch_and_tree('.')
2273
930
        self.build_tree(['a/', 'a/b'])
2274
 
        tt = TreeTransform(tree)
 
931
        tt = tree.transform()
2275
932
        self.addCleanup(tt.finalize)
2276
933
        a_id = tt.trans_id_tree_path('a')
2277
934
        tt.adjust_path('c', tt.root, a_id)
2278
935
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2279
936
        self.assertRaises(Bogus, tt.apply,
2280
937
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2281
 
        self.failUnlessExists('a')
2282
 
        self.failUnlessExists('a/b')
 
938
        self.assertPathExists('a')
 
939
        self.assertPathExists('a/b')
2283
940
        tt.apply()
2284
 
        self.failUnlessExists('c')
2285
 
        self.failUnlessExists('c/d')
 
941
        self.assertPathExists('c')
 
942
        self.assertPathExists('c/d')
2286
943
 
2287
944
    def test_rollback_deletion(self):
2288
945
        tree = self.make_branch_and_tree('.')
2289
946
        self.build_tree(['a/', 'a/b'])
2290
 
        tt = TreeTransform(tree)
 
947
        tt = tree.transform()
2291
948
        self.addCleanup(tt.finalize)
2292
949
        a_id = tt.trans_id_tree_path('a')
2293
950
        tt.delete_contents(a_id)
2294
951
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2295
952
        self.assertRaises(Bogus, tt.apply,
2296
953
                          _mover=self.ExceptionFileMover(bad_target='d'))
2297
 
        self.failUnlessExists('a')
2298
 
        self.failUnlessExists('a/b')
2299
 
 
2300
 
    def test_resolve_no_parent(self):
 
954
        self.assertPathExists('a')
 
955
        self.assertPathExists('a/b')
 
956
 
 
957
 
 
958
class TestFinalizeRobustness(tests.TestCaseWithTransport):
 
959
    """Ensure treetransform creation errors can be safely cleaned up after"""
 
960
 
 
961
    def _override_globals_in_method(self, instance, method_name, globals):
 
962
        """Replace method on instance with one with updated globals"""
 
963
        import types
 
964
        func = getattr(instance, method_name).__func__
 
965
        new_globals = dict(func.__globals__)
 
966
        new_globals.update(globals)
 
967
        new_func = types.FunctionType(func.__code__, new_globals,
 
968
                                      func.__name__, func.__defaults__)
 
969
        setattr(instance, method_name,
 
970
                types.MethodType(new_func, instance))
 
971
        self.addCleanup(delattr, instance, method_name)
 
972
 
 
973
    @staticmethod
 
974
    def _fake_open_raises_before(name, mode):
 
975
        """Like open() but raises before doing anything"""
 
976
        raise RuntimeError
 
977
 
 
978
    @staticmethod
 
979
    def _fake_open_raises_after(name, mode):
 
980
        """Like open() but raises after creating file without returning"""
 
981
        open(name, mode).close()
 
982
        raise RuntimeError
 
983
 
 
984
    def create_transform_and_root_trans_id(self):
 
985
        """Setup a transform creating a file in limbo"""
 
986
        tree = self.make_branch_and_tree('.')
 
987
        tt = tree.transform()
 
988
        return tt, tt.create_path("a", tt.root)
 
989
 
 
990
    def create_transform_and_subdir_trans_id(self):
 
991
        """Setup a transform creating a directory containing a file in limbo"""
 
992
        tree = self.make_branch_and_tree('.')
 
993
        tt = tree.transform()
 
994
        d_trans_id = tt.create_path("d", tt.root)
 
995
        tt.create_directory(d_trans_id)
 
996
        f_trans_id = tt.create_path("a", d_trans_id)
 
997
        tt.adjust_path("a", d_trans_id, f_trans_id)
 
998
        return tt, f_trans_id
 
999
 
 
1000
    def test_root_create_file_open_raises_before_creation(self):
 
1001
        tt, trans_id = self.create_transform_and_root_trans_id()
 
1002
        self._override_globals_in_method(
 
1003
            tt, "create_file", {"open": self._fake_open_raises_before})
 
1004
        self.assertRaises(RuntimeError, tt.create_file,
 
1005
                          [b"contents"], trans_id)
 
1006
        path = tt._limbo_name(trans_id)
 
1007
        self.assertPathDoesNotExist(path)
 
1008
        tt.finalize()
 
1009
        self.assertPathDoesNotExist(tt._limbodir)
 
1010
 
 
1011
    def test_root_create_file_open_raises_after_creation(self):
 
1012
        tt, trans_id = self.create_transform_and_root_trans_id()
 
1013
        self._override_globals_in_method(
 
1014
            tt, "create_file", {"open": self._fake_open_raises_after})
 
1015
        self.assertRaises(RuntimeError, tt.create_file,
 
1016
                          [b"contents"], trans_id)
 
1017
        path = tt._limbo_name(trans_id)
 
1018
        self.assertPathExists(path)
 
1019
        tt.finalize()
 
1020
        self.assertPathDoesNotExist(path)
 
1021
        self.assertPathDoesNotExist(tt._limbodir)
 
1022
 
 
1023
    def test_subdir_create_file_open_raises_before_creation(self):
 
1024
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
1025
        self._override_globals_in_method(
 
1026
            tt, "create_file", {"open": self._fake_open_raises_before})
 
1027
        self.assertRaises(RuntimeError, tt.create_file,
 
1028
                          [b"contents"], trans_id)
 
1029
        path = tt._limbo_name(trans_id)
 
1030
        self.assertPathDoesNotExist(path)
 
1031
        tt.finalize()
 
1032
        self.assertPathDoesNotExist(tt._limbodir)
 
1033
 
 
1034
    def test_subdir_create_file_open_raises_after_creation(self):
 
1035
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
1036
        self._override_globals_in_method(
 
1037
            tt, "create_file", {"open": self._fake_open_raises_after})
 
1038
        self.assertRaises(RuntimeError, tt.create_file,
 
1039
                          [b"contents"], trans_id)
 
1040
        path = tt._limbo_name(trans_id)
 
1041
        self.assertPathExists(path)
 
1042
        tt.finalize()
 
1043
        self.assertPathDoesNotExist(path)
 
1044
        self.assertPathDoesNotExist(tt._limbodir)
 
1045
 
 
1046
    def test_rename_in_limbo_rename_raises_after_rename(self):
 
1047
        tt, trans_id = self.create_transform_and_root_trans_id()
 
1048
        parent1 = tt.new_directory('parent1', tt.root)
 
1049
        child1 = tt.new_file('child1', parent1, [b'contents'])
 
1050
        parent2 = tt.new_directory('parent2', tt.root)
 
1051
 
 
1052
        class FakeOSModule(object):
 
1053
            def rename(self, old, new):
 
1054
                os.rename(old, new)
 
1055
                raise RuntimeError
 
1056
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
1057
                                         {"os": FakeOSModule()})
 
1058
        self.assertRaises(
 
1059
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
1060
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
 
1061
        self.assertPathExists(path)
 
1062
        tt.finalize()
 
1063
        self.assertPathDoesNotExist(path)
 
1064
        self.assertPathDoesNotExist(tt._limbodir)
 
1065
 
 
1066
    def test_rename_in_limbo_rename_raises_before_rename(self):
 
1067
        tt, trans_id = self.create_transform_and_root_trans_id()
 
1068
        parent1 = tt.new_directory('parent1', tt.root)
 
1069
        child1 = tt.new_file('child1', parent1, [b'contents'])
 
1070
        parent2 = tt.new_directory('parent2', tt.root)
 
1071
 
 
1072
        class FakeOSModule(object):
 
1073
            def rename(self, old, new):
 
1074
                raise RuntimeError
 
1075
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
1076
                                         {"os": FakeOSModule()})
 
1077
        self.assertRaises(
 
1078
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
1079
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
 
1080
        self.assertPathExists(path)
 
1081
        tt.finalize()
 
1082
        self.assertPathDoesNotExist(path)
 
1083
        self.assertPathDoesNotExist(tt._limbodir)
 
1084
 
 
1085
 
 
1086
class TestTransformMissingParent(tests.TestCaseWithTransport):
 
1087
 
 
1088
    def make_tt_with_versioned_dir(self):
2301
1089
        wt = self.make_branch_and_tree('.')
2302
 
        tt = TreeTransform(wt)
2303
 
        self.addCleanup(tt.finalize)
2304
 
        parent = tt.trans_id_file_id('parent-id')
2305
 
        tt.new_file('file', parent, 'Contents')
2306
 
        resolve_conflicts(tt)
2307
 
 
2308
 
 
2309
 
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2310
 
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2311
 
                  (False, False))
2312
 
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2313
 
              ('', ''), ('directory', 'directory'), (False, None))
2314
 
 
2315
 
 
2316
 
class TestTransformPreview(tests.TestCaseWithTransport):
2317
 
 
2318
 
    def create_tree(self):
2319
 
        tree = self.make_branch_and_tree('.')
2320
 
        self.build_tree_contents([('a', 'content 1')])
2321
 
        tree.set_root_id('TREE_ROOT')
2322
 
        tree.add('a', 'a-id')
2323
 
        tree.commit('rev1', rev_id='rev1')
2324
 
        return tree.branch.repository.revision_tree('rev1')
2325
 
 
2326
 
    def get_empty_preview(self):
2327
 
        repository = self.make_repository('repo')
2328
 
        tree = repository.revision_tree(_mod_revision.NULL_REVISION)
2329
 
        preview = TransformPreview(tree)
2330
 
        self.addCleanup(preview.finalize)
2331
 
        return preview
2332
 
 
2333
 
    def test_transform_preview(self):
2334
 
        revision_tree = self.create_tree()
2335
 
        preview = TransformPreview(revision_tree)
2336
 
        self.addCleanup(preview.finalize)
2337
 
 
2338
 
    def test_transform_preview_tree(self):
2339
 
        revision_tree = self.create_tree()
2340
 
        preview = TransformPreview(revision_tree)
2341
 
        self.addCleanup(preview.finalize)
2342
 
        preview.get_preview_tree()
2343
 
 
2344
 
    def test_transform_new_file(self):
2345
 
        revision_tree = self.create_tree()
2346
 
        preview = TransformPreview(revision_tree)
2347
 
        self.addCleanup(preview.finalize)
2348
 
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
2349
 
        preview_tree = preview.get_preview_tree()
2350
 
        self.assertEqual(preview_tree.kind('file2-id'), 'file')
2351
 
        self.assertEqual(
2352
 
            preview_tree.get_file('file2-id').read(), 'content B\n')
2353
 
 
2354
 
    def test_diff_preview_tree(self):
2355
 
        revision_tree = self.create_tree()
2356
 
        preview = TransformPreview(revision_tree)
2357
 
        self.addCleanup(preview.finalize)
2358
 
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
2359
 
        preview_tree = preview.get_preview_tree()
2360
 
        out = StringIO()
2361
 
        show_diff_trees(revision_tree, preview_tree, out)
2362
 
        lines = out.getvalue().splitlines()
2363
 
        self.assertEqual(lines[0], "=== added file 'file2'")
2364
 
        # 3 lines of diff administrivia
2365
 
        self.assertEqual(lines[4], "+content B")
2366
 
 
2367
 
    def test_transform_conflicts(self):
2368
 
        revision_tree = self.create_tree()
2369
 
        preview = TransformPreview(revision_tree)
2370
 
        self.addCleanup(preview.finalize)
2371
 
        preview.new_file('a', preview.root, 'content 2')
2372
 
        resolve_conflicts(preview)
2373
 
        trans_id = preview.trans_id_file_id('a-id')
2374
 
        self.assertEqual('a.moved', preview.final_name(trans_id))
2375
 
 
2376
 
    def get_tree_and_preview_tree(self):
2377
 
        revision_tree = self.create_tree()
2378
 
        preview = TransformPreview(revision_tree)
2379
 
        self.addCleanup(preview.finalize)
2380
 
        a_trans_id = preview.trans_id_file_id('a-id')
2381
 
        preview.delete_contents(a_trans_id)
2382
 
        preview.create_file('b content', a_trans_id)
2383
 
        preview_tree = preview.get_preview_tree()
2384
 
        return revision_tree, preview_tree
2385
 
 
2386
 
    def test_iter_changes(self):
2387
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2388
 
        root = revision_tree.inventory.root.file_id
2389
 
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
2390
 
                          (root, root), ('a', 'a'), ('file', 'file'),
2391
 
                          (False, False))],
2392
 
                          list(preview_tree.iter_changes(revision_tree)))
2393
 
 
2394
 
    def test_include_unchanged_succeeds(self):
2395
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2396
 
        changes = preview_tree.iter_changes(revision_tree,
2397
 
                                            include_unchanged=True)
2398
 
        root = revision_tree.inventory.root.file_id
2399
 
 
2400
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2401
 
 
2402
 
    def test_specific_files(self):
2403
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2404
 
        changes = preview_tree.iter_changes(revision_tree,
2405
 
                                            specific_files=[''])
2406
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2407
 
 
2408
 
    def test_want_unversioned(self):
2409
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2410
 
        changes = preview_tree.iter_changes(revision_tree,
2411
 
                                            want_unversioned=True)
2412
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2413
 
 
2414
 
    def test_ignore_extra_trees_no_specific_files(self):
2415
 
        # extra_trees is harmless without specific_files, so we'll silently
2416
 
        # accept it, even though we won't use it.
2417
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2418
 
        preview_tree.iter_changes(revision_tree, extra_trees=[preview_tree])
2419
 
 
2420
 
    def test_ignore_require_versioned_no_specific_files(self):
2421
 
        # require_versioned is meaningless without specific_files.
2422
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2423
 
        preview_tree.iter_changes(revision_tree, require_versioned=False)
2424
 
 
2425
 
    def test_ignore_pb(self):
2426
 
        # pb could be supported, but TT.iter_changes doesn't support it.
2427
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2428
 
        preview_tree.iter_changes(revision_tree)
2429
 
 
2430
 
    def test_kind(self):
2431
 
        revision_tree = self.create_tree()
2432
 
        preview = TransformPreview(revision_tree)
2433
 
        self.addCleanup(preview.finalize)
2434
 
        preview.new_file('file', preview.root, 'contents', 'file-id')
2435
 
        preview.new_directory('directory', preview.root, 'dir-id')
2436
 
        preview_tree = preview.get_preview_tree()
2437
 
        self.assertEqual('file', preview_tree.kind('file-id'))
2438
 
        self.assertEqual('directory', preview_tree.kind('dir-id'))
2439
 
 
2440
 
    def test_get_file_mtime(self):
2441
 
        preview = self.get_empty_preview()
2442
 
        file_trans_id = preview.new_file('file', preview.root, 'contents',
2443
 
                                         'file-id')
2444
 
        limbo_path = preview._limbo_name(file_trans_id)
2445
 
        preview_tree = preview.get_preview_tree()
2446
 
        self.assertEqual(os.stat(limbo_path).st_mtime,
2447
 
                         preview_tree.get_file_mtime('file-id'))
2448
 
 
2449
 
    def test_get_file_mtime_renamed(self):
2450
 
        work_tree = self.make_branch_and_tree('tree')
2451
 
        self.build_tree(['tree/file'])
2452
 
        work_tree.add('file', 'file-id')
2453
 
        preview = TransformPreview(work_tree)
2454
 
        self.addCleanup(preview.finalize)
2455
 
        file_trans_id = preview.trans_id_tree_file_id('file-id')
2456
 
        preview.adjust_path('renamed', preview.root, file_trans_id)
2457
 
        preview_tree = preview.get_preview_tree()
2458
 
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2459
 
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2460
 
 
2461
 
    def test_get_file(self):
2462
 
        preview = self.get_empty_preview()
2463
 
        preview.new_file('file', preview.root, 'contents', 'file-id')
2464
 
        preview_tree = preview.get_preview_tree()
2465
 
        tree_file = preview_tree.get_file('file-id')
2466
 
        try:
2467
 
            self.assertEqual('contents', tree_file.read())
2468
 
        finally:
2469
 
            tree_file.close()
2470
 
 
2471
 
    def test_get_symlink_target(self):
2472
 
        self.requireFeature(SymlinkFeature)
2473
 
        preview = self.get_empty_preview()
2474
 
        preview.new_symlink('symlink', preview.root, 'target', 'symlink-id')
2475
 
        preview_tree = preview.get_preview_tree()
2476
 
        self.assertEqual('target',
2477
 
                         preview_tree.get_symlink_target('symlink-id'))
2478
 
 
2479
 
    def test_all_file_ids(self):
2480
 
        tree = self.make_branch_and_tree('tree')
2481
 
        self.build_tree(['tree/a', 'tree/b', 'tree/c'])
2482
 
        tree.add(['a', 'b', 'c'], ['a-id', 'b-id', 'c-id'])
2483
 
        preview = TransformPreview(tree)
2484
 
        self.addCleanup(preview.finalize)
2485
 
        preview.unversion_file(preview.trans_id_file_id('b-id'))
2486
 
        c_trans_id = preview.trans_id_file_id('c-id')
2487
 
        preview.unversion_file(c_trans_id)
2488
 
        preview.version_file('c-id', c_trans_id)
2489
 
        preview_tree = preview.get_preview_tree()
2490
 
        self.assertEqual(set(['a-id', 'c-id', tree.get_root_id()]),
2491
 
                         preview_tree.all_file_ids())
2492
 
 
2493
 
    def test_path2id_deleted_unchanged(self):
2494
 
        tree = self.make_branch_and_tree('tree')
2495
 
        self.build_tree(['tree/unchanged', 'tree/deleted'])
2496
 
        tree.add(['unchanged', 'deleted'], ['unchanged-id', 'deleted-id'])
2497
 
        preview = TransformPreview(tree)
2498
 
        self.addCleanup(preview.finalize)
2499
 
        preview.unversion_file(preview.trans_id_file_id('deleted-id'))
2500
 
        preview_tree = preview.get_preview_tree()
2501
 
        self.assertEqual('unchanged-id', preview_tree.path2id('unchanged'))
2502
 
        self.assertIs(None, preview_tree.path2id('deleted'))
2503
 
 
2504
 
    def test_path2id_created(self):
2505
 
        tree = self.make_branch_and_tree('tree')
2506
 
        self.build_tree(['tree/unchanged'])
2507
 
        tree.add(['unchanged'], ['unchanged-id'])
2508
 
        preview = TransformPreview(tree)
2509
 
        self.addCleanup(preview.finalize)
2510
 
        preview.new_file('new', preview.trans_id_file_id('unchanged-id'),
2511
 
            'contents', 'new-id')
2512
 
        preview_tree = preview.get_preview_tree()
2513
 
        self.assertEqual('new-id', preview_tree.path2id('unchanged/new'))
2514
 
 
2515
 
    def test_path2id_moved(self):
2516
 
        tree = self.make_branch_and_tree('tree')
2517
 
        self.build_tree(['tree/old_parent/', 'tree/old_parent/child'])
2518
 
        tree.add(['old_parent', 'old_parent/child'],
2519
 
                 ['old_parent-id', 'child-id'])
2520
 
        preview = TransformPreview(tree)
2521
 
        self.addCleanup(preview.finalize)
2522
 
        new_parent = preview.new_directory('new_parent', preview.root,
2523
 
                                           'new_parent-id')
2524
 
        preview.adjust_path('child', new_parent,
2525
 
                            preview.trans_id_file_id('child-id'))
2526
 
        preview_tree = preview.get_preview_tree()
2527
 
        self.assertIs(None, preview_tree.path2id('old_parent/child'))
2528
 
        self.assertEqual('child-id', preview_tree.path2id('new_parent/child'))
2529
 
 
2530
 
    def test_path2id_renamed_parent(self):
2531
 
        tree = self.make_branch_and_tree('tree')
2532
 
        self.build_tree(['tree/old_name/', 'tree/old_name/child'])
2533
 
        tree.add(['old_name', 'old_name/child'],
2534
 
                 ['parent-id', 'child-id'])
2535
 
        preview = TransformPreview(tree)
2536
 
        self.addCleanup(preview.finalize)
2537
 
        preview.adjust_path('new_name', preview.root,
2538
 
                            preview.trans_id_file_id('parent-id'))
2539
 
        preview_tree = preview.get_preview_tree()
2540
 
        self.assertIs(None, preview_tree.path2id('old_name/child'))
2541
 
        self.assertEqual('child-id', preview_tree.path2id('new_name/child'))
2542
 
 
2543
 
    def assertMatchingIterEntries(self, tt, specific_file_ids=None):
2544
 
        preview_tree = tt.get_preview_tree()
2545
 
        preview_result = list(preview_tree.iter_entries_by_dir(
2546
 
                              specific_file_ids))
2547
 
        tree = tt._tree
2548
 
        tt.apply()
2549
 
        actual_result = list(tree.iter_entries_by_dir(specific_file_ids))
2550
 
        self.assertEqual(actual_result, preview_result)
2551
 
 
2552
 
    def test_iter_entries_by_dir_new(self):
2553
 
        tree = self.make_branch_and_tree('tree')
2554
 
        tt = TreeTransform(tree)
2555
 
        tt.new_file('new', tt.root, 'contents', 'new-id')
2556
 
        self.assertMatchingIterEntries(tt)
2557
 
 
2558
 
    def test_iter_entries_by_dir_deleted(self):
2559
 
        tree = self.make_branch_and_tree('tree')
2560
 
        self.build_tree(['tree/deleted'])
2561
 
        tree.add('deleted', 'deleted-id')
2562
 
        tt = TreeTransform(tree)
2563
 
        tt.delete_contents(tt.trans_id_file_id('deleted-id'))
2564
 
        self.assertMatchingIterEntries(tt)
2565
 
 
2566
 
    def test_iter_entries_by_dir_unversioned(self):
2567
 
        tree = self.make_branch_and_tree('tree')
2568
 
        self.build_tree(['tree/removed'])
2569
 
        tree.add('removed', 'removed-id')
2570
 
        tt = TreeTransform(tree)
2571
 
        tt.unversion_file(tt.trans_id_file_id('removed-id'))
2572
 
        self.assertMatchingIterEntries(tt)
2573
 
 
2574
 
    def test_iter_entries_by_dir_moved(self):
2575
 
        tree = self.make_branch_and_tree('tree')
2576
 
        self.build_tree(['tree/moved', 'tree/new_parent/'])
2577
 
        tree.add(['moved', 'new_parent'], ['moved-id', 'new_parent-id'])
2578
 
        tt = TreeTransform(tree)
2579
 
        tt.adjust_path('moved', tt.trans_id_file_id('new_parent-id'),
2580
 
                       tt.trans_id_file_id('moved-id'))
2581
 
        self.assertMatchingIterEntries(tt)
2582
 
 
2583
 
    def test_iter_entries_by_dir_specific_file_ids(self):
2584
 
        tree = self.make_branch_and_tree('tree')
2585
 
        tree.set_root_id('tree-root-id')
2586
 
        self.build_tree(['tree/parent/', 'tree/parent/child'])
2587
 
        tree.add(['parent', 'parent/child'], ['parent-id', 'child-id'])
2588
 
        tt = TreeTransform(tree)
2589
 
        self.assertMatchingIterEntries(tt, ['tree-root-id', 'child-id'])
2590
 
 
2591
 
    def test_symlink_content_summary(self):
2592
 
        self.requireFeature(SymlinkFeature)
2593
 
        preview = self.get_empty_preview()
2594
 
        preview.new_symlink('path', preview.root, 'target', 'path-id')
2595
 
        summary = preview.get_preview_tree().path_content_summary('path')
2596
 
        self.assertEqual(('symlink', None, None, 'target'), summary)
2597
 
 
2598
 
    def test_missing_content_summary(self):
2599
 
        preview = self.get_empty_preview()
2600
 
        summary = preview.get_preview_tree().path_content_summary('path')
2601
 
        self.assertEqual(('missing', None, None, None), summary)
2602
 
 
2603
 
    def test_deleted_content_summary(self):
2604
 
        tree = self.make_branch_and_tree('tree')
2605
 
        self.build_tree(['tree/path/'])
2606
 
        tree.add('path')
2607
 
        preview = TransformPreview(tree)
2608
 
        self.addCleanup(preview.finalize)
2609
 
        preview.delete_contents(preview.trans_id_tree_path('path'))
2610
 
        summary = preview.get_preview_tree().path_content_summary('path')
2611
 
        self.assertEqual(('missing', None, None, None), summary)
2612
 
 
2613
 
    def test_file_content_summary_executable(self):
2614
 
        preview = self.get_empty_preview()
2615
 
        path_id = preview.new_file('path', preview.root, 'contents', 'path-id')
2616
 
        preview.set_executability(True, path_id)
2617
 
        summary = preview.get_preview_tree().path_content_summary('path')
2618
 
        self.assertEqual(4, len(summary))
2619
 
        self.assertEqual('file', summary[0])
2620
 
        # size must be known
2621
 
        self.assertEqual(len('contents'), summary[1])
2622
 
        # executable
2623
 
        self.assertEqual(True, summary[2])
2624
 
        # will not have hash (not cheap to determine)
2625
 
        self.assertIs(None, summary[3])
2626
 
 
2627
 
    def test_change_executability(self):
2628
 
        tree = self.make_branch_and_tree('tree')
2629
 
        self.build_tree(['tree/path'])
2630
 
        tree.add('path')
2631
 
        preview = TransformPreview(tree)
2632
 
        self.addCleanup(preview.finalize)
2633
 
        path_id = preview.trans_id_tree_path('path')
2634
 
        preview.set_executability(True, path_id)
2635
 
        summary = preview.get_preview_tree().path_content_summary('path')
2636
 
        self.assertEqual(True, summary[2])
2637
 
 
2638
 
    def test_file_content_summary_non_exec(self):
2639
 
        preview = self.get_empty_preview()
2640
 
        preview.new_file('path', preview.root, 'contents', 'path-id')
2641
 
        summary = preview.get_preview_tree().path_content_summary('path')
2642
 
        self.assertEqual(4, len(summary))
2643
 
        self.assertEqual('file', summary[0])
2644
 
        # size must be known
2645
 
        self.assertEqual(len('contents'), summary[1])
2646
 
        # not executable
2647
 
        self.assertEqual(False, summary[2])
2648
 
        # will not have hash (not cheap to determine)
2649
 
        self.assertIs(None, summary[3])
2650
 
 
2651
 
    def test_dir_content_summary(self):
2652
 
        preview = self.get_empty_preview()
2653
 
        preview.new_directory('path', preview.root, 'path-id')
2654
 
        summary = preview.get_preview_tree().path_content_summary('path')
2655
 
        self.assertEqual(('directory', None, None, None), summary)
2656
 
 
2657
 
    def test_tree_content_summary(self):
2658
 
        preview = self.get_empty_preview()
2659
 
        path = preview.new_directory('path', preview.root, 'path-id')
2660
 
        preview.set_tree_reference('rev-1', path)
2661
 
        summary = preview.get_preview_tree().path_content_summary('path')
2662
 
        self.assertEqual(4, len(summary))
2663
 
        self.assertEqual('tree-reference', summary[0])
2664
 
 
2665
 
    def test_annotate(self):
2666
 
        tree = self.make_branch_and_tree('tree')
2667
 
        self.build_tree_contents([('tree/file', 'a\n')])
2668
 
        tree.add('file', 'file-id')
2669
 
        tree.commit('a', rev_id='one')
2670
 
        self.build_tree_contents([('tree/file', 'a\nb\n')])
2671
 
        preview = TransformPreview(tree)
2672
 
        self.addCleanup(preview.finalize)
2673
 
        file_trans_id = preview.trans_id_file_id('file-id')
2674
 
        preview.delete_contents(file_trans_id)
2675
 
        preview.create_file('a\nb\nc\n', file_trans_id)
2676
 
        preview_tree = preview.get_preview_tree()
2677
 
        expected = [
2678
 
            ('one', 'a\n'),
2679
 
            ('me:', 'b\n'),
2680
 
            ('me:', 'c\n'),
2681
 
        ]
2682
 
        annotation = preview_tree.annotate_iter('file-id', 'me:')
2683
 
        self.assertEqual(expected, annotation)
2684
 
 
2685
 
    def test_annotate_missing(self):
2686
 
        preview = self.get_empty_preview()
2687
 
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
2688
 
        preview_tree = preview.get_preview_tree()
2689
 
        expected = [
2690
 
            ('me:', 'a\n'),
2691
 
            ('me:', 'b\n'),
2692
 
            ('me:', 'c\n'),
2693
 
         ]
2694
 
        annotation = preview_tree.annotate_iter('file-id', 'me:')
2695
 
        self.assertEqual(expected, annotation)
2696
 
 
2697
 
    def test_annotate_rename(self):
2698
 
        tree = self.make_branch_and_tree('tree')
2699
 
        self.build_tree_contents([('tree/file', 'a\n')])
2700
 
        tree.add('file', 'file-id')
2701
 
        tree.commit('a', rev_id='one')
2702
 
        preview = TransformPreview(tree)
2703
 
        self.addCleanup(preview.finalize)
2704
 
        file_trans_id = preview.trans_id_file_id('file-id')
2705
 
        preview.adjust_path('newname', preview.root, file_trans_id)
2706
 
        preview_tree = preview.get_preview_tree()
2707
 
        expected = [
2708
 
            ('one', 'a\n'),
2709
 
        ]
2710
 
        annotation = preview_tree.annotate_iter('file-id', 'me:')
2711
 
        self.assertEqual(expected, annotation)
2712
 
 
2713
 
    def test_annotate_deleted(self):
2714
 
        tree = self.make_branch_and_tree('tree')
2715
 
        self.build_tree_contents([('tree/file', 'a\n')])
2716
 
        tree.add('file', 'file-id')
2717
 
        tree.commit('a', rev_id='one')
2718
 
        self.build_tree_contents([('tree/file', 'a\nb\n')])
2719
 
        preview = TransformPreview(tree)
2720
 
        self.addCleanup(preview.finalize)
2721
 
        file_trans_id = preview.trans_id_file_id('file-id')
2722
 
        preview.delete_contents(file_trans_id)
2723
 
        preview_tree = preview.get_preview_tree()
2724
 
        annotation = preview_tree.annotate_iter('file-id', 'me:')
2725
 
        self.assertIs(None, annotation)
2726
 
 
2727
 
    def test_stored_kind(self):
2728
 
        preview = self.get_empty_preview()
2729
 
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
2730
 
        preview_tree = preview.get_preview_tree()
2731
 
        self.assertEqual('file', preview_tree.stored_kind('file-id'))
2732
 
 
2733
 
    def test_is_executable(self):
2734
 
        preview = self.get_empty_preview()
2735
 
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
2736
 
        preview.set_executability(True, preview.trans_id_file_id('file-id'))
2737
 
        preview_tree = preview.get_preview_tree()
2738
 
        self.assertEqual(True, preview_tree.is_executable('file-id'))
2739
 
 
2740
 
    def test_get_set_parent_ids(self):
2741
 
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2742
 
        self.assertEqual([], preview_tree.get_parent_ids())
2743
 
        preview_tree.set_parent_ids(['rev-1'])
2744
 
        self.assertEqual(['rev-1'], preview_tree.get_parent_ids())
2745
 
 
2746
 
    def test_plan_file_merge(self):
2747
 
        work_a = self.make_branch_and_tree('wta')
2748
 
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
2749
 
        work_a.add('file', 'file-id')
2750
 
        base_id = work_a.commit('base version')
2751
 
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
2752
 
        preview = TransformPreview(work_a)
2753
 
        self.addCleanup(preview.finalize)
2754
 
        trans_id = preview.trans_id_file_id('file-id')
2755
 
        preview.delete_contents(trans_id)
2756
 
        preview.create_file('b\nc\nd\ne\n', trans_id)
2757
 
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
2758
 
        tree_a = preview.get_preview_tree()
2759
 
        tree_a.set_parent_ids([base_id])
2760
 
        self.assertEqual([
2761
 
            ('killed-a', 'a\n'),
2762
 
            ('killed-b', 'b\n'),
2763
 
            ('unchanged', 'c\n'),
2764
 
            ('unchanged', 'd\n'),
2765
 
            ('new-a', 'e\n'),
2766
 
            ('new-b', 'f\n'),
2767
 
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
2768
 
 
2769
 
    def test_plan_file_merge_revision_tree(self):
2770
 
        work_a = self.make_branch_and_tree('wta')
2771
 
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
2772
 
        work_a.add('file', 'file-id')
2773
 
        base_id = work_a.commit('base version')
2774
 
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
2775
 
        preview = TransformPreview(work_a.basis_tree())
2776
 
        self.addCleanup(preview.finalize)
2777
 
        trans_id = preview.trans_id_file_id('file-id')
2778
 
        preview.delete_contents(trans_id)
2779
 
        preview.create_file('b\nc\nd\ne\n', trans_id)
2780
 
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
2781
 
        tree_a = preview.get_preview_tree()
2782
 
        tree_a.set_parent_ids([base_id])
2783
 
        self.assertEqual([
2784
 
            ('killed-a', 'a\n'),
2785
 
            ('killed-b', 'b\n'),
2786
 
            ('unchanged', 'c\n'),
2787
 
            ('unchanged', 'd\n'),
2788
 
            ('new-a', 'e\n'),
2789
 
            ('new-b', 'f\n'),
2790
 
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
2791
 
 
2792
 
    def test_walkdirs(self):
2793
 
        preview = self.get_empty_preview()
2794
 
        root = preview.new_directory('', ROOT_PARENT, 'tree-root')
2795
 
        # FIXME: new_directory should mark root.
2796
 
        preview.fixup_new_roots()
2797
 
        preview_tree = preview.get_preview_tree()
2798
 
        file_trans_id = preview.new_file('a', preview.root, 'contents',
2799
 
                                         'a-id')
2800
 
        expected = [(('', 'tree-root'),
2801
 
                    [('a', 'a', 'file', None, 'a-id', 'file')])]
2802
 
        self.assertEqual(expected, list(preview_tree.walkdirs()))
2803
 
 
2804
 
    def test_extras(self):
2805
 
        work_tree = self.make_branch_and_tree('tree')
2806
 
        self.build_tree(['tree/removed-file', 'tree/existing-file',
2807
 
                         'tree/not-removed-file'])
2808
 
        work_tree.add(['removed-file', 'not-removed-file'])
2809
 
        preview = TransformPreview(work_tree)
2810
 
        self.addCleanup(preview.finalize)
2811
 
        preview.new_file('new-file', preview.root, 'contents')
2812
 
        preview.new_file('new-versioned-file', preview.root, 'contents',
2813
 
                         'new-versioned-id')
2814
 
        tree = preview.get_preview_tree()
2815
 
        preview.unversion_file(preview.trans_id_tree_path('removed-file'))
2816
 
        self.assertEqual(set(['new-file', 'removed-file', 'existing-file']),
2817
 
                         set(tree.extras()))
2818
 
 
2819
 
    def test_merge_into_preview(self):
2820
 
        work_tree = self.make_branch_and_tree('tree')
2821
 
        self.build_tree_contents([('tree/file','b\n')])
2822
 
        work_tree.add('file', 'file-id')
2823
 
        work_tree.commit('first commit')
2824
 
        child_tree = work_tree.bzrdir.sprout('child').open_workingtree()
2825
 
        self.build_tree_contents([('child/file','b\nc\n')])
2826
 
        child_tree.commit('child commit')
2827
 
        child_tree.lock_write()
2828
 
        self.addCleanup(child_tree.unlock)
2829
 
        work_tree.lock_write()
2830
 
        self.addCleanup(work_tree.unlock)
2831
 
        preview = TransformPreview(work_tree)
2832
 
        self.addCleanup(preview.finalize)
2833
 
        file_trans_id = preview.trans_id_file_id('file-id')
2834
 
        preview.delete_contents(file_trans_id)
2835
 
        preview.create_file('a\nb\n', file_trans_id)
2836
 
        preview_tree = preview.get_preview_tree()
2837
 
        merger = Merger.from_revision_ids(None, preview_tree,
2838
 
                                          child_tree.branch.last_revision(),
2839
 
                                          other_branch=child_tree.branch,
2840
 
                                          tree_branch=work_tree.branch)
2841
 
        merger.merge_type = Merge3Merger
2842
 
        tt = merger.make_merger().make_preview_transform()
2843
 
        self.addCleanup(tt.finalize)
2844
 
        final_tree = tt.get_preview_tree()
2845
 
        self.assertEqual('a\nb\nc\n', final_tree.get_file_text('file-id'))
2846
 
 
2847
 
    def test_merge_preview_into_workingtree(self):
2848
 
        tree = self.make_branch_and_tree('tree')
2849
 
        tree.set_root_id('TREE_ROOT')
2850
 
        tt = TransformPreview(tree)
2851
 
        self.addCleanup(tt.finalize)
2852
 
        tt.new_file('name', tt.root, 'content', 'file-id')
2853
 
        tree2 = self.make_branch_and_tree('tree2')
2854
 
        tree2.set_root_id('TREE_ROOT')
2855
 
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
2856
 
                                         None, tree.basis_tree())
2857
 
        merger.merge_type = Merge3Merger
2858
 
        merger.do_merge()
2859
 
 
2860
 
    def test_merge_preview_into_workingtree_handles_conflicts(self):
2861
 
        tree = self.make_branch_and_tree('tree')
2862
 
        self.build_tree_contents([('tree/foo', 'bar')])
2863
 
        tree.add('foo', 'foo-id')
2864
 
        tree.commit('foo')
2865
 
        tt = TransformPreview(tree)
2866
 
        self.addCleanup(tt.finalize)
2867
 
        trans_id = tt.trans_id_file_id('foo-id')
2868
 
        tt.delete_contents(trans_id)
2869
 
        tt.create_file('baz', trans_id)
2870
 
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
2871
 
        self.build_tree_contents([('tree2/foo', 'qux')])
2872
 
        pb = None
2873
 
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
2874
 
                                         pb, tree.basis_tree())
2875
 
        merger.merge_type = Merge3Merger
2876
 
        merger.do_merge()
2877
 
 
2878
 
    def test_is_executable(self):
2879
 
        tree = self.make_branch_and_tree('tree')
2880
 
        preview = TransformPreview(tree)
2881
 
        self.addCleanup(preview.finalize)
2882
 
        preview.new_file('foo', preview.root, 'bar', 'baz-id')
2883
 
        preview_tree = preview.get_preview_tree()
2884
 
        self.assertEqual(False, preview_tree.is_executable('baz-id',
2885
 
                                                           'tree/foo'))
2886
 
        self.assertEqual(False, preview_tree.is_executable('baz-id'))
2887
 
 
2888
 
    def test_commit_preview_tree(self):
2889
 
        tree = self.make_branch_and_tree('tree')
2890
 
        rev_id = tree.commit('rev1')
2891
 
        tree.branch.lock_write()
2892
 
        self.addCleanup(tree.branch.unlock)
2893
 
        tt = TransformPreview(tree)
2894
 
        tt.new_file('file', tt.root, 'contents', 'file_id')
2895
 
        self.addCleanup(tt.finalize)
2896
 
        preview = tt.get_preview_tree()
2897
 
        preview.set_parent_ids([rev_id])
2898
 
        builder = tree.branch.get_commit_builder([rev_id])
2899
 
        list(builder.record_iter_changes(preview, rev_id, tt.iter_changes()))
2900
 
        builder.finish_inventory()
2901
 
        rev2_id = builder.commit('rev2')
2902
 
        rev2_tree = tree.branch.repository.revision_tree(rev2_id)
2903
 
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
2904
 
 
2905
 
    def test_ascii_limbo_paths(self):
2906
 
        self.requireFeature(tests.UnicodeFilenameFeature)
2907
 
        branch = self.make_branch('any')
2908
 
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
2909
 
        tt = TransformPreview(tree)
2910
 
        self.addCleanup(tt.finalize)
2911
 
        foo_id = tt.new_directory('', ROOT_PARENT)
2912
 
        bar_id = tt.new_file(u'\u1234bar', foo_id, 'contents')
2913
 
        limbo_path = tt._limbo_name(bar_id)
2914
 
        self.assertEqual(limbo_path.encode('ascii', 'replace'), limbo_path)
 
1090
        self.build_tree(['dir/', ])
 
1091
        wt.add(['dir'], [b'dir-id'])
 
1092
        wt.commit('Create dir')
 
1093
        tt = wt.transform()
 
1094
        self.addCleanup(tt.finalize)
 
1095
        return wt, tt
 
1096
 
 
1097
    def test_resolve_create_parent_for_versioned_file(self):
 
1098
        wt, tt = self.make_tt_with_versioned_dir()
 
1099
        dir_tid = tt.trans_id_tree_path('dir')
 
1100
        tt.new_file('file', dir_tid, [b'Contents'], file_id=b'file-id')
 
1101
        tt.delete_contents(dir_tid)
 
1102
        tt.unversion_file(dir_tid)
 
1103
        conflicts = resolve_conflicts(tt)
 
1104
        # one conflict for the missing directory, one for the unversioned
 
1105
        # parent
 
1106
        self.assertLength(2, conflicts)
 
1107
 
 
1108
    def test_non_versioned_file_create_conflict(self):
 
1109
        wt, tt = self.make_tt_with_versioned_dir()
 
1110
        dir_tid = tt.trans_id_tree_path('dir')
 
1111
        tt.new_file('file', dir_tid, [b'Contents'])
 
1112
        tt.delete_contents(dir_tid)
 
1113
        tt.unversion_file(dir_tid)
 
1114
        conflicts = resolve_conflicts(tt)
 
1115
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
 
1116
        self.assertLength(1, conflicts)
 
1117
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
1118
                         conflicts.pop())
2915
1119
 
2916
1120
 
2917
1121
class FakeSerializer(object):
2926
1130
 
2927
1131
class TestSerializeTransform(tests.TestCaseWithTransport):
2928
1132
 
2929
 
    _test_needs_features = [tests.UnicodeFilenameFeature]
 
1133
    _test_needs_features = [features.UnicodeFilenameFeature]
2930
1134
 
2931
1135
    def get_preview(self, tree=None):
2932
1136
        if tree is None:
2933
1137
            tree = self.make_branch_and_tree('tree')
2934
 
        tt = TransformPreview(tree)
 
1138
        tt = tree.preview_transform()
2935
1139
        self.addCleanup(tt.finalize)
2936
1140
        return tt
2937
1141
 
2942
1146
    @staticmethod
2943
1147
    def default_attribs():
2944
1148
        return {
2945
 
            '_id_number': 1,
2946
 
            '_new_name': {},
2947
 
            '_new_parent': {},
2948
 
            '_new_executability': {},
2949
 
            '_new_id': {},
2950
 
            '_tree_path_ids': {'': 'new-0'},
2951
 
            '_removed_id': [],
2952
 
            '_removed_contents': [],
2953
 
            '_non_present_ids': {},
 
1149
            b'_id_number': 1,
 
1150
            b'_new_name': {},
 
1151
            b'_new_parent': {},
 
1152
            b'_new_executability': {},
 
1153
            b'_new_id': {},
 
1154
            b'_tree_path_ids': {b'': b'new-0'},
 
1155
            b'_removed_id': [],
 
1156
            b'_removed_contents': [],
 
1157
            b'_non_present_ids': {},
2954
1158
            }
2955
1159
 
2956
1160
    def make_records(self, attribs, contents):
2957
1161
        records = [
2958
 
            (((('attribs'),),), bencode.bencode(attribs))]
 
1162
            ((((b'attribs'),),), bencode.bencode(attribs))]
2959
1163
        records.extend([(((n, k),), c) for n, k, c in contents])
2960
1164
        return records
2961
1165
 
2962
1166
    def creation_records(self):
2963
1167
        attribs = self.default_attribs()
2964
 
        attribs['_id_number'] = 3
2965
 
        attribs['_new_name'] = {
2966
 
            'new-1': u'foo\u1234'.encode('utf-8'), 'new-2': 'qux'}
2967
 
        attribs['_new_id'] = {'new-1': 'baz', 'new-2': 'quxx'}
2968
 
        attribs['_new_parent'] = {'new-1': 'new-0', 'new-2': 'new-0'}
2969
 
        attribs['_new_executability'] = {'new-1': 1}
 
1168
        attribs[b'_id_number'] = 3
 
1169
        attribs[b'_new_name'] = {
 
1170
            b'new-1': u'foo\u1234'.encode('utf-8'), b'new-2': b'qux'}
 
1171
        attribs[b'_new_id'] = {b'new-1': b'baz', b'new-2': b'quxx'}
 
1172
        attribs[b'_new_parent'] = {b'new-1': b'new-0', b'new-2': b'new-0'}
 
1173
        attribs[b'_new_executability'] = {b'new-1': 1}
2970
1174
        contents = [
2971
 
            ('new-1', 'file', 'i 1\nbar\n'),
2972
 
            ('new-2', 'directory', ''),
 
1175
            (b'new-1', b'file', b'i 1\nbar\n'),
 
1176
            (b'new-2', b'directory', b''),
2973
1177
            ]
2974
1178
        return self.make_records(attribs, contents)
2975
1179
 
2976
1180
    def test_serialize_creation(self):
2977
1181
        tt = self.get_preview()
2978
 
        tt.new_file(u'foo\u1234', tt.root, 'bar', 'baz', True)
2979
 
        tt.new_directory('qux', tt.root, 'quxx')
 
1182
        tt.new_file(u'foo\u1234', tt.root, [b'bar'], b'baz', True)
 
1183
        tt.new_directory('qux', tt.root, b'quxx')
2980
1184
        self.assertSerializesTo(self.creation_records(), tt)
2981
1185
 
2982
1186
    def test_deserialize_creation(self):
2985
1189
        self.assertEqual(3, tt._id_number)
2986
1190
        self.assertEqual({'new-1': u'foo\u1234',
2987
1191
                          'new-2': 'qux'}, tt._new_name)
2988
 
        self.assertEqual({'new-1': 'baz', 'new-2': 'quxx'}, tt._new_id)
 
1192
        self.assertEqual({'new-1': b'baz', 'new-2': b'quxx'}, tt._new_id)
2989
1193
        self.assertEqual({'new-1': tt.root, 'new-2': tt.root}, tt._new_parent)
2990
 
        self.assertEqual({'baz': 'new-1', 'quxx': 'new-2'}, tt._r_new_id)
 
1194
        self.assertEqual({b'baz': 'new-1', b'quxx': 'new-2'}, tt._r_new_id)
2991
1195
        self.assertEqual({'new-1': True}, tt._new_executability)
2992
1196
        self.assertEqual({'new-1': 'file',
2993
1197
                          'new-2': 'directory'}, tt._new_contents)
2994
 
        foo_limbo = open(tt._limbo_name('new-1'), 'rb')
2995
 
        try:
 
1198
        with open(tt._limbo_name('new-1'), 'rb') as foo_limbo:
2996
1199
            foo_content = foo_limbo.read()
2997
 
        finally:
2998
 
            foo_limbo.close()
2999
 
        self.assertEqual('bar', foo_content)
 
1200
        self.assertEqual(b'bar', foo_content)
3000
1201
 
3001
1202
    def symlink_creation_records(self):
3002
1203
        attribs = self.default_attribs()
3003
 
        attribs['_id_number'] = 2
3004
 
        attribs['_new_name'] = {'new-1': u'foo\u1234'.encode('utf-8')}
3005
 
        attribs['_new_parent'] = {'new-1': 'new-0'}
3006
 
        contents = [('new-1', 'symlink', u'bar\u1234'.encode('utf-8'))]
 
1204
        attribs[b'_id_number'] = 2
 
1205
        attribs[b'_new_name'] = {b'new-1': u'foo\u1234'.encode('utf-8')}
 
1206
        attribs[b'_new_parent'] = {b'new-1': b'new-0'}
 
1207
        contents = [(b'new-1', b'symlink', u'bar\u1234'.encode('utf-8'))]
3007
1208
        return self.make_records(attribs, contents)
3008
1209
 
3009
1210
    def test_serialize_symlink_creation(self):
3010
 
        self.requireFeature(tests.SymlinkFeature)
 
1211
        self.requireFeature(features.SymlinkFeature)
3011
1212
        tt = self.get_preview()
3012
1213
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3013
1214
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3014
1215
 
3015
1216
    def test_deserialize_symlink_creation(self):
3016
 
        self.requireFeature(tests.SymlinkFeature)
 
1217
        self.requireFeature(features.SymlinkFeature)
3017
1218
        tt = self.get_preview()
3018
1219
        tt.deserialize(iter(self.symlink_creation_records()))
3019
1220
        abspath = tt._limbo_name('new-1')
3023
1224
    def make_destruction_preview(self):
3024
1225
        tree = self.make_branch_and_tree('.')
3025
1226
        self.build_tree([u'foo\u1234', 'bar'])
3026
 
        tree.add([u'foo\u1234', 'bar'], ['foo-id', 'bar-id'])
 
1227
        tree.add([u'foo\u1234', 'bar'], [b'foo-id', b'bar-id'])
3027
1228
        return self.get_preview(tree)
3028
1229
 
3029
1230
    def destruction_records(self):
3030
1231
        attribs = self.default_attribs()
3031
 
        attribs['_id_number'] = 3
3032
 
        attribs['_removed_id'] = ['new-1']
3033
 
        attribs['_removed_contents'] = ['new-2']
3034
 
        attribs['_tree_path_ids'] = {
3035
 
            '': 'new-0',
3036
 
            u'foo\u1234'.encode('utf-8'): 'new-1',
3037
 
            'bar': 'new-2',
 
1232
        attribs[b'_id_number'] = 3
 
1233
        attribs[b'_removed_id'] = [b'new-1']
 
1234
        attribs[b'_removed_contents'] = [b'new-2']
 
1235
        attribs[b'_tree_path_ids'] = {
 
1236
            b'': b'new-0',
 
1237
            u'foo\u1234'.encode('utf-8'): b'new-1',
 
1238
            b'bar': b'new-2',
3038
1239
            }
3039
1240
        return self.make_records(attribs, [])
3040
1241
 
3041
1242
    def test_serialize_destruction(self):
3042
1243
        tt = self.make_destruction_preview()
3043
 
        foo_trans_id = tt.trans_id_tree_file_id('foo-id')
 
1244
        foo_trans_id = tt.trans_id_tree_path(u'foo\u1234')
3044
1245
        tt.unversion_file(foo_trans_id)
3045
 
        bar_trans_id = tt.trans_id_tree_file_id('bar-id')
 
1246
        bar_trans_id = tt.trans_id_tree_path('bar')
3046
1247
        tt.delete_contents(bar_trans_id)
3047
1248
        self.assertSerializesTo(self.destruction_records(), tt)
3048
1249
 
3055
1256
        self.assertEqual({'new-1': u'foo\u1234',
3056
1257
                          'new-2': 'bar',
3057
1258
                          tt.root: ''}, tt._tree_id_paths)
3058
 
        self.assertEqual(set(['new-1']), tt._removed_id)
3059
 
        self.assertEqual(set(['new-2']), tt._removed_contents)
 
1259
        self.assertEqual({'new-1'}, tt._removed_id)
 
1260
        self.assertEqual({'new-2'}, tt._removed_contents)
3060
1261
 
3061
1262
    def missing_records(self):
3062
1263
        attribs = self.default_attribs()
3063
 
        attribs['_id_number'] = 2
3064
 
        attribs['_non_present_ids'] = {
3065
 
            'boo': 'new-1',}
 
1264
        attribs[b'_id_number'] = 2
 
1265
        attribs[b'_non_present_ids'] = {
 
1266
            b'boo': b'new-1', }
3066
1267
        return self.make_records(attribs, [])
3067
1268
 
3068
1269
    def test_serialize_missing(self):
3069
1270
        tt = self.get_preview()
3070
 
        boo_trans_id = tt.trans_id_file_id('boo')
 
1271
        tt.trans_id_file_id(b'boo')
3071
1272
        self.assertSerializesTo(self.missing_records(), tt)
3072
1273
 
3073
1274
    def test_deserialize_missing(self):
3074
1275
        tt = self.get_preview()
3075
1276
        tt.deserialize(iter(self.missing_records()))
3076
 
        self.assertEqual({'boo': 'new-1'}, tt._non_present_ids)
 
1277
        self.assertEqual({b'boo': 'new-1'}, tt._non_present_ids)
3077
1278
 
3078
1279
    def make_modification_preview(self):
3079
 
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3080
 
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
1280
        LINES_ONE = b'aa\nbb\ncc\ndd\n'
 
1281
        LINES_TWO = b'z\nbb\nx\ndd\n'
3081
1282
        tree = self.make_branch_and_tree('tree')
3082
1283
        self.build_tree_contents([('tree/file', LINES_ONE)])
3083
 
        tree.add('file', 'file-id')
3084
 
        return self.get_preview(tree), LINES_TWO
 
1284
        tree.add('file', b'file-id')
 
1285
        return self.get_preview(tree), [LINES_TWO]
3085
1286
 
3086
1287
    def modification_records(self):
3087
1288
        attribs = self.default_attribs()
3088
 
        attribs['_id_number'] = 2
3089
 
        attribs['_tree_path_ids'] = {
3090
 
            'file': 'new-1',
3091
 
            '': 'new-0',}
3092
 
        attribs['_removed_contents'] = ['new-1']
3093
 
        contents = [('new-1', 'file',
3094
 
                     'i 1\nz\n\nc 0 1 1 1\ni 1\nx\n\nc 0 3 3 1\n')]
 
1289
        attribs[b'_id_number'] = 2
 
1290
        attribs[b'_tree_path_ids'] = {
 
1291
            b'file': b'new-1',
 
1292
            b'': b'new-0', }
 
1293
        attribs[b'_removed_contents'] = [b'new-1']
 
1294
        contents = [(b'new-1', b'file',
 
1295
                     b'i 1\nz\n\nc 0 1 1 1\ni 1\nx\n\nc 0 3 3 1\n')]
3095
1296
        return self.make_records(attribs, contents)
3096
1297
 
3097
1298
    def test_serialize_modification(self):
3098
1299
        tt, LINES = self.make_modification_preview()
3099
 
        trans_id = tt.trans_id_file_id('file-id')
 
1300
        trans_id = tt.trans_id_file_id(b'file-id')
3100
1301
        tt.delete_contents(trans_id)
3101
1302
        tt.create_file(LINES, trans_id)
3102
1303
        self.assertSerializesTo(self.modification_records(), tt)
3104
1305
    def test_deserialize_modification(self):
3105
1306
        tt, LINES = self.make_modification_preview()
3106
1307
        tt.deserialize(iter(self.modification_records()))
3107
 
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
 
1308
        self.assertFileEqual(b''.join(LINES), tt._limbo_name('new-1'))
3108
1309
 
3109
1310
    def make_kind_change_preview(self):
3110
 
        LINES = 'a\nb\nc\nd\n'
 
1311
        LINES = b'a\nb\nc\nd\n'
3111
1312
        tree = self.make_branch_and_tree('tree')
3112
1313
        self.build_tree(['tree/foo/'])
3113
 
        tree.add('foo', 'foo-id')
3114
 
        return self.get_preview(tree), LINES
 
1314
        tree.add('foo', b'foo-id')
 
1315
        return self.get_preview(tree), [LINES]
3115
1316
 
3116
1317
    def kind_change_records(self):
3117
1318
        attribs = self.default_attribs()
3118
 
        attribs['_id_number'] = 2
3119
 
        attribs['_tree_path_ids'] = {
3120
 
            'foo': 'new-1',
3121
 
            '': 'new-0',}
3122
 
        attribs['_removed_contents'] = ['new-1']
3123
 
        contents = [('new-1', 'file',
3124
 
                     'i 4\na\nb\nc\nd\n\n')]
 
1319
        attribs[b'_id_number'] = 2
 
1320
        attribs[b'_tree_path_ids'] = {
 
1321
            b'foo': b'new-1',
 
1322
            b'': b'new-0', }
 
1323
        attribs[b'_removed_contents'] = [b'new-1']
 
1324
        contents = [(b'new-1', b'file',
 
1325
                     b'i 4\na\nb\nc\nd\n\n')]
3125
1326
        return self.make_records(attribs, contents)
3126
1327
 
3127
1328
    def test_serialize_kind_change(self):
3128
1329
        tt, LINES = self.make_kind_change_preview()
3129
 
        trans_id = tt.trans_id_file_id('foo-id')
 
1330
        trans_id = tt.trans_id_file_id(b'foo-id')
3130
1331
        tt.delete_contents(trans_id)
3131
1332
        tt.create_file(LINES, trans_id)
3132
1333
        self.assertSerializesTo(self.kind_change_records(), tt)
3134
1335
    def test_deserialize_kind_change(self):
3135
1336
        tt, LINES = self.make_kind_change_preview()
3136
1337
        tt.deserialize(iter(self.kind_change_records()))
3137
 
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
 
1338
        self.assertFileEqual(b''.join(LINES), tt._limbo_name('new-1'))
3138
1339
 
3139
1340
    def make_add_contents_preview(self):
3140
 
        LINES = 'a\nb\nc\nd\n'
 
1341
        LINES = b'a\nb\nc\nd\n'
3141
1342
        tree = self.make_branch_and_tree('tree')
3142
1343
        self.build_tree(['tree/foo'])
3143
1344
        tree.add('foo')
3146
1347
 
3147
1348
    def add_contents_records(self):
3148
1349
        attribs = self.default_attribs()
3149
 
        attribs['_id_number'] = 2
3150
 
        attribs['_tree_path_ids'] = {
3151
 
            'foo': 'new-1',
3152
 
            '': 'new-0',}
3153
 
        contents = [('new-1', 'file',
3154
 
                     'i 4\na\nb\nc\nd\n\n')]
 
1350
        attribs[b'_id_number'] = 2
 
1351
        attribs[b'_tree_path_ids'] = {
 
1352
            b'foo': b'new-1',
 
1353
            b'': b'new-0', }
 
1354
        contents = [(b'new-1', b'file',
 
1355
                     b'i 4\na\nb\nc\nd\n\n')]
3155
1356
        return self.make_records(attribs, contents)
3156
1357
 
3157
1358
    def test_serialize_add_contents(self):
3158
1359
        tt, LINES = self.make_add_contents_preview()
3159
1360
        trans_id = tt.trans_id_tree_path('foo')
3160
 
        tt.create_file(LINES, trans_id)
 
1361
        tt.create_file([LINES], trans_id)
3161
1362
        self.assertSerializesTo(self.add_contents_records(), tt)
3162
1363
 
3163
1364
    def test_deserialize_add_contents(self):
3166
1367
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
3167
1368
 
3168
1369
    def test_get_parents_lines(self):
3169
 
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3170
 
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
1370
        LINES_ONE = b'aa\nbb\ncc\ndd\n'
3171
1371
        tree = self.make_branch_and_tree('tree')
3172
1372
        self.build_tree_contents([('tree/file', LINES_ONE)])
3173
 
        tree.add('file', 'file-id')
 
1373
        tree.add('file', b'file-id')
3174
1374
        tt = self.get_preview(tree)
3175
1375
        trans_id = tt.trans_id_tree_path('file')
3176
 
        self.assertEqual((['aa\n', 'bb\n', 'cc\n', 'dd\n'],),
3177
 
            tt._get_parents_lines(trans_id))
 
1376
        self.assertEqual(([b'aa\n', b'bb\n', b'cc\n', b'dd\n'],),
 
1377
                         tt._get_parents_lines(trans_id))
3178
1378
 
3179
1379
    def test_get_parents_texts(self):
3180
 
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3181
 
        LINES_TWO = 'z\nbb\nx\ndd\n'
 
1380
        LINES_ONE = b'aa\nbb\ncc\ndd\n'
3182
1381
        tree = self.make_branch_and_tree('tree')
3183
1382
        self.build_tree_contents([('tree/file', LINES_ONE)])
3184
 
        tree.add('file', 'file-id')
 
1383
        tree.add('file', b'file-id')
3185
1384
        tt = self.get_preview(tree)
3186
1385
        trans_id = tt.trans_id_tree_path('file')
3187
1386
        self.assertEqual((LINES_ONE,),
3188
 
            tt._get_parents_texts(trans_id))
 
1387
                         tt._get_parents_texts(trans_id))
 
1388
 
 
1389
 
 
1390
class TestOrphan(tests.TestCaseWithTransport):
 
1391
 
 
1392
    def test_no_orphan_for_transform_preview(self):
 
1393
        tree = self.make_branch_and_tree('tree')
 
1394
        tt = tree.preview_transform()
 
1395
        self.addCleanup(tt.finalize)
 
1396
        self.assertRaises(NotImplementedError, tt.new_orphan, 'foo', 'bar')
 
1397
 
 
1398
    def _set_orphan_policy(self, wt, policy):
 
1399
        wt.branch.get_config_stack().set('transform.orphan_policy',
 
1400
                                         policy)
 
1401
 
 
1402
    def _prepare_orphan(self, wt):
 
1403
        self.build_tree(['dir/', 'dir/file', 'dir/foo'])
 
1404
        wt.add(['dir', 'dir/file'], [b'dir-id', b'file-id'])
 
1405
        wt.commit('add dir and file ignoring foo')
 
1406
        tt = wt.transform()
 
1407
        self.addCleanup(tt.finalize)
 
1408
        # dir and bar are deleted
 
1409
        dir_tid = tt.trans_id_tree_path('dir')
 
1410
        file_tid = tt.trans_id_tree_path('dir/file')
 
1411
        orphan_tid = tt.trans_id_tree_path('dir/foo')
 
1412
        tt.delete_contents(file_tid)
 
1413
        tt.unversion_file(file_tid)
 
1414
        tt.delete_contents(dir_tid)
 
1415
        tt.unversion_file(dir_tid)
 
1416
        # There should be a conflict because dir still contain foo
 
1417
        raw_conflicts = tt.find_conflicts()
 
1418
        self.assertLength(1, raw_conflicts)
 
1419
        self.assertEqual(('missing parent', 'new-1'), raw_conflicts[0])
 
1420
        return tt, orphan_tid
 
1421
 
 
1422
    def test_new_orphan_created(self):
 
1423
        wt = self.make_branch_and_tree('.')
 
1424
        self._set_orphan_policy(wt, 'move')
 
1425
        tt, orphan_tid = self._prepare_orphan(wt)
 
1426
        warnings = []
 
1427
 
 
1428
        def warning(*args):
 
1429
            warnings.append(args[0] % args[1:])
 
1430
        self.overrideAttr(trace, 'warning', warning)
 
1431
        remaining_conflicts = resolve_conflicts(tt)
 
1432
        self.assertEqual(['dir/foo has been orphaned in brz-orphans'],
 
1433
                         warnings)
 
1434
        # Yeah for resolved conflicts !
 
1435
        self.assertLength(0, remaining_conflicts)
 
1436
        # We have a new orphan
 
1437
        self.assertEqual('foo.~1~', tt.final_name(orphan_tid))
 
1438
        self.assertEqual('brz-orphans',
 
1439
                         tt.final_name(tt.final_parent(orphan_tid)))
 
1440
 
 
1441
    def test_never_orphan(self):
 
1442
        wt = self.make_branch_and_tree('.')
 
1443
        self._set_orphan_policy(wt, 'conflict')
 
1444
        tt, orphan_tid = self._prepare_orphan(wt)
 
1445
        remaining_conflicts = resolve_conflicts(tt)
 
1446
        self.assertLength(1, remaining_conflicts)
 
1447
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
1448
                         remaining_conflicts.pop())
 
1449
 
 
1450
    def test_orphan_error(self):
 
1451
        def bogus_orphan(tt, orphan_id, parent_id):
 
1452
            raise transform.OrphaningError(tt.final_name(orphan_id),
 
1453
                                           tt.final_name(parent_id))
 
1454
        transform.orphaning_registry.register('bogus', bogus_orphan,
 
1455
                                              'Raise an error when orphaning')
 
1456
        wt = self.make_branch_and_tree('.')
 
1457
        self._set_orphan_policy(wt, 'bogus')
 
1458
        tt, orphan_tid = self._prepare_orphan(wt)
 
1459
        remaining_conflicts = resolve_conflicts(tt)
 
1460
        self.assertLength(1, remaining_conflicts)
 
1461
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
1462
                         remaining_conflicts.pop())
 
1463
 
 
1464
    def test_unknown_orphan_policy(self):
 
1465
        wt = self.make_branch_and_tree('.')
 
1466
        # Set a fictional policy nobody ever implemented
 
1467
        self._set_orphan_policy(wt, 'donttouchmypreciouuus')
 
1468
        tt, orphan_tid = self._prepare_orphan(wt)
 
1469
        warnings = []
 
1470
 
 
1471
        def warning(*args):
 
1472
            warnings.append(args[0] % args[1:])
 
1473
        self.overrideAttr(trace, 'warning', warning)
 
1474
        remaining_conflicts = resolve_conflicts(tt)
 
1475
        # We fallback to the default policy which create a conflict
 
1476
        self.assertLength(1, remaining_conflicts)
 
1477
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
1478
                         remaining_conflicts.pop())
 
1479
        self.assertLength(1, warnings)
 
1480
        self.assertStartsWith(warnings[0], 'Value "donttouchmypreciouuus" ')
 
1481
 
 
1482
 
 
1483
class TestTransformHooks(tests.TestCaseWithTransport):
 
1484
 
 
1485
    def setUp(self):
 
1486
        super(TestTransformHooks, self).setUp()
 
1487
        self.wt = self.make_branch_and_tree('.')
 
1488
        os.chdir('..')
 
1489
 
 
1490
    def transform(self):
 
1491
        transform = self.wt.transform()
 
1492
        self.addCleanup(transform.finalize)
 
1493
        return transform, transform.root
 
1494
 
 
1495
    def test_pre_commit_hooks(self):
 
1496
        calls = []
 
1497
 
 
1498
        def record_pre_transform(tree, tt):
 
1499
            calls.append((tree, tt))
 
1500
        MutableTree.hooks.install_named_hook(
 
1501
            'pre_transform', record_pre_transform, "Pre transform")
 
1502
        transform, root = self.transform()
 
1503
        old_root_id = transform.tree_file_id(root)
 
1504
        transform.apply()
 
1505
        self.assertEqual(old_root_id, self.wt.path2id(''))
 
1506
        self.assertEqual([(self.wt, transform)], calls)
 
1507
 
 
1508
    def test_post_commit_hooks(self):
 
1509
        calls = []
 
1510
 
 
1511
        def record_post_transform(tree, tt):
 
1512
            calls.append((tree, tt))
 
1513
        MutableTree.hooks.install_named_hook(
 
1514
            'post_transform', record_post_transform, "Post transform")
 
1515
        transform, root = self.transform()
 
1516
        old_root_id = transform.tree_file_id(root)
 
1517
        transform.apply()
 
1518
        self.assertEqual(old_root_id, self.wt.path2id(''))
 
1519
        self.assertEqual([(self.wt, transform)], calls)
 
1520
 
 
1521
 
 
1522
class TestLinkTree(tests.TestCaseWithTransport):
 
1523
 
 
1524
    _test_needs_features = [HardlinkFeature]
 
1525
 
 
1526
    def setUp(self):
 
1527
        tests.TestCaseWithTransport.setUp(self)
 
1528
        self.parent_tree = self.make_branch_and_tree('parent')
 
1529
        self.parent_tree.lock_write()
 
1530
        self.addCleanup(self.parent_tree.unlock)
 
1531
        self.build_tree_contents([('parent/foo', b'bar')])
 
1532
        self.parent_tree.add('foo')
 
1533
        self.parent_tree.commit('added foo')
 
1534
        child_controldir = self.parent_tree.controldir.sprout('child')
 
1535
        self.child_tree = child_controldir.open_workingtree()
 
1536
 
 
1537
    def hardlinked(self):
 
1538
        parent_stat = os.lstat(self.parent_tree.abspath('foo'))
 
1539
        child_stat = os.lstat(self.child_tree.abspath('foo'))
 
1540
        return parent_stat.st_ino == child_stat.st_ino
 
1541
 
 
1542
    def test_link_fails_if_modified(self):
 
1543
        """If the file to be linked has modified text, don't link."""
 
1544
        self.build_tree_contents([('child/foo', b'baz')])
 
1545
        transform.link_tree(self.child_tree, self.parent_tree)
 
1546
        self.assertFalse(self.hardlinked())
 
1547
 
 
1548
    def test_link_fails_if_execute_bit_changed(self):
 
1549
        """If the file to be linked has modified execute bit, don't link."""
 
1550
        tt = self.child_tree.transform()
 
1551
        try:
 
1552
            trans_id = tt.trans_id_tree_path('foo')
 
1553
            tt.set_executability(True, trans_id)
 
1554
            tt.apply()
 
1555
        finally:
 
1556
            tt.finalize()
 
1557
        transform.link_tree(self.child_tree, self.parent_tree)
 
1558
        self.assertFalse(self.hardlinked())
 
1559
 
 
1560
    def test_link_succeeds_if_unmodified(self):
 
1561
        """If the file to be linked is unmodified, link"""
 
1562
        transform.link_tree(self.child_tree, self.parent_tree)
 
1563
        self.assertTrue(self.hardlinked())
 
1564
 
 
1565
 
 
1566
class ErrorTests(tests.TestCase):
 
1567
 
 
1568
    def test_transform_rename_failed(self):
 
1569
        e = TransformRenameFailed(u"from", u"to", "readonly file", 2)
 
1570
        self.assertEqual(
 
1571
            u"Failed to rename from to to: readonly file",
 
1572
            str(e))