~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_bundle.py

  • Committer: Martin Pool
  • Date: 2005-09-13 05:22:41 UTC
  • Revision ID: mbp@sourcefrog.net-20050913052241-52dbd8e8ced620f6
- better BZR_DEBUG trace output

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
from cStringIO import StringIO
18
 
import os
19
 
import sys
20
 
import tempfile
21
 
 
22
 
from bzrlib import (
23
 
    bzrdir,
24
 
    errors,
25
 
    inventory,
26
 
    repository,
27
 
    treebuilder,
28
 
    )
29
 
from bzrlib.builtins import _merge_helper
30
 
from bzrlib.bzrdir import BzrDir
31
 
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
32
 
from bzrlib.bundle.bundle_data import BundleTree
33
 
from bzrlib.bundle.serializer import write_bundle, read_bundle, v10
34
 
from bzrlib.bundle.serializer.v08 import BundleSerializerV08
35
 
from bzrlib.bundle.serializer.v09 import BundleSerializerV09
36
 
from bzrlib.bundle.serializer.v10 import BundleSerializerV10
37
 
from bzrlib.branch import Branch
38
 
from bzrlib.diff import internal_diff
39
 
from bzrlib.errors import (BzrError, TestamentMismatch, NotABundle, BadBundle, 
40
 
                           NoSuchFile,)
41
 
from bzrlib.merge import Merge3Merger
42
 
from bzrlib.repofmt import knitrepo
43
 
from bzrlib.osutils import has_symlinks, sha_file
44
 
from bzrlib.tests import (TestCaseInTempDir, TestCaseWithTransport,
45
 
                          TestCase, TestSkipped, test_commit)
46
 
from bzrlib.transform import TreeTransform
47
 
from bzrlib.workingtree import WorkingTree
48
 
 
49
 
 
50
 
class MockTree(object):
51
 
    def __init__(self):
52
 
        from bzrlib.inventory import InventoryDirectory, ROOT_ID
53
 
        object.__init__(self)
54
 
        self.paths = {ROOT_ID: ""}
55
 
        self.ids = {"": ROOT_ID}
56
 
        self.contents = {}
57
 
        self.root = InventoryDirectory(ROOT_ID, '', None)
58
 
 
59
 
    inventory = property(lambda x:x)
60
 
 
61
 
    def __iter__(self):
62
 
        return self.paths.iterkeys()
63
 
 
64
 
    def __getitem__(self, file_id):
65
 
        if file_id == self.root.file_id:
66
 
            return self.root
67
 
        else:
68
 
            return self.make_entry(file_id, self.paths[file_id])
69
 
 
70
 
    def parent_id(self, file_id):
71
 
        parent_dir = os.path.dirname(self.paths[file_id])
72
 
        if parent_dir == "":
73
 
            return None
74
 
        return self.ids[parent_dir]
75
 
 
76
 
    def iter_entries(self):
77
 
        for path, file_id in self.ids.iteritems():
78
 
            yield path, self[file_id]
79
 
 
80
 
    def get_file_kind(self, file_id):
81
 
        if file_id in self.contents:
82
 
            kind = 'file'
83
 
        else:
84
 
            kind = 'directory'
85
 
        return kind
86
 
 
87
 
    def make_entry(self, file_id, path):
88
 
        from bzrlib.inventory import (InventoryEntry, InventoryFile
89
 
                                    , InventoryDirectory, InventoryLink)
90
 
        name = os.path.basename(path)
91
 
        kind = self.get_file_kind(file_id)
92
 
        parent_id = self.parent_id(file_id)
93
 
        text_sha_1, text_size = self.contents_stats(file_id)
94
 
        if kind == 'directory':
95
 
            ie = InventoryDirectory(file_id, name, parent_id)
96
 
        elif kind == 'file':
97
 
            ie = InventoryFile(file_id, name, parent_id)
98
 
        elif kind == 'symlink':
99
 
            ie = InventoryLink(file_id, name, parent_id)
100
 
        else:
101
 
            raise BzrError('unknown kind %r' % kind)
102
 
        ie.text_sha1 = text_sha_1
103
 
        ie.text_size = text_size
104
 
        return ie
105
 
 
106
 
    def add_dir(self, file_id, path):
107
 
        self.paths[file_id] = path
108
 
        self.ids[path] = file_id
109
 
    
110
 
    def add_file(self, file_id, path, contents):
111
 
        self.add_dir(file_id, path)
112
 
        self.contents[file_id] = contents
113
 
 
114
 
    def path2id(self, path):
115
 
        return self.ids.get(path)
116
 
 
117
 
    def id2path(self, file_id):
118
 
        return self.paths.get(file_id)
119
 
 
120
 
    def has_id(self, file_id):
121
 
        return self.id2path(file_id) is not None
122
 
 
123
 
    def get_file(self, file_id):
124
 
        result = StringIO()
125
 
        result.write(self.contents[file_id])
126
 
        result.seek(0,0)
127
 
        return result
128
 
 
129
 
    def contents_stats(self, file_id):
130
 
        if file_id not in self.contents:
131
 
            return None, None
132
 
        text_sha1 = sha_file(self.get_file(file_id))
133
 
        return text_sha1, len(self.contents[file_id])
134
 
 
135
 
 
136
 
class BTreeTester(TestCase):
137
 
    """A simple unittest tester for the BundleTree class."""
138
 
 
139
 
    def make_tree_1(self):
140
 
        mtree = MockTree()
141
 
        mtree.add_dir("a", "grandparent")
142
 
        mtree.add_dir("b", "grandparent/parent")
143
 
        mtree.add_file("c", "grandparent/parent/file", "Hello\n")
144
 
        mtree.add_dir("d", "grandparent/alt_parent")
145
 
        return BundleTree(mtree, ''), mtree
146
 
        
147
 
    def test_renames(self):
148
 
        """Ensure that file renames have the proper effect on children"""
149
 
        btree = self.make_tree_1()[0]
150
 
        self.assertEqual(btree.old_path("grandparent"), "grandparent")
151
 
        self.assertEqual(btree.old_path("grandparent/parent"), 
152
 
                         "grandparent/parent")
153
 
        self.assertEqual(btree.old_path("grandparent/parent/file"),
154
 
                         "grandparent/parent/file")
155
 
 
156
 
        self.assertEqual(btree.id2path("a"), "grandparent")
157
 
        self.assertEqual(btree.id2path("b"), "grandparent/parent")
158
 
        self.assertEqual(btree.id2path("c"), "grandparent/parent/file")
159
 
 
160
 
        self.assertEqual(btree.path2id("grandparent"), "a")
161
 
        self.assertEqual(btree.path2id("grandparent/parent"), "b")
162
 
        self.assertEqual(btree.path2id("grandparent/parent/file"), "c")
163
 
 
164
 
        assert btree.path2id("grandparent2") is None
165
 
        assert btree.path2id("grandparent2/parent") is None
166
 
        assert btree.path2id("grandparent2/parent/file") is None
167
 
 
168
 
        btree.note_rename("grandparent", "grandparent2")
169
 
        assert btree.old_path("grandparent") is None
170
 
        assert btree.old_path("grandparent/parent") is None
171
 
        assert btree.old_path("grandparent/parent/file") is None
172
 
 
173
 
        self.assertEqual(btree.id2path("a"), "grandparent2")
174
 
        self.assertEqual(btree.id2path("b"), "grandparent2/parent")
175
 
        self.assertEqual(btree.id2path("c"), "grandparent2/parent/file")
176
 
 
177
 
        self.assertEqual(btree.path2id("grandparent2"), "a")
178
 
        self.assertEqual(btree.path2id("grandparent2/parent"), "b")
179
 
        self.assertEqual(btree.path2id("grandparent2/parent/file"), "c")
180
 
 
181
 
        assert btree.path2id("grandparent") is None
182
 
        assert btree.path2id("grandparent/parent") is None
183
 
        assert btree.path2id("grandparent/parent/file") is None
184
 
 
185
 
        btree.note_rename("grandparent/parent", "grandparent2/parent2")
186
 
        self.assertEqual(btree.id2path("a"), "grandparent2")
187
 
        self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
188
 
        self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file")
189
 
 
190
 
        self.assertEqual(btree.path2id("grandparent2"), "a")
191
 
        self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
192
 
        self.assertEqual(btree.path2id("grandparent2/parent2/file"), "c")
193
 
 
194
 
        assert btree.path2id("grandparent2/parent") is None
195
 
        assert btree.path2id("grandparent2/parent/file") is None
196
 
 
197
 
        btree.note_rename("grandparent/parent/file", 
198
 
                          "grandparent2/parent2/file2")
199
 
        self.assertEqual(btree.id2path("a"), "grandparent2")
200
 
        self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
201
 
        self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file2")
202
 
 
203
 
        self.assertEqual(btree.path2id("grandparent2"), "a")
204
 
        self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
205
 
        self.assertEqual(btree.path2id("grandparent2/parent2/file2"), "c")
206
 
 
207
 
        assert btree.path2id("grandparent2/parent2/file") is None
208
 
 
209
 
    def test_moves(self):
210
 
        """Ensure that file moves have the proper effect on children"""
211
 
        btree = self.make_tree_1()[0]
212
 
        btree.note_rename("grandparent/parent/file", 
213
 
                          "grandparent/alt_parent/file")
214
 
        self.assertEqual(btree.id2path("c"), "grandparent/alt_parent/file")
215
 
        self.assertEqual(btree.path2id("grandparent/alt_parent/file"), "c")
216
 
        assert btree.path2id("grandparent/parent/file") is None
217
 
 
218
 
    def unified_diff(self, old, new):
219
 
        out = StringIO()
220
 
        internal_diff("old", old, "new", new, out)
221
 
        out.seek(0,0)
222
 
        return out.read()
223
 
 
224
 
    def make_tree_2(self):
225
 
        btree = self.make_tree_1()[0]
226
 
        btree.note_rename("grandparent/parent/file", 
227
 
                          "grandparent/alt_parent/file")
228
 
        assert btree.id2path("e") is None
229
 
        assert btree.path2id("grandparent/parent/file") is None
230
 
        btree.note_id("e", "grandparent/parent/file")
231
 
        return btree
232
 
 
233
 
    def test_adds(self):
234
 
        """File/inventory adds"""
235
 
        btree = self.make_tree_2()
236
 
        add_patch = self.unified_diff([], ["Extra cheese\n"])
237
 
        btree.note_patch("grandparent/parent/file", add_patch)
238
 
        btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
239
 
        btree.note_target('grandparent/parent/symlink', 'venus')
240
 
        self.adds_test(btree)
241
 
 
242
 
    def adds_test(self, btree):
243
 
        self.assertEqual(btree.id2path("e"), "grandparent/parent/file")
244
 
        self.assertEqual(btree.path2id("grandparent/parent/file"), "e")
245
 
        self.assertEqual(btree.get_file("e").read(), "Extra cheese\n")
246
 
        self.assertEqual(btree.get_symlink_target('f'), 'venus')
247
 
 
248
 
    def test_adds2(self):
249
 
        """File/inventory adds, with patch-compatibile renames"""
250
 
        btree = self.make_tree_2()
251
 
        btree.contents_by_id = False
252
 
        add_patch = self.unified_diff(["Hello\n"], ["Extra cheese\n"])
253
 
        btree.note_patch("grandparent/parent/file", add_patch)
254
 
        btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
255
 
        btree.note_target('grandparent/parent/symlink', 'venus')
256
 
        self.adds_test(btree)
257
 
 
258
 
    def make_tree_3(self):
259
 
        btree, mtree = self.make_tree_1()
260
 
        mtree.add_file("e", "grandparent/parent/topping", "Anchovies\n")
261
 
        btree.note_rename("grandparent/parent/file", 
262
 
                          "grandparent/alt_parent/file")
263
 
        btree.note_rename("grandparent/parent/topping", 
264
 
                          "grandparent/alt_parent/stopping")
265
 
        return btree
266
 
 
267
 
    def get_file_test(self, btree):
268
 
        self.assertEqual(btree.get_file("e").read(), "Lemon\n")
269
 
        self.assertEqual(btree.get_file("c").read(), "Hello\n")
270
 
 
271
 
    def test_get_file(self):
272
 
        """Get file contents"""
273
 
        btree = self.make_tree_3()
274
 
        mod_patch = self.unified_diff(["Anchovies\n"], ["Lemon\n"])
275
 
        btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
276
 
        self.get_file_test(btree)
277
 
 
278
 
    def test_get_file2(self):
279
 
        """Get file contents, with patch-compatibile renames"""
280
 
        btree = self.make_tree_3()
281
 
        btree.contents_by_id = False
282
 
        mod_patch = self.unified_diff([], ["Lemon\n"])
283
 
        btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
284
 
        mod_patch = self.unified_diff([], ["Hello\n"])
285
 
        btree.note_patch("grandparent/alt_parent/file", mod_patch)
286
 
        self.get_file_test(btree)
287
 
 
288
 
    def test_delete(self):
289
 
        "Deletion by bundle"
290
 
        btree = self.make_tree_1()[0]
291
 
        self.assertEqual(btree.get_file("c").read(), "Hello\n")
292
 
        btree.note_deletion("grandparent/parent/file")
293
 
        assert btree.id2path("c") is None
294
 
        assert btree.path2id("grandparent/parent/file") is None
295
 
 
296
 
    def sorted_ids(self, tree):
297
 
        ids = list(tree)
298
 
        ids.sort()
299
 
        return ids
300
 
 
301
 
    def test_iteration(self):
302
 
        """Ensure that iteration through ids works properly"""
303
 
        btree = self.make_tree_1()[0]
304
 
        self.assertEqual(self.sorted_ids(btree),
305
 
            [inventory.ROOT_ID, 'a', 'b', 'c', 'd'])
306
 
        btree.note_deletion("grandparent/parent/file")
307
 
        btree.note_id("e", "grandparent/alt_parent/fool", kind="directory")
308
 
        btree.note_last_changed("grandparent/alt_parent/fool", 
309
 
                                "revisionidiguess")
310
 
        self.assertEqual(self.sorted_ids(btree),
311
 
            [inventory.ROOT_ID, 'a', 'b', 'd', 'e'])
312
 
 
313
 
 
314
 
class BundleTester1(TestCaseWithTransport):
315
 
 
316
 
    def test_mismatched_bundle(self):
317
 
        format = bzrdir.BzrDirMetaFormat1()
318
 
        format.repository_format = knitrepo.RepositoryFormatKnit3()
319
 
        serializer = BundleSerializerV08('0.8')
320
 
        b = self.make_branch('.', format=format)
321
 
        self.assertRaises(errors.IncompatibleBundleFormat, serializer.write, 
322
 
                          b.repository, [], {}, StringIO())
323
 
 
324
 
    def test_matched_bundle(self):
325
 
        """Don't raise IncompatibleBundleFormat for knit2 and bundle0.9"""
326
 
        format = bzrdir.BzrDirMetaFormat1()
327
 
        format.repository_format = knitrepo.RepositoryFormatKnit3()
328
 
        serializer = BundleSerializerV09('0.9')
329
 
        b = self.make_branch('.', format=format)
330
 
        serializer.write(b.repository, [], {}, StringIO())
331
 
 
332
 
    def test_mismatched_model(self):
333
 
        """Try copying a bundle from knit2 to knit1"""
334
 
        format = bzrdir.BzrDirMetaFormat1()
335
 
        format.repository_format = knitrepo.RepositoryFormatKnit3()
336
 
        source = self.make_branch_and_tree('source', format=format)
337
 
        source.commit('one', rev_id='one-id')
338
 
        source.commit('two', rev_id='two-id')
339
 
        text = StringIO()
340
 
        write_bundle(source.branch.repository, 'two-id', None, text, 
341
 
                     format='0.9')
342
 
        text.seek(0)
343
 
 
344
 
        format = bzrdir.BzrDirMetaFormat1()
345
 
        format.repository_format = knitrepo.RepositoryFormatKnit1()
346
 
        target = self.make_branch('target', format=format)
347
 
        self.assertRaises(errors.IncompatibleRevision, install_bundle, 
348
 
                          target.repository, read_bundle(text))
349
 
 
350
 
 
351
 
class BundleTester(object):
352
 
 
353
 
    def bzrdir_format(self):
354
 
        format = bzrdir.BzrDirMetaFormat1()
355
 
        format.repository_format = knitrepo.RepositoryFormatKnit1()
356
 
        return format
357
 
 
358
 
    def make_branch_and_tree(self, path, format=None):
359
 
        if format is None:
360
 
            format = self.bzrdir_format()
361
 
        return TestCaseWithTransport.make_branch_and_tree(self, path, format)
362
 
 
363
 
    def make_branch(self, path, format=None):
364
 
        if format is None:
365
 
            format = self.bzrdir_format()
366
 
        return TestCaseWithTransport.make_branch(self, path, format)
367
 
 
368
 
    def create_bundle_text(self, base_rev_id, rev_id):
369
 
        bundle_txt = StringIO()
370
 
        rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id, 
371
 
                               bundle_txt, format=self.format)
372
 
        bundle_txt.seek(0)
373
 
        self.assertEqual(bundle_txt.readline(), 
374
 
                         '# Bazaar revision bundle v%s\n' % self.format)
375
 
        self.assertEqual(bundle_txt.readline(), '#\n')
376
 
 
377
 
        rev = self.b1.repository.get_revision(rev_id)
378
 
        self.assertEqual(bundle_txt.readline().decode('utf-8'),
379
 
                         u'# message:\n')
380
 
 
381
 
        open(',,bundle', 'wb').write(bundle_txt.getvalue())
382
 
        bundle_txt.seek(0)
383
 
        return bundle_txt, rev_ids
384
 
 
385
 
    def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
386
 
        """Create a bundle from base_rev_id -> rev_id in built-in branch.
387
 
        Make sure that the text generated is valid, and that it
388
 
        can be applied against the base, and generate the same information.
389
 
        
390
 
        :return: The in-memory bundle 
391
 
        """
392
 
        bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
393
 
 
394
 
        # This should also validate the generated bundle 
395
 
        bundle = read_bundle(bundle_txt)
396
 
        repository = self.b1.repository
397
 
        for bundle_rev in bundle.real_revisions:
398
 
            # These really should have already been checked when we read the
399
 
            # bundle, since it computes the sha1 hash for the revision, which
400
 
            # only will match if everything is okay, but lets be explicit about
401
 
            # it
402
 
            branch_rev = repository.get_revision(bundle_rev.revision_id)
403
 
            for a in ('inventory_sha1', 'revision_id', 'parent_ids',
404
 
                      'timestamp', 'timezone', 'message', 'committer', 
405
 
                      'parent_ids', 'properties'):
406
 
                self.assertEqual(getattr(branch_rev, a), 
407
 
                                 getattr(bundle_rev, a))
408
 
            self.assertEqual(len(branch_rev.parent_ids), 
409
 
                             len(bundle_rev.parent_ids))
410
 
        self.assertEqual(rev_ids, 
411
 
                         [r.revision_id for r in bundle.real_revisions])
412
 
        self.valid_apply_bundle(base_rev_id, bundle,
413
 
                                   checkout_dir=checkout_dir)
414
 
 
415
 
        return bundle
416
 
 
417
 
    def get_invalid_bundle(self, base_rev_id, rev_id):
418
 
        """Create a bundle from base_rev_id -> rev_id in built-in branch.
419
 
        Munge the text so that it's invalid.
420
 
        
421
 
        :return: The in-memory bundle
422
 
        """
423
 
        bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
424
 
        new_text = bundle_txt.getvalue().replace('executable:no', 
425
 
                                               'executable:yes')
426
 
        bundle_txt = StringIO(new_text)
427
 
        bundle = read_bundle(bundle_txt)
428
 
        self.valid_apply_bundle(base_rev_id, bundle)
429
 
        return bundle 
430
 
 
431
 
    def test_non_bundle(self):
432
 
        self.assertRaises(NotABundle, read_bundle, StringIO('#!/bin/sh\n'))
433
 
 
434
 
    def test_malformed(self):
435
 
        self.assertRaises(BadBundle, read_bundle, 
436
 
                          StringIO('# Bazaar revision bundle v'))
437
 
 
438
 
    def test_crlf_bundle(self):
439
 
        try:
440
 
            read_bundle(StringIO('# Bazaar revision bundle v0.8\r\n'))
441
 
        except BadBundle:
442
 
            # It is currently permitted for bundles with crlf line endings to
443
 
            # make read_bundle raise a BadBundle, but this should be fixed.
444
 
            # Anything else, especially NotABundle, is an error.
445
 
            pass
446
 
 
447
 
    def get_checkout(self, rev_id, checkout_dir=None):
448
 
        """Get a new tree, with the specified revision in it.
449
 
        """
450
 
 
451
 
        if checkout_dir is None:
452
 
            checkout_dir = tempfile.mkdtemp(prefix='test-branch-', dir='.')
453
 
        else:
454
 
            if not os.path.exists(checkout_dir):
455
 
                os.mkdir(checkout_dir)
456
 
        tree = self.make_branch_and_tree(checkout_dir)
457
 
        s = StringIO()
458
 
        ancestors = write_bundle(self.b1.repository, rev_id, None, s,
459
 
                                 format=self.format)
460
 
        s.seek(0)
461
 
        assert isinstance(s.getvalue(), str), (
462
 
            "Bundle isn't a bytestring:\n %s..." % repr(s.getvalue())[:40])
463
 
        install_bundle(tree.branch.repository, read_bundle(s))
464
 
        for ancestor in ancestors:
465
 
            old = self.b1.repository.revision_tree(ancestor)
466
 
            new = tree.branch.repository.revision_tree(ancestor)
467
 
 
468
 
            # Check that there aren't any inventory level changes
469
 
            delta = new.changes_from(old)
470
 
            self.assertFalse(delta.has_changed(),
471
 
                             'Revision %s not copied correctly.'
472
 
                             % (ancestor,))
473
 
 
474
 
            # Now check that the file contents are all correct
475
 
            for inventory_id in old:
476
 
                try:
477
 
                    old_file = old.get_file(inventory_id)
478
 
                except NoSuchFile:
479
 
                    continue
480
 
                if old_file is None:
481
 
                    continue
482
 
                self.assertEqual(old_file.read(),
483
 
                                 new.get_file(inventory_id).read())
484
 
        if rev_id is not None:
485
 
            rh = self.b1.revision_history()
486
 
            tree.branch.set_revision_history(rh[:rh.index(rev_id)+1])
487
 
            tree.update()
488
 
            delta = tree.changes_from(self.b1.repository.revision_tree(rev_id))
489
 
            self.assertFalse(delta.has_changed(),
490
 
                             'Working tree has modifications: %s' % delta)
491
 
        return tree
492
 
 
493
 
    def valid_apply_bundle(self, base_rev_id, info, checkout_dir=None):
494
 
        """Get the base revision, apply the changes, and make
495
 
        sure everything matches the builtin branch.
496
 
        """
497
 
        to_tree = self.get_checkout(base_rev_id, checkout_dir=checkout_dir)
498
 
        original_parents = to_tree.get_parent_ids()
499
 
        repository = to_tree.branch.repository
500
 
        original_parents = to_tree.get_parent_ids()
501
 
        self.assertIs(repository.has_revision(base_rev_id), True)
502
 
        for rev in info.real_revisions:
503
 
            self.assert_(not repository.has_revision(rev.revision_id),
504
 
                'Revision {%s} present before applying bundle' 
505
 
                % rev.revision_id)
506
 
        merge_bundle(info, to_tree, True, Merge3Merger, False, False)
507
 
 
508
 
        for rev in info.real_revisions:
509
 
            self.assert_(repository.has_revision(rev.revision_id),
510
 
                'Missing revision {%s} after applying bundle' 
511
 
                % rev.revision_id)
512
 
 
513
 
        self.assert_(to_tree.branch.repository.has_revision(info.target))
514
 
        # Do we also want to verify that all the texts have been added?
515
 
 
516
 
        self.assertEqual(original_parents + [info.target],
517
 
            to_tree.get_parent_ids())
518
 
 
519
 
        rev = info.real_revisions[-1]
520
 
        base_tree = self.b1.repository.revision_tree(rev.revision_id)
521
 
        to_tree = to_tree.branch.repository.revision_tree(rev.revision_id)
522
 
        
523
 
        # TODO: make sure the target tree is identical to base tree
524
 
        #       we might also check the working tree.
525
 
 
526
 
        base_files = list(base_tree.list_files())
527
 
        to_files = list(to_tree.list_files())
528
 
        self.assertEqual(len(base_files), len(to_files))
529
 
        for base_file, to_file in zip(base_files, to_files):
530
 
            self.assertEqual(base_file, to_file)
531
 
 
532
 
        for path, status, kind, fileid, entry in base_files:
533
 
            # Check that the meta information is the same
534
 
            self.assertEqual(base_tree.get_file_size(fileid),
535
 
                    to_tree.get_file_size(fileid))
536
 
            self.assertEqual(base_tree.get_file_sha1(fileid),
537
 
                    to_tree.get_file_sha1(fileid))
538
 
            # Check that the contents are the same
539
 
            # This is pretty expensive
540
 
            # self.assertEqual(base_tree.get_file(fileid).read(),
541
 
            #         to_tree.get_file(fileid).read())
542
 
 
543
 
    def test_bundle(self):
544
 
        self.tree1 = self.make_branch_and_tree('b1')
545
 
        self.b1 = self.tree1.branch
546
 
 
547
 
        open('b1/one', 'wb').write('one\n')
548
 
        self.tree1.add('one')
549
 
        self.tree1.commit('add one', rev_id='a@cset-0-1')
550
 
 
551
 
        bundle = self.get_valid_bundle(None, 'a@cset-0-1')
552
 
        # FIXME: The current write_bundle api no longer supports
553
 
        #        setting a custom summary message
554
 
        #        We should re-introduce the ability, and update
555
 
        #        the tests to make sure it works.
556
 
        # bundle = self.get_valid_bundle(None, 'a@cset-0-1',
557
 
        #         message='With a specialized message')
558
 
 
559
 
        # Make sure we can handle files with spaces, tabs, other
560
 
        # bogus characters
561
 
        self.build_tree([
562
 
                'b1/with space.txt'
563
 
                , 'b1/dir/'
564
 
                , 'b1/dir/filein subdir.c'
565
 
                , 'b1/dir/WithCaps.txt'
566
 
                , 'b1/dir/ pre space'
567
 
                , 'b1/sub/'
568
 
                , 'b1/sub/sub/'
569
 
                , 'b1/sub/sub/nonempty.txt'
570
 
                ])
571
 
        open('b1/sub/sub/emptyfile.txt', 'wb').close()
572
 
        open('b1/dir/nolastnewline.txt', 'wb').write('bloop')
573
 
        tt = TreeTransform(self.tree1)
574
 
        tt.new_file('executable', tt.root, '#!/bin/sh\n', 'exe-1', True)
575
 
        tt.apply()
576
 
        self.tree1.add([
577
 
                'with space.txt'
578
 
                , 'dir'
579
 
                , 'dir/filein subdir.c'
580
 
                , 'dir/WithCaps.txt'
581
 
                , 'dir/ pre space'
582
 
                , 'dir/nolastnewline.txt'
583
 
                , 'sub'
584
 
                , 'sub/sub'
585
 
                , 'sub/sub/nonempty.txt'
586
 
                , 'sub/sub/emptyfile.txt'
587
 
                ])
588
 
        self.tree1.commit('add whitespace', rev_id='a@cset-0-2')
589
 
 
590
 
        bundle = self.get_valid_bundle('a@cset-0-1', 'a@cset-0-2')
591
 
 
592
 
        # Check a rollup bundle 
593
 
        bundle = self.get_valid_bundle(None, 'a@cset-0-2')
594
 
 
595
 
        # Now delete entries
596
 
        self.tree1.remove(
597
 
                ['sub/sub/nonempty.txt'
598
 
                , 'sub/sub/emptyfile.txt'
599
 
                , 'sub/sub'
600
 
                ])
601
 
        tt = TreeTransform(self.tree1)
602
 
        trans_id = tt.trans_id_tree_file_id('exe-1')
603
 
        tt.set_executability(False, trans_id)
604
 
        tt.apply()
605
 
        self.tree1.commit('removed', rev_id='a@cset-0-3')
606
 
        
607
 
        bundle = self.get_valid_bundle('a@cset-0-2', 'a@cset-0-3')
608
 
        self.assertRaises(TestamentMismatch, self.get_invalid_bundle, 
609
 
                          'a@cset-0-2', 'a@cset-0-3')
610
 
        # Check a rollup bundle 
611
 
        bundle = self.get_valid_bundle(None, 'a@cset-0-3')
612
 
 
613
 
        # Now move the directory
614
 
        self.tree1.rename_one('dir', 'sub/dir')
615
 
        self.tree1.commit('rename dir', rev_id='a@cset-0-4')
616
 
 
617
 
        bundle = self.get_valid_bundle('a@cset-0-3', 'a@cset-0-4')
618
 
        # Check a rollup bundle 
619
 
        bundle = self.get_valid_bundle(None, 'a@cset-0-4')
620
 
 
621
 
        # Modified files
622
 
        open('b1/sub/dir/WithCaps.txt', 'ab').write('\nAdding some text\n')
623
 
        open('b1/sub/dir/ pre space', 'ab').write('\r\nAdding some\r\nDOS format lines\r\n')
624
 
        open('b1/sub/dir/nolastnewline.txt', 'ab').write('\n')
625
 
        self.tree1.rename_one('sub/dir/ pre space', 
626
 
                              'sub/ start space')
627
 
        self.tree1.commit('Modified files', rev_id='a@cset-0-5')
628
 
        bundle = self.get_valid_bundle('a@cset-0-4', 'a@cset-0-5')
629
 
 
630
 
        self.tree1.rename_one('sub/dir/WithCaps.txt', 'temp')
631
 
        self.tree1.rename_one('with space.txt', 'WithCaps.txt')
632
 
        self.tree1.rename_one('temp', 'with space.txt')
633
 
        self.tree1.commit(u'swap filenames', rev_id='a@cset-0-6',
634
 
                          verbose=False)
635
 
        bundle = self.get_valid_bundle('a@cset-0-5', 'a@cset-0-6')
636
 
        other = self.get_checkout('a@cset-0-5')
637
 
        tree1_inv = self.tree1.branch.repository.get_inventory_xml(
638
 
            'a@cset-0-5')
639
 
        tree2_inv = other.branch.repository.get_inventory_xml('a@cset-0-5')
640
 
        self.assertEqualDiff(tree1_inv, tree2_inv)
641
 
        other.rename_one('sub/dir/nolastnewline.txt', 'sub/nolastnewline.txt')
642
 
        other.commit('rename file', rev_id='a@cset-0-6b')
643
 
        _merge_helper([other.basedir, -1], [None, None],
644
 
                      this_dir=self.tree1.basedir)
645
 
        self.tree1.commit(u'Merge', rev_id='a@cset-0-7',
646
 
                          verbose=False)
647
 
        bundle = self.get_valid_bundle('a@cset-0-6', 'a@cset-0-7')
648
 
 
649
 
    def test_symlink_bundle(self):
650
 
        if not has_symlinks():
651
 
            raise TestSkipped("No symlink support")
652
 
        self.tree1 = self.make_branch_and_tree('b1')
653
 
        self.b1 = self.tree1.branch
654
 
        tt = TreeTransform(self.tree1)
655
 
        tt.new_symlink('link', tt.root, 'bar/foo', 'link-1')
656
 
        tt.apply()
657
 
        self.tree1.commit('add symlink', rev_id='l@cset-0-1')
658
 
        self.get_valid_bundle(None, 'l@cset-0-1')
659
 
        tt = TreeTransform(self.tree1)
660
 
        trans_id = tt.trans_id_tree_file_id('link-1')
661
 
        tt.adjust_path('link2', tt.root, trans_id)
662
 
        tt.delete_contents(trans_id)
663
 
        tt.create_symlink('mars', trans_id)
664
 
        tt.apply()
665
 
        self.tree1.commit('rename and change symlink', rev_id='l@cset-0-2')
666
 
        self.get_valid_bundle('l@cset-0-1', 'l@cset-0-2')
667
 
        tt = TreeTransform(self.tree1)
668
 
        trans_id = tt.trans_id_tree_file_id('link-1')
669
 
        tt.delete_contents(trans_id)
670
 
        tt.create_symlink('jupiter', trans_id)
671
 
        tt.apply()
672
 
        self.tree1.commit('just change symlink target', rev_id='l@cset-0-3')
673
 
        self.get_valid_bundle('l@cset-0-2', 'l@cset-0-3')
674
 
        tt = TreeTransform(self.tree1)
675
 
        trans_id = tt.trans_id_tree_file_id('link-1')
676
 
        tt.delete_contents(trans_id)
677
 
        tt.apply()
678
 
        self.tree1.commit('Delete symlink', rev_id='l@cset-0-4')
679
 
        self.get_valid_bundle('l@cset-0-3', 'l@cset-0-4')
680
 
 
681
 
    def test_binary_bundle(self):
682
 
        self.tree1 = self.make_branch_and_tree('b1')
683
 
        self.b1 = self.tree1.branch
684
 
        tt = TreeTransform(self.tree1)
685
 
        
686
 
        # Add
687
 
        tt.new_file('file', tt.root, '\x00\n\x00\r\x01\n\x02\r\xff', 'binary-1')
688
 
        tt.new_file('file2', tt.root, '\x01\n\x02\r\x03\n\x04\r\xff', 'binary-2')
689
 
        tt.apply()
690
 
        self.tree1.commit('add binary', rev_id='b@cset-0-1')
691
 
        self.get_valid_bundle(None, 'b@cset-0-1')
692
 
 
693
 
        # Delete
694
 
        tt = TreeTransform(self.tree1)
695
 
        trans_id = tt.trans_id_tree_file_id('binary-1')
696
 
        tt.delete_contents(trans_id)
697
 
        tt.apply()
698
 
        self.tree1.commit('delete binary', rev_id='b@cset-0-2')
699
 
        self.get_valid_bundle('b@cset-0-1', 'b@cset-0-2')
700
 
 
701
 
        # Rename & modify
702
 
        tt = TreeTransform(self.tree1)
703
 
        trans_id = tt.trans_id_tree_file_id('binary-2')
704
 
        tt.adjust_path('file3', tt.root, trans_id)
705
 
        tt.delete_contents(trans_id)
706
 
        tt.create_file('file\rcontents\x00\n\x00', trans_id)
707
 
        tt.apply()
708
 
        self.tree1.commit('rename and modify binary', rev_id='b@cset-0-3')
709
 
        self.get_valid_bundle('b@cset-0-2', 'b@cset-0-3')
710
 
 
711
 
        # Modify
712
 
        tt = TreeTransform(self.tree1)
713
 
        trans_id = tt.trans_id_tree_file_id('binary-2')
714
 
        tt.delete_contents(trans_id)
715
 
        tt.create_file('\x00file\rcontents', trans_id)
716
 
        tt.apply()
717
 
        self.tree1.commit('just modify binary', rev_id='b@cset-0-4')
718
 
        self.get_valid_bundle('b@cset-0-3', 'b@cset-0-4')
719
 
 
720
 
        # Rollup
721
 
        self.get_valid_bundle(None, 'b@cset-0-4')
722
 
 
723
 
    def test_last_modified(self):
724
 
        self.tree1 = self.make_branch_and_tree('b1')
725
 
        self.b1 = self.tree1.branch
726
 
        tt = TreeTransform(self.tree1)
727
 
        tt.new_file('file', tt.root, 'file', 'file')
728
 
        tt.apply()
729
 
        self.tree1.commit('create file', rev_id='a@lmod-0-1')
730
 
 
731
 
        tt = TreeTransform(self.tree1)
732
 
        trans_id = tt.trans_id_tree_file_id('file')
733
 
        tt.delete_contents(trans_id)
734
 
        tt.create_file('file2', trans_id)
735
 
        tt.apply()
736
 
        self.tree1.commit('modify text', rev_id='a@lmod-0-2a')
737
 
 
738
 
        other = self.get_checkout('a@lmod-0-1')
739
 
        tt = TreeTransform(other)
740
 
        trans_id = tt.trans_id_tree_file_id('file')
741
 
        tt.delete_contents(trans_id)
742
 
        tt.create_file('file2', trans_id)
743
 
        tt.apply()
744
 
        other.commit('modify text in another tree', rev_id='a@lmod-0-2b')
745
 
        _merge_helper([other.basedir, -1], [None, None],
746
 
                      this_dir=self.tree1.basedir)
747
 
        self.tree1.commit(u'Merge', rev_id='a@lmod-0-3',
748
 
                          verbose=False)
749
 
        self.tree1.commit(u'Merge', rev_id='a@lmod-0-4')
750
 
        bundle = self.get_valid_bundle('a@lmod-0-2a', 'a@lmod-0-4')
751
 
 
752
 
    def test_hide_history(self):
753
 
        self.tree1 = self.make_branch_and_tree('b1')
754
 
        self.b1 = self.tree1.branch
755
 
 
756
 
        open('b1/one', 'wb').write('one\n')
757
 
        self.tree1.add('one')
758
 
        self.tree1.commit('add file', rev_id='a@cset-0-1')
759
 
        open('b1/one', 'wb').write('two\n')
760
 
        self.tree1.commit('modify', rev_id='a@cset-0-2')
761
 
        open('b1/one', 'wb').write('three\n')
762
 
        self.tree1.commit('modify', rev_id='a@cset-0-3')
763
 
        bundle_file = StringIO()
764
 
        rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-3',
765
 
                               'a@cset-0-1', bundle_file, format=self.format)
766
 
        self.assertNotContainsRe(bundle_file.getvalue(), '\btwo\b')
767
 
        self.assertContainsRe(self.get_raw(bundle_file), 'one')
768
 
        self.assertContainsRe(self.get_raw(bundle_file), 'three')
769
 
 
770
 
    @staticmethod
771
 
    def get_raw(bundle_file):
772
 
        return bundle_file.getvalue()
773
 
 
774
 
    def test_unicode_bundle(self):
775
 
        # Handle international characters
776
 
        os.mkdir('b1')
777
 
        try:
778
 
            f = open(u'b1/with Dod\xe9', 'wb')
779
 
        except UnicodeEncodeError:
780
 
            raise TestSkipped("Filesystem doesn't support unicode")
781
 
 
782
 
        self.tree1 = self.make_branch_and_tree('b1')
783
 
        self.b1 = self.tree1.branch
784
 
 
785
 
        f.write((u'A file\n'
786
 
            u'With international man of mystery\n'
787
 
            u'William Dod\xe9\n').encode('utf-8'))
788
 
        f.close()
789
 
 
790
 
        self.tree1.add([u'with Dod\xe9'], ['withdod-id'])
791
 
        self.tree1.commit(u'i18n commit from William Dod\xe9',
792
 
                          rev_id='i18n-1', committer=u'William Dod\xe9')
793
 
 
794
 
        if sys.platform == 'darwin':
795
 
            # On Mac the '\xe9' gets changed to 'e\u0301'
796
 
            self.assertEqual([u'.bzr', u'with Dode\u0301'],
797
 
                             sorted(os.listdir(u'b1')))
798
 
            delta = self.tree1.changes_from(self.tree1.basis_tree())
799
 
            self.assertEqual([(u'with Dod\xe9', 'withdod-id', 'file')],
800
 
                             delta.removed)
801
 
            self.knownFailure("Mac OSX doesn't preserve unicode"
802
 
                              " combining characters.")
803
 
 
804
 
        # Add
805
 
        bundle = self.get_valid_bundle(None, 'i18n-1')
806
 
 
807
 
        # Modified
808
 
        f = open(u'b1/with Dod\xe9', 'wb')
809
 
        f.write(u'Modified \xb5\n'.encode('utf8'))
810
 
        f.close()
811
 
        self.tree1.commit(u'modified', rev_id='i18n-2')
812
 
 
813
 
        bundle = self.get_valid_bundle('i18n-1', 'i18n-2')
814
 
        
815
 
        # Renamed
816
 
        self.tree1.rename_one(u'with Dod\xe9', u'B\xe5gfors')
817
 
        self.tree1.commit(u'renamed, the new i18n man', rev_id='i18n-3',
818
 
                          committer=u'Erik B\xe5gfors')
819
 
 
820
 
        bundle = self.get_valid_bundle('i18n-2', 'i18n-3')
821
 
 
822
 
        # Removed
823
 
        self.tree1.remove([u'B\xe5gfors'])
824
 
        self.tree1.commit(u'removed', rev_id='i18n-4')
825
 
 
826
 
        bundle = self.get_valid_bundle('i18n-3', 'i18n-4')
827
 
 
828
 
        # Rollup
829
 
        bundle = self.get_valid_bundle(None, 'i18n-4')
830
 
 
831
 
 
832
 
    def test_whitespace_bundle(self):
833
 
        if sys.platform in ('win32', 'cygwin'):
834
 
            raise TestSkipped('Windows doesn\'t support filenames'
835
 
                              ' with tabs or trailing spaces')
836
 
        self.tree1 = self.make_branch_and_tree('b1')
837
 
        self.b1 = self.tree1.branch
838
 
 
839
 
        self.build_tree(['b1/trailing space '])
840
 
        self.tree1.add(['trailing space '])
841
 
        # TODO: jam 20060701 Check for handling files with '\t' characters
842
 
        #       once we actually support them
843
 
 
844
 
        # Added
845
 
        self.tree1.commit('funky whitespace', rev_id='white-1')
846
 
 
847
 
        bundle = self.get_valid_bundle(None, 'white-1')
848
 
 
849
 
        # Modified
850
 
        open('b1/trailing space ', 'ab').write('add some text\n')
851
 
        self.tree1.commit('add text', rev_id='white-2')
852
 
 
853
 
        bundle = self.get_valid_bundle('white-1', 'white-2')
854
 
 
855
 
        # Renamed
856
 
        self.tree1.rename_one('trailing space ', ' start and end space ')
857
 
        self.tree1.commit('rename', rev_id='white-3')
858
 
 
859
 
        bundle = self.get_valid_bundle('white-2', 'white-3')
860
 
 
861
 
        # Removed
862
 
        self.tree1.remove([' start and end space '])
863
 
        self.tree1.commit('removed', rev_id='white-4')
864
 
 
865
 
        bundle = self.get_valid_bundle('white-3', 'white-4')
866
 
        
867
 
        # Now test a complet roll-up
868
 
        bundle = self.get_valid_bundle(None, 'white-4')
869
 
 
870
 
    def test_alt_timezone_bundle(self):
871
 
        self.tree1 = self.make_branch_and_memory_tree('b1')
872
 
        self.b1 = self.tree1.branch
873
 
        builder = treebuilder.TreeBuilder()
874
 
 
875
 
        self.tree1.lock_write()
876
 
        builder.start_tree(self.tree1)
877
 
        builder.build(['newfile'])
878
 
        builder.finish_tree()
879
 
 
880
 
        # Asia/Colombo offset = 5 hours 30 minutes
881
 
        self.tree1.commit('non-hour offset timezone', rev_id='tz-1',
882
 
                          timezone=19800, timestamp=1152544886.0)
883
 
 
884
 
        bundle = self.get_valid_bundle(None, 'tz-1')
885
 
        
886
 
        rev = bundle.revisions[0]
887
 
        self.assertEqual('Mon 2006-07-10 20:51:26.000000000 +0530', rev.date)
888
 
        self.assertEqual(19800, rev.timezone)
889
 
        self.assertEqual(1152544886.0, rev.timestamp)
890
 
        self.tree1.unlock()
891
 
 
892
 
    def test_bundle_root_id(self):
893
 
        self.tree1 = self.make_branch_and_tree('b1')
894
 
        self.b1 = self.tree1.branch
895
 
        self.tree1.commit('message', rev_id='revid1')
896
 
        bundle = self.get_valid_bundle(None, 'revid1')
897
 
        tree = bundle.revision_tree(self.b1.repository, 'revid1')
898
 
        self.assertEqual('revid1', tree.inventory.root.revision)
899
 
 
900
 
    def test_install_revisions(self):
901
 
        self.tree1 = self.make_branch_and_tree('b1')
902
 
        self.b1 = self.tree1.branch
903
 
        self.tree1.commit('message', rev_id='rev2a')
904
 
        bundle = self.get_valid_bundle(None, 'rev2a')
905
 
        branch2 = self.make_branch('b2')
906
 
        self.assertFalse(branch2.repository.has_revision('rev2a'))
907
 
        target_revision = bundle.install_revisions(branch2.repository)
908
 
        self.assertTrue(branch2.repository.has_revision('rev2a'))
909
 
        self.assertEqual('rev2a', target_revision)
910
 
 
911
 
    def test_bundle_empty_property(self):
912
 
        """Test serializing revision properties with an empty value."""
913
 
        tree = self.make_branch_and_memory_tree('tree')
914
 
        tree.lock_write()
915
 
        self.addCleanup(tree.unlock)
916
 
        tree.add([''], ['TREE_ROOT'])
917
 
        tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
918
 
        self.b1 = tree.branch
919
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
920
 
        bundle = read_bundle(bundle_sio)
921
 
        revision_info = bundle.revisions[0]
922
 
        self.assertEqual('rev1', revision_info.revision_id)
923
 
        rev = revision_info.as_revision()
924
 
        self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
925
 
                         rev.properties)
926
 
 
927
 
    def test_bundle_sorted_properties(self):
928
 
        """For stability the writer should write properties in sorted order."""
929
 
        tree = self.make_branch_and_memory_tree('tree')
930
 
        tree.lock_write()
931
 
        self.addCleanup(tree.unlock)
932
 
 
933
 
        tree.add([''], ['TREE_ROOT'])
934
 
        tree.commit('One', rev_id='rev1',
935
 
                    revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
936
 
        self.b1 = tree.branch
937
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
938
 
        bundle = read_bundle(bundle_sio)
939
 
        revision_info = bundle.revisions[0]
940
 
        self.assertEqual('rev1', revision_info.revision_id)
941
 
        rev = revision_info.as_revision()
942
 
        self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
943
 
                          'd':'1'}, rev.properties)
944
 
 
945
 
    def test_bundle_unicode_properties(self):
946
 
        """We should be able to round trip a non-ascii property."""
947
 
        tree = self.make_branch_and_memory_tree('tree')
948
 
        tree.lock_write()
949
 
        self.addCleanup(tree.unlock)
950
 
 
951
 
        tree.add([''], ['TREE_ROOT'])
952
 
        # Revisions themselves do not require anything about revision property
953
 
        # keys, other than that they are a basestring, and do not contain
954
 
        # whitespace.
955
 
        # However, Testaments assert than they are str(), and thus should not
956
 
        # be Unicode.
957
 
        tree.commit('One', rev_id='rev1',
958
 
                    revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
959
 
        self.b1 = tree.branch
960
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
961
 
        bundle = read_bundle(bundle_sio)
962
 
        revision_info = bundle.revisions[0]
963
 
        self.assertEqual('rev1', revision_info.revision_id)
964
 
        rev = revision_info.as_revision()
965
 
        self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
966
 
                          'alpha':u'\u03b1'}, rev.properties)
967
 
 
968
 
    def test_bundle_with_ghosts(self):
969
 
        tree = self.make_branch_and_tree('tree')
970
 
        self.b1 = tree.branch
971
 
        self.build_tree_contents([('tree/file', 'content1')])
972
 
        tree.add(['file'])
973
 
        tree.commit('rev1')
974
 
        self.build_tree_contents([('tree/file', 'content2')])
975
 
        tree.add_parent_tree_id('ghost')
976
 
        tree.commit('rev2', rev_id='rev2')
977
 
        bundle = self.get_valid_bundle(None, 'rev2')
978
 
 
979
 
 
980
 
class V08BundleTester(BundleTester, TestCaseWithTransport):
981
 
 
982
 
    format = '0.8'
983
 
 
984
 
    def test_bundle_empty_property(self):
985
 
        """Test serializing revision properties with an empty value."""
986
 
        tree = self.make_branch_and_memory_tree('tree')
987
 
        tree.lock_write()
988
 
        self.addCleanup(tree.unlock)
989
 
        tree.add([''], ['TREE_ROOT'])
990
 
        tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
991
 
        self.b1 = tree.branch
992
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
993
 
        self.assertContainsRe(bundle_sio.getvalue(),
994
 
                              '# properties:\n'
995
 
                              '#   branch-nick: tree\n'
996
 
                              '#   empty: \n'
997
 
                              '#   one: two\n'
998
 
                             )
999
 
        bundle = read_bundle(bundle_sio)
1000
 
        revision_info = bundle.revisions[0]
1001
 
        self.assertEqual('rev1', revision_info.revision_id)
1002
 
        rev = revision_info.as_revision()
1003
 
        self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1004
 
                         rev.properties)
1005
 
 
1006
 
    def test_bundle_empty_property_alt(self):
1007
 
        """Test serializing revision properties with an empty value.
1008
 
 
1009
 
        Older readers had a bug when reading an empty property.
1010
 
        They assumed that all keys ended in ': \n'. However they would write an
1011
 
        empty value as ':\n'. This tests make sure that all newer bzr versions
1012
 
        can handle th second form.
1013
 
        """
1014
 
        tree = self.make_branch_and_memory_tree('tree')
1015
 
        tree.lock_write()
1016
 
        self.addCleanup(tree.unlock)
1017
 
        tree.add([''], ['TREE_ROOT'])
1018
 
        tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1019
 
        self.b1 = tree.branch
1020
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
1021
 
        txt = bundle_sio.getvalue()
1022
 
        loc = txt.find('#   empty: ') + len('#   empty:')
1023
 
        # Create a new bundle, which strips the trailing space after empty
1024
 
        bundle_sio = StringIO(txt[:loc] + txt[loc+1:])
1025
 
 
1026
 
        self.assertContainsRe(bundle_sio.getvalue(),
1027
 
                              '# properties:\n'
1028
 
                              '#   branch-nick: tree\n'
1029
 
                              '#   empty:\n'
1030
 
                              '#   one: two\n'
1031
 
                             )
1032
 
        bundle = read_bundle(bundle_sio)
1033
 
        revision_info = bundle.revisions[0]
1034
 
        self.assertEqual('rev1', revision_info.revision_id)
1035
 
        rev = revision_info.as_revision()
1036
 
        self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1037
 
                         rev.properties)
1038
 
 
1039
 
    def test_bundle_sorted_properties(self):
1040
 
        """For stability the writer should write properties in sorted order."""
1041
 
        tree = self.make_branch_and_memory_tree('tree')
1042
 
        tree.lock_write()
1043
 
        self.addCleanup(tree.unlock)
1044
 
 
1045
 
        tree.add([''], ['TREE_ROOT'])
1046
 
        tree.commit('One', rev_id='rev1',
1047
 
                    revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1048
 
        self.b1 = tree.branch
1049
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
1050
 
        self.assertContainsRe(bundle_sio.getvalue(),
1051
 
                              '# properties:\n'
1052
 
                              '#   a: 4\n'
1053
 
                              '#   b: 3\n'
1054
 
                              '#   branch-nick: tree\n'
1055
 
                              '#   c: 2\n'
1056
 
                              '#   d: 1\n'
1057
 
                             )
1058
 
        bundle = read_bundle(bundle_sio)
1059
 
        revision_info = bundle.revisions[0]
1060
 
        self.assertEqual('rev1', revision_info.revision_id)
1061
 
        rev = revision_info.as_revision()
1062
 
        self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1063
 
                          'd':'1'}, rev.properties)
1064
 
 
1065
 
    def test_bundle_unicode_properties(self):
1066
 
        """We should be able to round trip a non-ascii property."""
1067
 
        tree = self.make_branch_and_memory_tree('tree')
1068
 
        tree.lock_write()
1069
 
        self.addCleanup(tree.unlock)
1070
 
 
1071
 
        tree.add([''], ['TREE_ROOT'])
1072
 
        # Revisions themselves do not require anything about revision property
1073
 
        # keys, other than that they are a basestring, and do not contain
1074
 
        # whitespace.
1075
 
        # However, Testaments assert than they are str(), and thus should not
1076
 
        # be Unicode.
1077
 
        tree.commit('One', rev_id='rev1',
1078
 
                    revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1079
 
        self.b1 = tree.branch
1080
 
        bundle_sio, revision_ids = self.create_bundle_text(None, 'rev1')
1081
 
        self.assertContainsRe(bundle_sio.getvalue(),
1082
 
                              '# properties:\n'
1083
 
                              '#   alpha: \xce\xb1\n'
1084
 
                              '#   branch-nick: tree\n'
1085
 
                              '#   omega: \xce\xa9\n'
1086
 
                             )
1087
 
        bundle = read_bundle(bundle_sio)
1088
 
        revision_info = bundle.revisions[0]
1089
 
        self.assertEqual('rev1', revision_info.revision_id)
1090
 
        rev = revision_info.as_revision()
1091
 
        self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1092
 
                          'alpha':u'\u03b1'}, rev.properties)
1093
 
 
1094
 
 
1095
 
class V09BundleKnit2Tester(V08BundleTester):
1096
 
 
1097
 
    format = '0.9'
1098
 
 
1099
 
    def bzrdir_format(self):
1100
 
        format = bzrdir.BzrDirMetaFormat1()
1101
 
        format.repository_format = knitrepo.RepositoryFormatKnit3()
1102
 
        return format
1103
 
 
1104
 
 
1105
 
class V09BundleKnit1Tester(V08BundleTester):
1106
 
 
1107
 
    format = '0.9'
1108
 
 
1109
 
    def bzrdir_format(self):
1110
 
        format = bzrdir.BzrDirMetaFormat1()
1111
 
        format.repository_format = knitrepo.RepositoryFormatKnit1()
1112
 
        return format
1113
 
 
1114
 
 
1115
 
class V10BundleTester(BundleTester, TestCaseWithTransport):
1116
 
 
1117
 
    format = '1.0alpha'
1118
 
 
1119
 
    def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
1120
 
        """Create a bundle from base_rev_id -> rev_id in built-in branch.
1121
 
        Make sure that the text generated is valid, and that it
1122
 
        can be applied against the base, and generate the same information.
1123
 
        
1124
 
        :return: The in-memory bundle 
1125
 
        """
1126
 
        bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1127
 
 
1128
 
        # This should also validate the generated bundle 
1129
 
        bundle = read_bundle(bundle_txt)
1130
 
        repository = self.b1.repository
1131
 
        for bundle_rev in bundle.real_revisions:
1132
 
            # These really should have already been checked when we read the
1133
 
            # bundle, since it computes the sha1 hash for the revision, which
1134
 
            # only will match if everything is okay, but lets be explicit about
1135
 
            # it
1136
 
            branch_rev = repository.get_revision(bundle_rev.revision_id)
1137
 
            for a in ('inventory_sha1', 'revision_id', 'parent_ids',
1138
 
                      'timestamp', 'timezone', 'message', 'committer', 
1139
 
                      'parent_ids', 'properties'):
1140
 
                self.assertEqual(getattr(branch_rev, a), 
1141
 
                                 getattr(bundle_rev, a))
1142
 
            self.assertEqual(len(branch_rev.parent_ids), 
1143
 
                             len(bundle_rev.parent_ids))
1144
 
        self.assertEqual(set(rev_ids),
1145
 
                         set([r.revision_id for r in bundle.real_revisions]))
1146
 
        self.valid_apply_bundle(base_rev_id, bundle,
1147
 
                                   checkout_dir=checkout_dir)
1148
 
 
1149
 
        return bundle
1150
 
 
1151
 
    def get_invalid_bundle(self, base_rev_id, rev_id):
1152
 
        """Create a bundle from base_rev_id -> rev_id in built-in branch.
1153
 
        Munge the text so that it's invalid.
1154
 
 
1155
 
        :return: The in-memory bundle
1156
 
        """
1157
 
        from bzrlib.bundle import serializer
1158
 
        bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1159
 
        new_text = self.get_raw(StringIO(''.join(bundle_txt)))
1160
 
        new_text = new_text.replace('<file file_id="exe-1"',
1161
 
                                    '<file executable="y" file_id="exe-1"')
1162
 
        new_text = new_text.replace('B418', 'B433')
1163
 
        bundle_txt = StringIO()
1164
 
        bundle_txt.write(serializer._get_bundle_header('1.0alpha'))
1165
 
        bundle_txt.write('\n')
1166
 
        bundle_txt.write(new_text.encode('bz2').encode('base-64'))
1167
 
        bundle_txt.seek(0)
1168
 
        bundle = read_bundle(bundle_txt)
1169
 
        self.valid_apply_bundle(base_rev_id, bundle)
1170
 
        return bundle
1171
 
 
1172
 
    def create_bundle_text(self, base_rev_id, rev_id):
1173
 
        bundle_txt = StringIO()
1174
 
        rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id, 
1175
 
                               bundle_txt, format=self.format)
1176
 
        bundle_txt.seek(0)
1177
 
        self.assertEqual(bundle_txt.readline(), 
1178
 
                         '# Bazaar revision bundle v%s\n' % self.format)
1179
 
        self.assertEqual(bundle_txt.readline(), '#\n')
1180
 
 
1181
 
        rev = self.b1.repository.get_revision(rev_id)
1182
 
 
1183
 
        open(',,bundle', 'wb').write(bundle_txt.getvalue())
1184
 
        bundle_txt.seek(0)
1185
 
        return bundle_txt, rev_ids
1186
 
 
1187
 
    def test_creation(self):
1188
 
        tree = self.make_branch_and_tree('tree')
1189
 
        self.build_tree_contents([('tree/file', 'contents1\nstatic\n')])
1190
 
        tree.add('file', 'fileid-2')
1191
 
        tree.commit('added file', rev_id='rev1')
1192
 
        self.build_tree_contents([('tree/file', 'contents2\nstatic\n')])
1193
 
        tree.commit('changed file', rev_id='rev2')
1194
 
        s = StringIO()
1195
 
        serializer = BundleSerializerV10('1.0')
1196
 
        serializer.write(tree.branch.repository, ['rev1', 'rev2'], {}, s)
1197
 
        s.seek(0)
1198
 
        tree2 = self.make_branch_and_tree('target')
1199
 
        target_repo = tree2.branch.repository
1200
 
        install_bundle(target_repo, serializer.read(s))
1201
 
        vf = target_repo.weave_store.get_weave('fileid-2',
1202
 
            target_repo.get_transaction())
1203
 
        self.assertEqual('contents1\nstatic\n', vf.get_text('rev1'))
1204
 
        self.assertEqual('contents2\nstatic\n', vf.get_text('rev2'))
1205
 
        rtree = target_repo.revision_tree('rev2')
1206
 
        inventory_vf = target_repo.get_inventory_weave()
1207
 
        self.assertEqual(['rev1'], inventory_vf.get_parents('rev2'))
1208
 
        self.assertEqual('changed file',
1209
 
                         target_repo.get_revision('rev2').message)
1210
 
 
1211
 
    def test_name_encode(self):
1212
 
        self.assertEqual('revision:rev1',
1213
 
            v10.BundleWriter.encode_name('revision', 'rev1'))
1214
 
        self.assertEqual('file:rev1/file-id-1',
1215
 
            v10.BundleWriter.encode_name('file', 'rev1', 'file-id-1'))
1216
 
 
1217
 
    def test_name_decode(self):
1218
 
        self.assertEqual(('revision', 'rev1', None),
1219
 
            v10.BundleReader.decode_name('revision:rev1'))
1220
 
        self.assertEqual(('file', 'rev1', 'file-id-1'),
1221
 
            v10.BundleReader.decode_name('file:rev1/file-id-1'))
1222
 
 
1223
 
    @staticmethod
1224
 
    def get_raw(bundle_file):
1225
 
        bundle_file.seek(0)
1226
 
        while True:
1227
 
            line = bundle_file.readline()
1228
 
            assert '' != line
1229
 
            if line.rstrip('\n') == '# End of patch':
1230
 
                break
1231
 
        lines = bundle_file.readlines()
1232
 
        return ''.join(lines).decode('base-64').decode('bz2')
1233
 
 
1234
 
    def test_copy_signatures(self):
1235
 
        tree_a = self.make_branch_and_tree('tree_a')
1236
 
        import bzrlib.gpg
1237
 
        import bzrlib.commit as commit
1238
 
        oldstrategy = bzrlib.gpg.GPGStrategy
1239
 
        branch = tree_a.branch
1240
 
        repo_a = branch.repository
1241
 
        tree_a.commit("base", allow_pointless=True, rev_id='A')
1242
 
        self.failIf(branch.repository.has_signature_for_revision_id('A'))
1243
 
        try:
1244
 
            from bzrlib.testament import Testament
1245
 
            # monkey patch gpg signing mechanism
1246
 
            bzrlib.gpg.GPGStrategy = bzrlib.gpg.LoopbackGPGStrategy
1247
 
            new_config = test_commit.MustSignConfig(branch)
1248
 
            commit.Commit(config=new_config).commit(message="base",
1249
 
                                                    allow_pointless=True,
1250
 
                                                    rev_id='B',
1251
 
                                                    working_tree=tree_a)
1252
 
            def sign(text):
1253
 
                return bzrlib.gpg.LoopbackGPGStrategy(None).sign(text)
1254
 
            self.assertTrue(repo_a.has_signature_for_revision_id('B'))
1255
 
        finally:
1256
 
            bzrlib.gpg.GPGStrategy = oldstrategy
1257
 
        tree_b = self.make_branch_and_tree('tree_b')
1258
 
        repo_b = tree_b.branch.repository
1259
 
        s = StringIO()
1260
 
        serializer = BundleSerializerV10('1.0')
1261
 
        serializer.write(tree_a.branch.repository, ['A', 'B'], {}, s)
1262
 
        s.seek(0)
1263
 
        install_bundle(repo_b, serializer.read(s))
1264
 
        self.assertTrue(repo_b.has_signature_for_revision_id('B'))
1265
 
        self.assertEqual(repo_b.get_signature_text('B'),
1266
 
                         repo_a.get_signature_text('B'))
1267
 
 
1268
 
    def test_has_diff(self):
1269
 
        tree = self.make_branch_and_tree('tree')
1270
 
        self.build_tree_contents([('tree/file', 'File content 1')])
1271
 
        tree.add('file')
1272
 
        tree.commit('added file', rev_id='rev1')
1273
 
        s = StringIO()
1274
 
        serializer = BundleSerializerV10('1.0')
1275
 
        serializer.write(tree.branch.repository, ['rev1'], {}, s)
1276
 
        self.assertContainsRe(s.getvalue(), '\+File content 1')
1277
 
 
1278
 
    def test_write_patch(self):
1279
 
        s = StringIO()
1280
 
        writer = v10.BundleWriter(s)
1281
 
        writer.begin()
1282
 
        writer.write_patch('My patch\n')
1283
 
        writer.end()
1284
 
        self.assertContainsRe(s.getvalue(),
1285
 
            '# Bazaar revision bundle v1.0alpha\n'
1286
 
            '#\nMy patch\n'
1287
 
            '# End of patch\n')
1288
 
 
1289
 
 
1290
 
class MungedBundleTester(TestCaseWithTransport):
1291
 
 
1292
 
    def build_test_bundle(self):
1293
 
        wt = self.make_branch_and_tree('b1')
1294
 
 
1295
 
        self.build_tree(['b1/one'])
1296
 
        wt.add('one')
1297
 
        wt.commit('add one', rev_id='a@cset-0-1')
1298
 
        self.build_tree(['b1/two'])
1299
 
        wt.add('two')
1300
 
        wt.commit('add two', rev_id='a@cset-0-2',
1301
 
                  revprops={'branch-nick':'test'})
1302
 
 
1303
 
        bundle_txt = StringIO()
1304
 
        rev_ids = write_bundle(wt.branch.repository, 'a@cset-0-2',
1305
 
                               'a@cset-0-1', bundle_txt)
1306
 
        self.assertEqual(['a@cset-0-2'], rev_ids)
1307
 
        bundle_txt.seek(0, 0)
1308
 
        return bundle_txt
1309
 
 
1310
 
    def check_valid(self, bundle):
1311
 
        """Check that after whatever munging, the final object is valid."""
1312
 
        self.assertEqual(['a@cset-0-2'],
1313
 
            [r.revision_id for r in bundle.real_revisions])
1314
 
 
1315
 
    def test_extra_whitespace(self):
1316
 
        bundle_txt = self.build_test_bundle()
1317
 
 
1318
 
        # Seek to the end of the file
1319
 
        # Adding one extra newline used to give us
1320
 
        # TypeError: float() argument must be a string or a number
1321
 
        bundle_txt.seek(0, 2)
1322
 
        bundle_txt.write('\n')
1323
 
        bundle_txt.seek(0)
1324
 
 
1325
 
        bundle = read_bundle(bundle_txt)
1326
 
        self.check_valid(bundle)
1327
 
 
1328
 
    def test_extra_whitespace_2(self):
1329
 
        bundle_txt = self.build_test_bundle()
1330
 
 
1331
 
        # Seek to the end of the file
1332
 
        # Adding two extra newlines used to give us
1333
 
        # MalformedPatches: The first line of all patches should be ...
1334
 
        bundle_txt.seek(0, 2)
1335
 
        bundle_txt.write('\n\n')
1336
 
        bundle_txt.seek(0)
1337
 
 
1338
 
        bundle = read_bundle(bundle_txt)
1339
 
        self.check_valid(bundle)
1340
 
 
1341
 
    def test_missing_trailing_whitespace(self):
1342
 
        bundle_txt = self.build_test_bundle()
1343
 
 
1344
 
        # Remove a trailing newline, it shouldn't kill the parser
1345
 
        raw = bundle_txt.getvalue()
1346
 
        # The contents of the bundle don't have to be this, but this
1347
 
        # test is concerned with the exact case where the serializer
1348
 
        # creates a blank line at the end, and fails if that
1349
 
        # line is stripped
1350
 
        self.assertEqual('\n\n', raw[-2:])
1351
 
        bundle_txt = StringIO(raw[:-1])
1352
 
 
1353
 
        bundle = read_bundle(bundle_txt)
1354
 
        self.check_valid(bundle)
1355
 
 
1356
 
    def test_opening_text(self):
1357
 
        bundle_txt = self.build_test_bundle()
1358
 
 
1359
 
        bundle_txt = StringIO("Some random\nemail comments\n"
1360
 
                              + bundle_txt.getvalue())
1361
 
 
1362
 
        bundle = read_bundle(bundle_txt)
1363
 
        self.check_valid(bundle)
1364
 
 
1365
 
    def test_trailing_text(self):
1366
 
        bundle_txt = self.build_test_bundle()
1367
 
 
1368
 
        bundle_txt = StringIO(bundle_txt.getvalue() +
1369
 
                              "Some trailing\nrandom\ntext\n")
1370
 
 
1371
 
        bundle = read_bundle(bundle_txt)
1372
 
        self.check_valid(bundle)
1373
 
 
1374
 
 
1375
 
class TestBundleWriterReader(TestCase):
1376
 
 
1377
 
    def test_roundtrip_record(self):
1378
 
        fileobj = StringIO()
1379
 
        writer = v10.BundleWriter(fileobj)
1380
 
        writer.begin()
1381
 
        writer.write_patch("Hi there!\n")
1382
 
        writer._add_record("Record body", {'parents': ['1', '3']},
1383
 
                           'file', 'revid', 'fileid')
1384
 
        writer.end()
1385
 
        fileobj.seek(0)
1386
 
        reader = v10.BundleReader(fileobj)
1387
 
        record = reader.iter_records().next()
1388
 
        self.assertEqual(("Record body", {'parents': ['1', '3']}, 'file',
1389
 
                          'revid', 'fileid'), record)