1
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
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.
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.
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
17
from cStringIO import StringIO
27
revision as _mod_revision,
30
from bzrlib.bzrdir import BzrDir
31
from bzrlib.bundle import read_mergeable_from_url
32
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
33
from bzrlib.bundle.bundle_data import BundleTree
34
from bzrlib.directory_service import directories
35
from bzrlib.bundle.serializer import write_bundle, read_bundle, v09, v4
36
from bzrlib.bundle.serializer.v08 import BundleSerializerV08
37
from bzrlib.bundle.serializer.v09 import BundleSerializerV09
38
from bzrlib.bundle.serializer.v4 import BundleSerializerV4
39
from bzrlib.branch import Branch
40
from bzrlib.diff import internal_diff
41
from bzrlib.merge import Merge3Merger
42
from bzrlib.repofmt import knitrepo
43
from bzrlib.osutils import sha_file, sha_string
44
from bzrlib.tests import (
48
TestCaseWithTransport,
53
from bzrlib.transform import TreeTransform
56
class MockTree(object):
58
from bzrlib.inventory import InventoryDirectory, ROOT_ID
60
self.paths = {ROOT_ID: ""}
61
self.ids = {"": ROOT_ID}
63
self.root = InventoryDirectory(ROOT_ID, '', None)
65
inventory = property(lambda x:x)
68
return self.paths.iterkeys()
70
def __getitem__(self, file_id):
71
if file_id == self.root.file_id:
74
return self.make_entry(file_id, self.paths[file_id])
76
def parent_id(self, file_id):
77
parent_dir = os.path.dirname(self.paths[file_id])
80
return self.ids[parent_dir]
82
def iter_entries(self):
83
for path, file_id in self.ids.iteritems():
84
yield path, self[file_id]
86
def get_file_kind(self, file_id):
87
if file_id in self.contents:
93
def make_entry(self, file_id, path):
94
from bzrlib.inventory import (InventoryEntry, InventoryFile
95
, InventoryDirectory, InventoryLink)
96
name = os.path.basename(path)
97
kind = self.get_file_kind(file_id)
98
parent_id = self.parent_id(file_id)
99
text_sha_1, text_size = self.contents_stats(file_id)
100
if kind == 'directory':
101
ie = InventoryDirectory(file_id, name, parent_id)
103
ie = InventoryFile(file_id, name, parent_id)
104
elif kind == 'symlink':
105
ie = InventoryLink(file_id, name, parent_id)
107
raise errors.BzrError('unknown kind %r' % kind)
108
ie.text_sha1 = text_sha_1
109
ie.text_size = text_size
112
def add_dir(self, file_id, path):
113
self.paths[file_id] = path
114
self.ids[path] = file_id
116
def add_file(self, file_id, path, contents):
117
self.add_dir(file_id, path)
118
self.contents[file_id] = contents
120
def path2id(self, path):
121
return self.ids.get(path)
123
def id2path(self, file_id):
124
return self.paths.get(file_id)
126
def has_id(self, file_id):
127
return self.id2path(file_id) is not None
129
def get_file(self, file_id):
131
result.write(self.contents[file_id])
135
def contents_stats(self, file_id):
136
if file_id not in self.contents:
138
text_sha1 = sha_file(self.get_file(file_id))
139
return text_sha1, len(self.contents[file_id])
142
class BTreeTester(TestCase):
143
"""A simple unittest tester for the BundleTree class."""
145
def make_tree_1(self):
147
mtree.add_dir("a", "grandparent")
148
mtree.add_dir("b", "grandparent/parent")
149
mtree.add_file("c", "grandparent/parent/file", "Hello\n")
150
mtree.add_dir("d", "grandparent/alt_parent")
151
return BundleTree(mtree, ''), mtree
153
def test_renames(self):
154
"""Ensure that file renames have the proper effect on children"""
155
btree = self.make_tree_1()[0]
156
self.assertEqual(btree.old_path("grandparent"), "grandparent")
157
self.assertEqual(btree.old_path("grandparent/parent"),
158
"grandparent/parent")
159
self.assertEqual(btree.old_path("grandparent/parent/file"),
160
"grandparent/parent/file")
162
self.assertEqual(btree.id2path("a"), "grandparent")
163
self.assertEqual(btree.id2path("b"), "grandparent/parent")
164
self.assertEqual(btree.id2path("c"), "grandparent/parent/file")
166
self.assertEqual(btree.path2id("grandparent"), "a")
167
self.assertEqual(btree.path2id("grandparent/parent"), "b")
168
self.assertEqual(btree.path2id("grandparent/parent/file"), "c")
170
self.assertTrue(btree.path2id("grandparent2") is None)
171
self.assertTrue(btree.path2id("grandparent2/parent") is None)
172
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
174
btree.note_rename("grandparent", "grandparent2")
175
self.assertTrue(btree.old_path("grandparent") is None)
176
self.assertTrue(btree.old_path("grandparent/parent") is None)
177
self.assertTrue(btree.old_path("grandparent/parent/file") is None)
179
self.assertEqual(btree.id2path("a"), "grandparent2")
180
self.assertEqual(btree.id2path("b"), "grandparent2/parent")
181
self.assertEqual(btree.id2path("c"), "grandparent2/parent/file")
183
self.assertEqual(btree.path2id("grandparent2"), "a")
184
self.assertEqual(btree.path2id("grandparent2/parent"), "b")
185
self.assertEqual(btree.path2id("grandparent2/parent/file"), "c")
187
self.assertTrue(btree.path2id("grandparent") is None)
188
self.assertTrue(btree.path2id("grandparent/parent") is None)
189
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
191
btree.note_rename("grandparent/parent", "grandparent2/parent2")
192
self.assertEqual(btree.id2path("a"), "grandparent2")
193
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
194
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file")
196
self.assertEqual(btree.path2id("grandparent2"), "a")
197
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
198
self.assertEqual(btree.path2id("grandparent2/parent2/file"), "c")
200
self.assertTrue(btree.path2id("grandparent2/parent") is None)
201
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
203
btree.note_rename("grandparent/parent/file",
204
"grandparent2/parent2/file2")
205
self.assertEqual(btree.id2path("a"), "grandparent2")
206
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
207
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file2")
209
self.assertEqual(btree.path2id("grandparent2"), "a")
210
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
211
self.assertEqual(btree.path2id("grandparent2/parent2/file2"), "c")
213
self.assertTrue(btree.path2id("grandparent2/parent2/file") is None)
215
def test_moves(self):
216
"""Ensure that file moves have the proper effect on children"""
217
btree = self.make_tree_1()[0]
218
btree.note_rename("grandparent/parent/file",
219
"grandparent/alt_parent/file")
220
self.assertEqual(btree.id2path("c"), "grandparent/alt_parent/file")
221
self.assertEqual(btree.path2id("grandparent/alt_parent/file"), "c")
222
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
224
def unified_diff(self, old, new):
226
internal_diff("old", old, "new", new, out)
230
def make_tree_2(self):
231
btree = self.make_tree_1()[0]
232
btree.note_rename("grandparent/parent/file",
233
"grandparent/alt_parent/file")
234
self.assertTrue(btree.id2path("e") is None)
235
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
236
btree.note_id("e", "grandparent/parent/file")
240
"""File/inventory adds"""
241
btree = self.make_tree_2()
242
add_patch = self.unified_diff([], ["Extra cheese\n"])
243
btree.note_patch("grandparent/parent/file", add_patch)
244
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
245
btree.note_target('grandparent/parent/symlink', 'venus')
246
self.adds_test(btree)
248
def adds_test(self, btree):
249
self.assertEqual(btree.id2path("e"), "grandparent/parent/file")
250
self.assertEqual(btree.path2id("grandparent/parent/file"), "e")
251
self.assertEqual(btree.get_file("e").read(), "Extra cheese\n")
252
self.assertEqual(btree.get_symlink_target('f'), 'venus')
254
def test_adds2(self):
255
"""File/inventory adds, with patch-compatibile renames"""
256
btree = self.make_tree_2()
257
btree.contents_by_id = False
258
add_patch = self.unified_diff(["Hello\n"], ["Extra cheese\n"])
259
btree.note_patch("grandparent/parent/file", add_patch)
260
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
261
btree.note_target('grandparent/parent/symlink', 'venus')
262
self.adds_test(btree)
264
def make_tree_3(self):
265
btree, mtree = self.make_tree_1()
266
mtree.add_file("e", "grandparent/parent/topping", "Anchovies\n")
267
btree.note_rename("grandparent/parent/file",
268
"grandparent/alt_parent/file")
269
btree.note_rename("grandparent/parent/topping",
270
"grandparent/alt_parent/stopping")
273
def get_file_test(self, btree):
274
self.assertEqual(btree.get_file("e").read(), "Lemon\n")
275
self.assertEqual(btree.get_file("c").read(), "Hello\n")
277
def test_get_file(self):
278
"""Get file contents"""
279
btree = self.make_tree_3()
280
mod_patch = self.unified_diff(["Anchovies\n"], ["Lemon\n"])
281
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
282
self.get_file_test(btree)
284
def test_get_file2(self):
285
"""Get file contents, with patch-compatibile renames"""
286
btree = self.make_tree_3()
287
btree.contents_by_id = False
288
mod_patch = self.unified_diff([], ["Lemon\n"])
289
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
290
mod_patch = self.unified_diff([], ["Hello\n"])
291
btree.note_patch("grandparent/alt_parent/file", mod_patch)
292
self.get_file_test(btree)
294
def test_delete(self):
296
btree = self.make_tree_1()[0]
297
self.assertEqual(btree.get_file("c").read(), "Hello\n")
298
btree.note_deletion("grandparent/parent/file")
299
self.assertTrue(btree.id2path("c") is None)
300
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
302
def sorted_ids(self, tree):
307
def test_iteration(self):
308
"""Ensure that iteration through ids works properly"""
309
btree = self.make_tree_1()[0]
310
self.assertEqual(self.sorted_ids(btree),
311
[inventory.ROOT_ID, 'a', 'b', 'c', 'd'])
312
btree.note_deletion("grandparent/parent/file")
313
btree.note_id("e", "grandparent/alt_parent/fool", kind="directory")
314
btree.note_last_changed("grandparent/alt_parent/fool",
316
self.assertEqual(self.sorted_ids(btree),
317
[inventory.ROOT_ID, 'a', 'b', 'd', 'e'])
320
class BundleTester1(TestCaseWithTransport):
322
def test_mismatched_bundle(self):
323
format = bzrdir.BzrDirMetaFormat1()
324
format.repository_format = knitrepo.RepositoryFormatKnit3()
325
serializer = BundleSerializerV08('0.8')
326
b = self.make_branch('.', format=format)
327
self.assertRaises(errors.IncompatibleBundleFormat, serializer.write,
328
b.repository, [], {}, StringIO())
330
def test_matched_bundle(self):
331
"""Don't raise IncompatibleBundleFormat for knit2 and bundle0.9"""
332
format = bzrdir.BzrDirMetaFormat1()
333
format.repository_format = knitrepo.RepositoryFormatKnit3()
334
serializer = BundleSerializerV09('0.9')
335
b = self.make_branch('.', format=format)
336
serializer.write(b.repository, [], {}, StringIO())
338
def test_mismatched_model(self):
339
"""Try copying a bundle from knit2 to knit1"""
340
format = bzrdir.BzrDirMetaFormat1()
341
format.repository_format = knitrepo.RepositoryFormatKnit3()
342
source = self.make_branch_and_tree('source', format=format)
343
source.commit('one', rev_id='one-id')
344
source.commit('two', rev_id='two-id')
346
write_bundle(source.branch.repository, 'two-id', 'null:', text,
350
format = bzrdir.BzrDirMetaFormat1()
351
format.repository_format = knitrepo.RepositoryFormatKnit1()
352
target = self.make_branch('target', format=format)
353
self.assertRaises(errors.IncompatibleRevision, install_bundle,
354
target.repository, read_bundle(text))
357
class BundleTester(object):
359
def bzrdir_format(self):
360
format = bzrdir.BzrDirMetaFormat1()
361
format.repository_format = knitrepo.RepositoryFormatKnit1()
364
def make_branch_and_tree(self, path, format=None):
366
format = self.bzrdir_format()
367
return TestCaseWithTransport.make_branch_and_tree(self, path, format)
369
def make_branch(self, path, format=None):
371
format = self.bzrdir_format()
372
return TestCaseWithTransport.make_branch(self, path, format)
374
def create_bundle_text(self, base_rev_id, rev_id):
375
bundle_txt = StringIO()
376
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
377
bundle_txt, format=self.format)
379
self.assertEqual(bundle_txt.readline(),
380
'# Bazaar revision bundle v%s\n' % self.format)
381
self.assertEqual(bundle_txt.readline(), '#\n')
383
rev = self.b1.repository.get_revision(rev_id)
384
self.assertEqual(bundle_txt.readline().decode('utf-8'),
387
return bundle_txt, rev_ids
389
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
390
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
391
Make sure that the text generated is valid, and that it
392
can be applied against the base, and generate the same information.
394
:return: The in-memory bundle
396
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
398
# This should also validate the generated bundle
399
bundle = read_bundle(bundle_txt)
400
repository = self.b1.repository
401
for bundle_rev in bundle.real_revisions:
402
# These really should have already been checked when we read the
403
# bundle, since it computes the sha1 hash for the revision, which
404
# only will match if everything is okay, but lets be explicit about
406
branch_rev = repository.get_revision(bundle_rev.revision_id)
407
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
408
'timestamp', 'timezone', 'message', 'committer',
409
'parent_ids', 'properties'):
410
self.assertEqual(getattr(branch_rev, a),
411
getattr(bundle_rev, a))
412
self.assertEqual(len(branch_rev.parent_ids),
413
len(bundle_rev.parent_ids))
414
self.assertEqual(rev_ids,
415
[r.revision_id for r in bundle.real_revisions])
416
self.valid_apply_bundle(base_rev_id, bundle,
417
checkout_dir=checkout_dir)
421
def get_invalid_bundle(self, base_rev_id, rev_id):
422
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
423
Munge the text so that it's invalid.
425
:return: The in-memory bundle
427
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
428
new_text = bundle_txt.getvalue().replace('executable:no',
430
bundle_txt = StringIO(new_text)
431
bundle = read_bundle(bundle_txt)
432
self.valid_apply_bundle(base_rev_id, bundle)
435
def test_non_bundle(self):
436
self.assertRaises(errors.NotABundle,
437
read_bundle, StringIO('#!/bin/sh\n'))
439
def test_malformed(self):
440
self.assertRaises(errors.BadBundle, read_bundle,
441
StringIO('# Bazaar revision bundle v'))
443
def test_crlf_bundle(self):
445
read_bundle(StringIO('# Bazaar revision bundle v0.8\r\n'))
446
except errors.BadBundle:
447
# It is currently permitted for bundles with crlf line endings to
448
# make read_bundle raise a BadBundle, but this should be fixed.
449
# Anything else, especially NotABundle, is an error.
452
def get_checkout(self, rev_id, checkout_dir=None):
453
"""Get a new tree, with the specified revision in it.
456
if checkout_dir is None:
457
checkout_dir = osutils.mkdtemp(prefix='test-branch-', dir='.')
459
if not os.path.exists(checkout_dir):
460
os.mkdir(checkout_dir)
461
tree = self.make_branch_and_tree(checkout_dir)
463
ancestors = write_bundle(self.b1.repository, rev_id, 'null:', s,
466
self.assertIsInstance(s.getvalue(), str)
467
install_bundle(tree.branch.repository, read_bundle(s))
468
for ancestor in ancestors:
469
old = self.b1.repository.revision_tree(ancestor)
470
new = tree.branch.repository.revision_tree(ancestor)
474
# Check that there aren't any inventory level changes
475
delta = new.changes_from(old)
476
self.assertFalse(delta.has_changed(),
477
'Revision %s not copied correctly.'
480
# Now check that the file contents are all correct
481
for inventory_id in old:
483
old_file = old.get_file(inventory_id)
484
except errors.NoSuchFile:
488
self.assertEqual(old_file.read(),
489
new.get_file(inventory_id).read())
493
if not _mod_revision.is_null(rev_id):
494
rh = self.b1.revision_history()
495
tree.branch.set_revision_history(rh[:rh.index(rev_id)+1])
497
delta = tree.changes_from(self.b1.repository.revision_tree(rev_id))
498
self.assertFalse(delta.has_changed(),
499
'Working tree has modifications: %s' % delta)
502
def valid_apply_bundle(self, base_rev_id, info, checkout_dir=None):
503
"""Get the base revision, apply the changes, and make
504
sure everything matches the builtin branch.
506
to_tree = self.get_checkout(base_rev_id, checkout_dir=checkout_dir)
509
self._valid_apply_bundle(base_rev_id, info, to_tree)
513
def _valid_apply_bundle(self, base_rev_id, info, to_tree):
514
original_parents = to_tree.get_parent_ids()
515
repository = to_tree.branch.repository
516
original_parents = to_tree.get_parent_ids()
517
self.assertIs(repository.has_revision(base_rev_id), True)
518
for rev in info.real_revisions:
519
self.assert_(not repository.has_revision(rev.revision_id),
520
'Revision {%s} present before applying bundle'
522
merge_bundle(info, to_tree, True, Merge3Merger, False, False)
524
for rev in info.real_revisions:
525
self.assert_(repository.has_revision(rev.revision_id),
526
'Missing revision {%s} after applying bundle'
529
self.assert_(to_tree.branch.repository.has_revision(info.target))
530
# Do we also want to verify that all the texts have been added?
532
self.assertEqual(original_parents + [info.target],
533
to_tree.get_parent_ids())
535
rev = info.real_revisions[-1]
536
base_tree = self.b1.repository.revision_tree(rev.revision_id)
537
to_tree = to_tree.branch.repository.revision_tree(rev.revision_id)
539
# TODO: make sure the target tree is identical to base tree
540
# we might also check the working tree.
542
base_files = list(base_tree.list_files())
543
to_files = list(to_tree.list_files())
544
self.assertEqual(len(base_files), len(to_files))
545
for base_file, to_file in zip(base_files, to_files):
546
self.assertEqual(base_file, to_file)
548
for path, status, kind, fileid, entry in base_files:
549
# Check that the meta information is the same
550
self.assertEqual(base_tree.get_file_size(fileid),
551
to_tree.get_file_size(fileid))
552
self.assertEqual(base_tree.get_file_sha1(fileid),
553
to_tree.get_file_sha1(fileid))
554
# Check that the contents are the same
555
# This is pretty expensive
556
# self.assertEqual(base_tree.get_file(fileid).read(),
557
# to_tree.get_file(fileid).read())
559
def test_bundle(self):
560
self.tree1 = self.make_branch_and_tree('b1')
561
self.b1 = self.tree1.branch
563
open('b1/one', 'wb').write('one\n')
564
self.tree1.add('one')
565
self.tree1.commit('add one', rev_id='a@cset-0-1')
567
bundle = self.get_valid_bundle('null:', 'a@cset-0-1')
569
# Make sure we can handle files with spaces, tabs, other
574
, 'b1/dir/filein subdir.c'
575
, 'b1/dir/WithCaps.txt'
576
, 'b1/dir/ pre space'
579
, 'b1/sub/sub/nonempty.txt'
581
open('b1/sub/sub/emptyfile.txt', 'wb').close()
582
open('b1/dir/nolastnewline.txt', 'wb').write('bloop')
583
tt = TreeTransform(self.tree1)
584
tt.new_file('executable', tt.root, '#!/bin/sh\n', 'exe-1', True)
586
# have to fix length of file-id so that we can predictably rewrite
587
# a (length-prefixed) record containing it later.
588
self.tree1.add('with space.txt', 'withspace-id')
591
, 'dir/filein subdir.c'
594
, 'dir/nolastnewline.txt'
597
, 'sub/sub/nonempty.txt'
598
, 'sub/sub/emptyfile.txt'
600
self.tree1.commit('add whitespace', rev_id='a@cset-0-2')
602
bundle = self.get_valid_bundle('a@cset-0-1', 'a@cset-0-2')
604
# Check a rollup bundle
605
bundle = self.get_valid_bundle('null:', 'a@cset-0-2')
609
['sub/sub/nonempty.txt'
610
, 'sub/sub/emptyfile.txt'
613
tt = TreeTransform(self.tree1)
614
trans_id = tt.trans_id_tree_file_id('exe-1')
615
tt.set_executability(False, trans_id)
617
self.tree1.commit('removed', rev_id='a@cset-0-3')
619
bundle = self.get_valid_bundle('a@cset-0-2', 'a@cset-0-3')
620
self.assertRaises((errors.TestamentMismatch,
621
errors.VersionedFileInvalidChecksum), self.get_invalid_bundle,
622
'a@cset-0-2', 'a@cset-0-3')
623
# Check a rollup bundle
624
bundle = self.get_valid_bundle('null:', 'a@cset-0-3')
626
# Now move the directory
627
self.tree1.rename_one('dir', 'sub/dir')
628
self.tree1.commit('rename dir', rev_id='a@cset-0-4')
630
bundle = self.get_valid_bundle('a@cset-0-3', 'a@cset-0-4')
631
# Check a rollup bundle
632
bundle = self.get_valid_bundle('null:', 'a@cset-0-4')
635
open('b1/sub/dir/WithCaps.txt', 'ab').write('\nAdding some text\n')
636
open('b1/sub/dir/ pre space', 'ab').write(
637
'\r\nAdding some\r\nDOS format lines\r\n')
638
open('b1/sub/dir/nolastnewline.txt', 'ab').write('\n')
639
self.tree1.rename_one('sub/dir/ pre space',
641
self.tree1.commit('Modified files', rev_id='a@cset-0-5')
642
bundle = self.get_valid_bundle('a@cset-0-4', 'a@cset-0-5')
644
self.tree1.rename_one('sub/dir/WithCaps.txt', 'temp')
645
self.tree1.rename_one('with space.txt', 'WithCaps.txt')
646
self.tree1.rename_one('temp', 'with space.txt')
647
self.tree1.commit(u'swap filenames', rev_id='a@cset-0-6',
649
bundle = self.get_valid_bundle('a@cset-0-5', 'a@cset-0-6')
650
other = self.get_checkout('a@cset-0-5')
651
tree1_inv = self.tree1.branch.repository.get_inventory_xml(
653
tree2_inv = other.branch.repository.get_inventory_xml('a@cset-0-5')
654
self.assertEqualDiff(tree1_inv, tree2_inv)
655
other.rename_one('sub/dir/nolastnewline.txt', 'sub/nolastnewline.txt')
656
other.commit('rename file', rev_id='a@cset-0-6b')
657
self.tree1.merge_from_branch(other.branch)
658
self.tree1.commit(u'Merge', rev_id='a@cset-0-7',
660
bundle = self.get_valid_bundle('a@cset-0-6', 'a@cset-0-7')
662
def test_symlink_bundle(self):
663
self.requireFeature(SymlinkFeature)
664
self.tree1 = self.make_branch_and_tree('b1')
665
self.b1 = self.tree1.branch
666
tt = TreeTransform(self.tree1)
667
tt.new_symlink('link', tt.root, 'bar/foo', 'link-1')
669
self.tree1.commit('add symlink', rev_id='l@cset-0-1')
670
self.get_valid_bundle('null:', 'l@cset-0-1')
671
tt = TreeTransform(self.tree1)
672
trans_id = tt.trans_id_tree_file_id('link-1')
673
tt.adjust_path('link2', tt.root, trans_id)
674
tt.delete_contents(trans_id)
675
tt.create_symlink('mars', trans_id)
677
self.tree1.commit('rename and change symlink', rev_id='l@cset-0-2')
678
self.get_valid_bundle('l@cset-0-1', 'l@cset-0-2')
679
tt = TreeTransform(self.tree1)
680
trans_id = tt.trans_id_tree_file_id('link-1')
681
tt.delete_contents(trans_id)
682
tt.create_symlink('jupiter', trans_id)
684
self.tree1.commit('just change symlink target', rev_id='l@cset-0-3')
685
self.get_valid_bundle('l@cset-0-2', 'l@cset-0-3')
686
tt = TreeTransform(self.tree1)
687
trans_id = tt.trans_id_tree_file_id('link-1')
688
tt.delete_contents(trans_id)
690
self.tree1.commit('Delete symlink', rev_id='l@cset-0-4')
691
self.get_valid_bundle('l@cset-0-3', 'l@cset-0-4')
693
def test_binary_bundle(self):
694
self.tree1 = self.make_branch_and_tree('b1')
695
self.b1 = self.tree1.branch
696
tt = TreeTransform(self.tree1)
699
tt.new_file('file', tt.root, '\x00\n\x00\r\x01\n\x02\r\xff', 'binary-1')
700
tt.new_file('file2', tt.root, '\x01\n\x02\r\x03\n\x04\r\xff',
703
self.tree1.commit('add binary', rev_id='b@cset-0-1')
704
self.get_valid_bundle('null:', 'b@cset-0-1')
707
tt = TreeTransform(self.tree1)
708
trans_id = tt.trans_id_tree_file_id('binary-1')
709
tt.delete_contents(trans_id)
711
self.tree1.commit('delete binary', rev_id='b@cset-0-2')
712
self.get_valid_bundle('b@cset-0-1', 'b@cset-0-2')
715
tt = TreeTransform(self.tree1)
716
trans_id = tt.trans_id_tree_file_id('binary-2')
717
tt.adjust_path('file3', tt.root, trans_id)
718
tt.delete_contents(trans_id)
719
tt.create_file('file\rcontents\x00\n\x00', trans_id)
721
self.tree1.commit('rename and modify binary', rev_id='b@cset-0-3')
722
self.get_valid_bundle('b@cset-0-2', 'b@cset-0-3')
725
tt = TreeTransform(self.tree1)
726
trans_id = tt.trans_id_tree_file_id('binary-2')
727
tt.delete_contents(trans_id)
728
tt.create_file('\x00file\rcontents', trans_id)
730
self.tree1.commit('just modify binary', rev_id='b@cset-0-4')
731
self.get_valid_bundle('b@cset-0-3', 'b@cset-0-4')
734
self.get_valid_bundle('null:', 'b@cset-0-4')
736
def test_last_modified(self):
737
self.tree1 = self.make_branch_and_tree('b1')
738
self.b1 = self.tree1.branch
739
tt = TreeTransform(self.tree1)
740
tt.new_file('file', tt.root, 'file', 'file')
742
self.tree1.commit('create file', rev_id='a@lmod-0-1')
744
tt = TreeTransform(self.tree1)
745
trans_id = tt.trans_id_tree_file_id('file')
746
tt.delete_contents(trans_id)
747
tt.create_file('file2', trans_id)
749
self.tree1.commit('modify text', rev_id='a@lmod-0-2a')
751
other = self.get_checkout('a@lmod-0-1')
752
tt = TreeTransform(other)
753
trans_id = tt.trans_id_tree_file_id('file')
754
tt.delete_contents(trans_id)
755
tt.create_file('file2', trans_id)
757
other.commit('modify text in another tree', rev_id='a@lmod-0-2b')
758
self.tree1.merge_from_branch(other.branch)
759
self.tree1.commit(u'Merge', rev_id='a@lmod-0-3',
761
self.tree1.commit(u'Merge', rev_id='a@lmod-0-4')
762
bundle = self.get_valid_bundle('a@lmod-0-2a', 'a@lmod-0-4')
764
def test_hide_history(self):
765
self.tree1 = self.make_branch_and_tree('b1')
766
self.b1 = self.tree1.branch
768
open('b1/one', 'wb').write('one\n')
769
self.tree1.add('one')
770
self.tree1.commit('add file', rev_id='a@cset-0-1')
771
open('b1/one', 'wb').write('two\n')
772
self.tree1.commit('modify', rev_id='a@cset-0-2')
773
open('b1/one', 'wb').write('three\n')
774
self.tree1.commit('modify', rev_id='a@cset-0-3')
775
bundle_file = StringIO()
776
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-3',
777
'a@cset-0-1', bundle_file, format=self.format)
778
self.assertNotContainsRe(bundle_file.getvalue(), '\btwo\b')
779
self.assertContainsRe(self.get_raw(bundle_file), 'one')
780
self.assertContainsRe(self.get_raw(bundle_file), 'three')
782
def test_bundle_same_basis(self):
783
"""Ensure using the basis as the target doesn't cause an error"""
784
self.tree1 = self.make_branch_and_tree('b1')
785
self.tree1.commit('add file', rev_id='a@cset-0-1')
786
bundle_file = StringIO()
787
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-1',
788
'a@cset-0-1', bundle_file)
791
def get_raw(bundle_file):
792
return bundle_file.getvalue()
794
def test_unicode_bundle(self):
795
# Handle international characters
798
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
799
except UnicodeEncodeError:
800
raise TestSkipped("Filesystem doesn't support unicode")
802
self.tree1 = self.make_branch_and_tree('b1')
803
self.b1 = self.tree1.branch
806
u'With international man of mystery\n'
807
u'William Dod\xe9\n').encode('utf-8'))
810
self.tree1.add([u'with Dod\N{Euro Sign}'], ['withdod-id'])
811
self.tree1.commit(u'i18n commit from William Dod\xe9',
812
rev_id='i18n-1', committer=u'William Dod\xe9')
815
bundle = self.get_valid_bundle('null:', 'i18n-1')
818
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
819
f.write(u'Modified \xb5\n'.encode('utf8'))
821
self.tree1.commit(u'modified', rev_id='i18n-2')
823
bundle = self.get_valid_bundle('i18n-1', 'i18n-2')
826
self.tree1.rename_one(u'with Dod\N{Euro Sign}', u'B\N{Euro Sign}gfors')
827
self.tree1.commit(u'renamed, the new i18n man', rev_id='i18n-3',
828
committer=u'Erik B\xe5gfors')
830
bundle = self.get_valid_bundle('i18n-2', 'i18n-3')
833
self.tree1.remove([u'B\N{Euro Sign}gfors'])
834
self.tree1.commit(u'removed', rev_id='i18n-4')
836
bundle = self.get_valid_bundle('i18n-3', 'i18n-4')
839
bundle = self.get_valid_bundle('null:', 'i18n-4')
842
def test_whitespace_bundle(self):
843
if sys.platform in ('win32', 'cygwin'):
844
raise TestSkipped('Windows doesn\'t support filenames'
845
' with tabs or trailing spaces')
846
self.tree1 = self.make_branch_and_tree('b1')
847
self.b1 = self.tree1.branch
849
self.build_tree(['b1/trailing space '])
850
self.tree1.add(['trailing space '])
851
# TODO: jam 20060701 Check for handling files with '\t' characters
852
# once we actually support them
855
self.tree1.commit('funky whitespace', rev_id='white-1')
857
bundle = self.get_valid_bundle('null:', 'white-1')
860
open('b1/trailing space ', 'ab').write('add some text\n')
861
self.tree1.commit('add text', rev_id='white-2')
863
bundle = self.get_valid_bundle('white-1', 'white-2')
866
self.tree1.rename_one('trailing space ', ' start and end space ')
867
self.tree1.commit('rename', rev_id='white-3')
869
bundle = self.get_valid_bundle('white-2', 'white-3')
872
self.tree1.remove([' start and end space '])
873
self.tree1.commit('removed', rev_id='white-4')
875
bundle = self.get_valid_bundle('white-3', 'white-4')
877
# Now test a complet roll-up
878
bundle = self.get_valid_bundle('null:', 'white-4')
880
def test_alt_timezone_bundle(self):
881
self.tree1 = self.make_branch_and_memory_tree('b1')
882
self.b1 = self.tree1.branch
883
builder = treebuilder.TreeBuilder()
885
self.tree1.lock_write()
886
builder.start_tree(self.tree1)
887
builder.build(['newfile'])
888
builder.finish_tree()
890
# Asia/Colombo offset = 5 hours 30 minutes
891
self.tree1.commit('non-hour offset timezone', rev_id='tz-1',
892
timezone=19800, timestamp=1152544886.0)
894
bundle = self.get_valid_bundle('null:', 'tz-1')
896
rev = bundle.revisions[0]
897
self.assertEqual('Mon 2006-07-10 20:51:26.000000000 +0530', rev.date)
898
self.assertEqual(19800, rev.timezone)
899
self.assertEqual(1152544886.0, rev.timestamp)
902
def test_bundle_root_id(self):
903
self.tree1 = self.make_branch_and_tree('b1')
904
self.b1 = self.tree1.branch
905
self.tree1.commit('message', rev_id='revid1')
906
bundle = self.get_valid_bundle('null:', 'revid1')
907
tree = self.get_bundle_tree(bundle, 'revid1')
908
self.assertEqual('revid1', tree.inventory.root.revision)
910
def test_install_revisions(self):
911
self.tree1 = self.make_branch_and_tree('b1')
912
self.b1 = self.tree1.branch
913
self.tree1.commit('message', rev_id='rev2a')
914
bundle = self.get_valid_bundle('null:', 'rev2a')
915
branch2 = self.make_branch('b2')
916
self.assertFalse(branch2.repository.has_revision('rev2a'))
917
target_revision = bundle.install_revisions(branch2.repository)
918
self.assertTrue(branch2.repository.has_revision('rev2a'))
919
self.assertEqual('rev2a', target_revision)
921
def test_bundle_empty_property(self):
922
"""Test serializing revision properties with an empty value."""
923
tree = self.make_branch_and_memory_tree('tree')
925
self.addCleanup(tree.unlock)
926
tree.add([''], ['TREE_ROOT'])
927
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
928
self.b1 = tree.branch
929
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
930
bundle = read_bundle(bundle_sio)
931
revision_info = bundle.revisions[0]
932
self.assertEqual('rev1', revision_info.revision_id)
933
rev = revision_info.as_revision()
934
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
937
def test_bundle_sorted_properties(self):
938
"""For stability the writer should write properties in sorted order."""
939
tree = self.make_branch_and_memory_tree('tree')
941
self.addCleanup(tree.unlock)
943
tree.add([''], ['TREE_ROOT'])
944
tree.commit('One', rev_id='rev1',
945
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
946
self.b1 = tree.branch
947
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
948
bundle = read_bundle(bundle_sio)
949
revision_info = bundle.revisions[0]
950
self.assertEqual('rev1', revision_info.revision_id)
951
rev = revision_info.as_revision()
952
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
953
'd':'1'}, rev.properties)
955
def test_bundle_unicode_properties(self):
956
"""We should be able to round trip a non-ascii property."""
957
tree = self.make_branch_and_memory_tree('tree')
959
self.addCleanup(tree.unlock)
961
tree.add([''], ['TREE_ROOT'])
962
# Revisions themselves do not require anything about revision property
963
# keys, other than that they are a basestring, and do not contain
965
# However, Testaments assert than they are str(), and thus should not
967
tree.commit('One', rev_id='rev1',
968
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
969
self.b1 = tree.branch
970
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
971
bundle = read_bundle(bundle_sio)
972
revision_info = bundle.revisions[0]
973
self.assertEqual('rev1', revision_info.revision_id)
974
rev = revision_info.as_revision()
975
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
976
'alpha':u'\u03b1'}, rev.properties)
978
def test_bundle_with_ghosts(self):
979
tree = self.make_branch_and_tree('tree')
980
self.b1 = tree.branch
981
self.build_tree_contents([('tree/file', 'content1')])
984
self.build_tree_contents([('tree/file', 'content2')])
985
tree.add_parent_tree_id('ghost')
986
tree.commit('rev2', rev_id='rev2')
987
bundle = self.get_valid_bundle('null:', 'rev2')
989
def make_simple_tree(self, format=None):
990
tree = self.make_branch_and_tree('b1', format=format)
991
self.b1 = tree.branch
992
self.build_tree(['b1/file'])
996
def test_across_serializers(self):
997
tree = self.make_simple_tree('knit')
998
tree.commit('hello', rev_id='rev1')
999
tree.commit('hello', rev_id='rev2')
1000
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1001
repo = self.make_repository('repo', format='dirstate-with-subtree')
1002
bundle.install_revisions(repo)
1003
inv_text = repo.get_inventory_xml('rev2')
1004
self.assertNotContainsRe(inv_text, 'format="5"')
1005
self.assertContainsRe(inv_text, 'format="7"')
1007
def make_repo_with_installed_revisions(self):
1008
tree = self.make_simple_tree('knit')
1009
tree.commit('hello', rev_id='rev1')
1010
tree.commit('hello', rev_id='rev2')
1011
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1012
repo = self.make_repository('repo', format='dirstate-with-subtree')
1013
bundle.install_revisions(repo)
1016
def test_across_models(self):
1017
repo = self.make_repo_with_installed_revisions()
1018
inv = repo.get_inventory('rev2')
1019
self.assertEqual('rev2', inv.root.revision)
1020
root_id = inv.root.file_id
1022
self.addCleanup(repo.unlock)
1023
self.assertEqual({(root_id, 'rev1'):(),
1024
(root_id, 'rev2'):((root_id, 'rev1'),)},
1025
repo.texts.get_parent_map([(root_id, 'rev1'), (root_id, 'rev2')]))
1027
def test_inv_hash_across_serializers(self):
1028
repo = self.make_repo_with_installed_revisions()
1029
recorded_inv_sha1 = repo.get_inventory_sha1('rev2')
1030
xml = repo.get_inventory_xml('rev2')
1031
self.assertEqual(sha_string(xml), recorded_inv_sha1)
1033
def test_across_models_incompatible(self):
1034
tree = self.make_simple_tree('dirstate-with-subtree')
1035
tree.commit('hello', rev_id='rev1')
1036
tree.commit('hello', rev_id='rev2')
1038
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1039
except errors.IncompatibleBundleFormat:
1040
raise TestSkipped("Format 0.8 doesn't work with knit3")
1041
repo = self.make_repository('repo', format='knit')
1042
bundle.install_revisions(repo)
1044
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1045
self.assertRaises(errors.IncompatibleRevision,
1046
bundle.install_revisions, repo)
1048
def test_get_merge_request(self):
1049
tree = self.make_simple_tree()
1050
tree.commit('hello', rev_id='rev1')
1051
tree.commit('hello', rev_id='rev2')
1052
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1053
result = bundle.get_merge_request(tree.branch.repository)
1054
self.assertEqual((None, 'rev1', 'inapplicable'), result)
1056
def test_with_subtree(self):
1057
tree = self.make_branch_and_tree('tree',
1058
format='dirstate-with-subtree')
1059
self.b1 = tree.branch
1060
subtree = self.make_branch_and_tree('tree/subtree',
1061
format='dirstate-with-subtree')
1063
tree.commit('hello', rev_id='rev1')
1065
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1066
except errors.IncompatibleBundleFormat:
1067
raise TestSkipped("Format 0.8 doesn't work with knit3")
1068
if isinstance(bundle, v09.BundleInfo09):
1069
raise TestSkipped("Format 0.9 doesn't work with subtrees")
1070
repo = self.make_repository('repo', format='knit')
1071
self.assertRaises(errors.IncompatibleRevision,
1072
bundle.install_revisions, repo)
1073
repo2 = self.make_repository('repo2', format='dirstate-with-subtree')
1074
bundle.install_revisions(repo2)
1076
def test_revision_id_with_slash(self):
1077
self.tree1 = self.make_branch_and_tree('tree')
1078
self.b1 = self.tree1.branch
1080
self.tree1.commit('Revision/id/with/slashes', rev_id='rev/id')
1082
raise TestSkipped("Repository doesn't support revision ids with"
1084
bundle = self.get_valid_bundle('null:', 'rev/id')
1086
def test_skip_file(self):
1087
"""Make sure we don't accidentally write to the wrong versionedfile"""
1088
self.tree1 = self.make_branch_and_tree('tree')
1089
self.b1 = self.tree1.branch
1090
# rev1 is not present in bundle, done by fetch
1091
self.build_tree_contents([('tree/file2', 'contents1')])
1092
self.tree1.add('file2', 'file2-id')
1093
self.tree1.commit('rev1', rev_id='reva')
1094
self.build_tree_contents([('tree/file3', 'contents2')])
1095
# rev2 is present in bundle, and done by fetch
1096
# having file1 in the bunle causes file1's versionedfile to be opened.
1097
self.tree1.add('file3', 'file3-id')
1098
self.tree1.commit('rev2')
1099
# Updating file2 should not cause an attempt to add to file1's vf
1100
target = self.tree1.bzrdir.sprout('target').open_workingtree()
1101
self.build_tree_contents([('tree/file2', 'contents3')])
1102
self.tree1.commit('rev3', rev_id='rev3')
1103
bundle = self.get_valid_bundle('reva', 'rev3')
1104
if getattr(bundle, 'get_bundle_reader', None) is None:
1105
raise TestSkipped('Bundle format cannot provide reader')
1106
# be sure that file1 comes before file2
1107
for b, m, k, r, f in bundle.get_bundle_reader().iter_records():
1110
self.assertNotEqual(f, 'file2-id')
1111
bundle.install_revisions(target.branch.repository)
1114
class V08BundleTester(BundleTester, TestCaseWithTransport):
1118
def test_bundle_empty_property(self):
1119
"""Test serializing revision properties with an empty value."""
1120
tree = self.make_branch_and_memory_tree('tree')
1122
self.addCleanup(tree.unlock)
1123
tree.add([''], ['TREE_ROOT'])
1124
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1125
self.b1 = tree.branch
1126
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1127
self.assertContainsRe(bundle_sio.getvalue(),
1129
'# branch-nick: tree\n'
1133
bundle = read_bundle(bundle_sio)
1134
revision_info = bundle.revisions[0]
1135
self.assertEqual('rev1', revision_info.revision_id)
1136
rev = revision_info.as_revision()
1137
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1140
def get_bundle_tree(self, bundle, revision_id):
1141
repository = self.make_repository('repo')
1142
return bundle.revision_tree(repository, 'revid1')
1144
def test_bundle_empty_property_alt(self):
1145
"""Test serializing revision properties with an empty value.
1147
Older readers had a bug when reading an empty property.
1148
They assumed that all keys ended in ': \n'. However they would write an
1149
empty value as ':\n'. This tests make sure that all newer bzr versions
1150
can handle th second form.
1152
tree = self.make_branch_and_memory_tree('tree')
1154
self.addCleanup(tree.unlock)
1155
tree.add([''], ['TREE_ROOT'])
1156
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1157
self.b1 = tree.branch
1158
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1159
txt = bundle_sio.getvalue()
1160
loc = txt.find('# empty: ') + len('# empty:')
1161
# Create a new bundle, which strips the trailing space after empty
1162
bundle_sio = StringIO(txt[:loc] + txt[loc+1:])
1164
self.assertContainsRe(bundle_sio.getvalue(),
1166
'# branch-nick: tree\n'
1170
bundle = read_bundle(bundle_sio)
1171
revision_info = bundle.revisions[0]
1172
self.assertEqual('rev1', revision_info.revision_id)
1173
rev = revision_info.as_revision()
1174
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1177
def test_bundle_sorted_properties(self):
1178
"""For stability the writer should write properties in sorted order."""
1179
tree = self.make_branch_and_memory_tree('tree')
1181
self.addCleanup(tree.unlock)
1183
tree.add([''], ['TREE_ROOT'])
1184
tree.commit('One', rev_id='rev1',
1185
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1186
self.b1 = tree.branch
1187
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1188
self.assertContainsRe(bundle_sio.getvalue(),
1192
'# branch-nick: tree\n'
1196
bundle = read_bundle(bundle_sio)
1197
revision_info = bundle.revisions[0]
1198
self.assertEqual('rev1', revision_info.revision_id)
1199
rev = revision_info.as_revision()
1200
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1201
'd':'1'}, rev.properties)
1203
def test_bundle_unicode_properties(self):
1204
"""We should be able to round trip a non-ascii property."""
1205
tree = self.make_branch_and_memory_tree('tree')
1207
self.addCleanup(tree.unlock)
1209
tree.add([''], ['TREE_ROOT'])
1210
# Revisions themselves do not require anything about revision property
1211
# keys, other than that they are a basestring, and do not contain
1213
# However, Testaments assert than they are str(), and thus should not
1215
tree.commit('One', rev_id='rev1',
1216
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1217
self.b1 = tree.branch
1218
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1219
self.assertContainsRe(bundle_sio.getvalue(),
1221
'# alpha: \xce\xb1\n'
1222
'# branch-nick: tree\n'
1223
'# omega: \xce\xa9\n'
1225
bundle = read_bundle(bundle_sio)
1226
revision_info = bundle.revisions[0]
1227
self.assertEqual('rev1', revision_info.revision_id)
1228
rev = revision_info.as_revision()
1229
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1230
'alpha':u'\u03b1'}, rev.properties)
1233
class V09BundleKnit2Tester(V08BundleTester):
1237
def bzrdir_format(self):
1238
format = bzrdir.BzrDirMetaFormat1()
1239
format.repository_format = knitrepo.RepositoryFormatKnit3()
1243
class V09BundleKnit1Tester(V08BundleTester):
1247
def bzrdir_format(self):
1248
format = bzrdir.BzrDirMetaFormat1()
1249
format.repository_format = knitrepo.RepositoryFormatKnit1()
1253
class V4BundleTester(BundleTester, TestCaseWithTransport):
1257
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
1258
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1259
Make sure that the text generated is valid, and that it
1260
can be applied against the base, and generate the same information.
1262
:return: The in-memory bundle
1264
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1266
# This should also validate the generated bundle
1267
bundle = read_bundle(bundle_txt)
1268
repository = self.b1.repository
1269
for bundle_rev in bundle.real_revisions:
1270
# These really should have already been checked when we read the
1271
# bundle, since it computes the sha1 hash for the revision, which
1272
# only will match if everything is okay, but lets be explicit about
1274
branch_rev = repository.get_revision(bundle_rev.revision_id)
1275
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
1276
'timestamp', 'timezone', 'message', 'committer',
1277
'parent_ids', 'properties'):
1278
self.assertEqual(getattr(branch_rev, a),
1279
getattr(bundle_rev, a))
1280
self.assertEqual(len(branch_rev.parent_ids),
1281
len(bundle_rev.parent_ids))
1282
self.assertEqual(set(rev_ids),
1283
set([r.revision_id for r in bundle.real_revisions]))
1284
self.valid_apply_bundle(base_rev_id, bundle,
1285
checkout_dir=checkout_dir)
1289
def get_invalid_bundle(self, base_rev_id, rev_id):
1290
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1291
Munge the text so that it's invalid.
1293
:return: The in-memory bundle
1295
from bzrlib.bundle import serializer
1296
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1297
new_text = self.get_raw(StringIO(''.join(bundle_txt)))
1298
new_text = new_text.replace('<file file_id="exe-1"',
1299
'<file executable="y" file_id="exe-1"')
1300
new_text = new_text.replace('B222', 'B237')
1301
bundle_txt = StringIO()
1302
bundle_txt.write(serializer._get_bundle_header('4'))
1303
bundle_txt.write('\n')
1304
bundle_txt.write(new_text.encode('bz2'))
1306
bundle = read_bundle(bundle_txt)
1307
self.valid_apply_bundle(base_rev_id, bundle)
1310
def create_bundle_text(self, base_rev_id, rev_id):
1311
bundle_txt = StringIO()
1312
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
1313
bundle_txt, format=self.format)
1315
self.assertEqual(bundle_txt.readline(),
1316
'# Bazaar revision bundle v%s\n' % self.format)
1317
self.assertEqual(bundle_txt.readline(), '#\n')
1318
rev = self.b1.repository.get_revision(rev_id)
1320
return bundle_txt, rev_ids
1322
def get_bundle_tree(self, bundle, revision_id):
1323
repository = self.make_repository('repo')
1324
bundle.install_revisions(repository)
1325
return repository.revision_tree(revision_id)
1327
def test_creation(self):
1328
tree = self.make_branch_and_tree('tree')
1329
self.build_tree_contents([('tree/file', 'contents1\nstatic\n')])
1330
tree.add('file', 'fileid-2')
1331
tree.commit('added file', rev_id='rev1')
1332
self.build_tree_contents([('tree/file', 'contents2\nstatic\n')])
1333
tree.commit('changed file', rev_id='rev2')
1335
serializer = BundleSerializerV4('1.0')
1336
serializer.write(tree.branch.repository, ['rev1', 'rev2'], {}, s)
1338
tree2 = self.make_branch_and_tree('target')
1339
target_repo = tree2.branch.repository
1340
install_bundle(target_repo, serializer.read(s))
1341
target_repo.lock_read()
1342
self.addCleanup(target_repo.unlock)
1343
self.assertEqual({'1':'contents1\nstatic\n',
1344
'2':'contents2\nstatic\n'},
1345
dict(target_repo.iter_files_bytes(
1346
[('fileid-2', 'rev1', '1'), ('fileid-2', 'rev2', '2')])))
1347
rtree = target_repo.revision_tree('rev2')
1348
inventory_vf = target_repo.inventories
1349
# If the inventory store has a graph, it must match the revision graph.
1351
[inventory_vf.get_parent_map([('rev2',)])[('rev2',)]],
1352
[None, (('rev1',),)])
1353
self.assertEqual('changed file',
1354
target_repo.get_revision('rev2').message)
1357
def get_raw(bundle_file):
1359
line = bundle_file.readline()
1360
line = bundle_file.readline()
1361
lines = bundle_file.readlines()
1362
return ''.join(lines).decode('bz2')
1364
def test_copy_signatures(self):
1365
tree_a = self.make_branch_and_tree('tree_a')
1367
import bzrlib.commit as commit
1368
oldstrategy = bzrlib.gpg.GPGStrategy
1369
branch = tree_a.branch
1370
repo_a = branch.repository
1371
tree_a.commit("base", allow_pointless=True, rev_id='A')
1372
self.failIf(branch.repository.has_signature_for_revision_id('A'))
1374
from bzrlib.testament import Testament
1375
# monkey patch gpg signing mechanism
1376
bzrlib.gpg.GPGStrategy = bzrlib.gpg.LoopbackGPGStrategy
1377
new_config = test_commit.MustSignConfig(branch)
1378
commit.Commit(config=new_config).commit(message="base",
1379
allow_pointless=True,
1381
working_tree=tree_a)
1383
return bzrlib.gpg.LoopbackGPGStrategy(None).sign(text)
1384
self.assertTrue(repo_a.has_signature_for_revision_id('B'))
1386
bzrlib.gpg.GPGStrategy = oldstrategy
1387
tree_b = self.make_branch_and_tree('tree_b')
1388
repo_b = tree_b.branch.repository
1390
serializer = BundleSerializerV4('4')
1391
serializer.write(tree_a.branch.repository, ['A', 'B'], {}, s)
1393
install_bundle(repo_b, serializer.read(s))
1394
self.assertTrue(repo_b.has_signature_for_revision_id('B'))
1395
self.assertEqual(repo_b.get_signature_text('B'),
1396
repo_a.get_signature_text('B'))
1398
# ensure repeat installs are harmless
1399
install_bundle(repo_b, serializer.read(s))
1402
class V4WeaveBundleTester(V4BundleTester):
1404
def bzrdir_format(self):
1408
class MungedBundleTester(object):
1410
def build_test_bundle(self):
1411
wt = self.make_branch_and_tree('b1')
1413
self.build_tree(['b1/one'])
1415
wt.commit('add one', rev_id='a@cset-0-1')
1416
self.build_tree(['b1/two'])
1418
wt.commit('add two', rev_id='a@cset-0-2',
1419
revprops={'branch-nick':'test'})
1421
bundle_txt = StringIO()
1422
rev_ids = write_bundle(wt.branch.repository, 'a@cset-0-2',
1423
'a@cset-0-1', bundle_txt, self.format)
1424
self.assertEqual(set(['a@cset-0-2']), set(rev_ids))
1425
bundle_txt.seek(0, 0)
1428
def check_valid(self, bundle):
1429
"""Check that after whatever munging, the final object is valid."""
1430
self.assertEqual(['a@cset-0-2'],
1431
[r.revision_id for r in bundle.real_revisions])
1433
def test_extra_whitespace(self):
1434
bundle_txt = self.build_test_bundle()
1436
# Seek to the end of the file
1437
# Adding one extra newline used to give us
1438
# TypeError: float() argument must be a string or a number
1439
bundle_txt.seek(0, 2)
1440
bundle_txt.write('\n')
1443
bundle = read_bundle(bundle_txt)
1444
self.check_valid(bundle)
1446
def test_extra_whitespace_2(self):
1447
bundle_txt = self.build_test_bundle()
1449
# Seek to the end of the file
1450
# Adding two extra newlines used to give us
1451
# MalformedPatches: The first line of all patches should be ...
1452
bundle_txt.seek(0, 2)
1453
bundle_txt.write('\n\n')
1456
bundle = read_bundle(bundle_txt)
1457
self.check_valid(bundle)
1460
class MungedBundleTesterV09(TestCaseWithTransport, MungedBundleTester):
1464
def test_missing_trailing_whitespace(self):
1465
bundle_txt = self.build_test_bundle()
1467
# Remove a trailing newline, it shouldn't kill the parser
1468
raw = bundle_txt.getvalue()
1469
# The contents of the bundle don't have to be this, but this
1470
# test is concerned with the exact case where the serializer
1471
# creates a blank line at the end, and fails if that
1473
self.assertEqual('\n\n', raw[-2:])
1474
bundle_txt = StringIO(raw[:-1])
1476
bundle = read_bundle(bundle_txt)
1477
self.check_valid(bundle)
1479
def test_opening_text(self):
1480
bundle_txt = self.build_test_bundle()
1482
bundle_txt = StringIO("Some random\nemail comments\n"
1483
+ bundle_txt.getvalue())
1485
bundle = read_bundle(bundle_txt)
1486
self.check_valid(bundle)
1488
def test_trailing_text(self):
1489
bundle_txt = self.build_test_bundle()
1491
bundle_txt = StringIO(bundle_txt.getvalue() +
1492
"Some trailing\nrandom\ntext\n")
1494
bundle = read_bundle(bundle_txt)
1495
self.check_valid(bundle)
1498
class MungedBundleTesterV4(TestCaseWithTransport, MungedBundleTester):
1503
class TestBundleWriterReader(TestCase):
1505
def test_roundtrip_record(self):
1506
fileobj = StringIO()
1507
writer = v4.BundleWriter(fileobj)
1509
writer.add_info_record(foo='bar')
1510
writer._add_record("Record body", {'parents': ['1', '3'],
1511
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1514
reader = v4.BundleReader(fileobj, stream_input=True)
1515
record_iter = reader.iter_records()
1516
record = record_iter.next()
1517
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1518
'info', None, None), record)
1519
record = record_iter.next()
1520
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1521
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1524
def test_roundtrip_record_memory_hungry(self):
1525
fileobj = StringIO()
1526
writer = v4.BundleWriter(fileobj)
1528
writer.add_info_record(foo='bar')
1529
writer._add_record("Record body", {'parents': ['1', '3'],
1530
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1533
reader = v4.BundleReader(fileobj, stream_input=False)
1534
record_iter = reader.iter_records()
1535
record = record_iter.next()
1536
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1537
'info', None, None), record)
1538
record = record_iter.next()
1539
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1540
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1543
def test_encode_name(self):
1544
self.assertEqual('revision/rev1',
1545
v4.BundleWriter.encode_name('revision', 'rev1'))
1546
self.assertEqual('file/rev//1/file-id-1',
1547
v4.BundleWriter.encode_name('file', 'rev/1', 'file-id-1'))
1548
self.assertEqual('info',
1549
v4.BundleWriter.encode_name('info', None, None))
1551
def test_decode_name(self):
1552
self.assertEqual(('revision', 'rev1', None),
1553
v4.BundleReader.decode_name('revision/rev1'))
1554
self.assertEqual(('file', 'rev/1', 'file-id-1'),
1555
v4.BundleReader.decode_name('file/rev//1/file-id-1'))
1556
self.assertEqual(('info', None, None),
1557
v4.BundleReader.decode_name('info'))
1559
def test_too_many_names(self):
1560
fileobj = StringIO()
1561
writer = v4.BundleWriter(fileobj)
1563
writer.add_info_record(foo='bar')
1564
writer._container.add_bytes_record('blah', ['two', 'names'])
1567
record_iter = v4.BundleReader(fileobj).iter_records()
1568
record = record_iter.next()
1569
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1570
'info', None, None), record)
1571
self.assertRaises(errors.BadBundle, record_iter.next)
1574
class TestReadMergeableFromUrl(TestCaseWithTransport):
1576
def test_read_mergeable_skips_local(self):
1577
"""A local bundle named like the URL should not be read.
1579
out, wt = test_read_bundle.create_bundle_file(self)
1580
class FooService(object):
1581
"""A directory service that always returns source"""
1583
def look_up(self, name, url):
1585
directories.register('foo:', FooService, 'Testing directory service')
1586
self.addCleanup(lambda: directories.remove('foo:'))
1587
self.build_tree_contents([('./foo:bar', out.getvalue())])
1588
self.assertRaises(errors.NotABundle, read_mergeable_from_url,