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.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, v09, v4
34
from bzrlib.bundle.serializer.v08 import BundleSerializerV08
35
from bzrlib.bundle.serializer.v09 import BundleSerializerV09
36
from bzrlib.bundle.serializer.v4 import BundleSerializerV4
37
from bzrlib.branch import Branch
38
from bzrlib.diff import internal_diff
39
from bzrlib.errors import (BzrError, TestamentMismatch, NotABundle, BadBundle,
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
49
class MockTree(object):
51
from bzrlib.inventory import InventoryDirectory, ROOT_ID
53
self.paths = {ROOT_ID: ""}
54
self.ids = {"": ROOT_ID}
56
self.root = InventoryDirectory(ROOT_ID, '', None)
58
inventory = property(lambda x:x)
61
return self.paths.iterkeys()
63
def __getitem__(self, file_id):
64
if file_id == self.root.file_id:
67
return self.make_entry(file_id, self.paths[file_id])
69
def parent_id(self, file_id):
70
parent_dir = os.path.dirname(self.paths[file_id])
73
return self.ids[parent_dir]
75
def iter_entries(self):
76
for path, file_id in self.ids.iteritems():
77
yield path, self[file_id]
79
def get_file_kind(self, file_id):
80
if file_id in self.contents:
86
def make_entry(self, file_id, path):
87
from bzrlib.inventory import (InventoryEntry, InventoryFile
88
, InventoryDirectory, InventoryLink)
89
name = os.path.basename(path)
90
kind = self.get_file_kind(file_id)
91
parent_id = self.parent_id(file_id)
92
text_sha_1, text_size = self.contents_stats(file_id)
93
if kind == 'directory':
94
ie = InventoryDirectory(file_id, name, parent_id)
96
ie = InventoryFile(file_id, name, parent_id)
97
elif kind == 'symlink':
98
ie = InventoryLink(file_id, name, parent_id)
100
raise BzrError('unknown kind %r' % kind)
101
ie.text_sha1 = text_sha_1
102
ie.text_size = text_size
105
def add_dir(self, file_id, path):
106
self.paths[file_id] = path
107
self.ids[path] = file_id
109
def add_file(self, file_id, path, contents):
110
self.add_dir(file_id, path)
111
self.contents[file_id] = contents
113
def path2id(self, path):
114
return self.ids.get(path)
116
def id2path(self, file_id):
117
return self.paths.get(file_id)
119
def has_id(self, file_id):
120
return self.id2path(file_id) is not None
122
def get_file(self, file_id):
124
result.write(self.contents[file_id])
128
def contents_stats(self, file_id):
129
if file_id not in self.contents:
131
text_sha1 = sha_file(self.get_file(file_id))
132
return text_sha1, len(self.contents[file_id])
135
class BTreeTester(TestCase):
136
"""A simple unittest tester for the BundleTree class."""
138
def make_tree_1(self):
140
mtree.add_dir("a", "grandparent")
141
mtree.add_dir("b", "grandparent/parent")
142
mtree.add_file("c", "grandparent/parent/file", "Hello\n")
143
mtree.add_dir("d", "grandparent/alt_parent")
144
return BundleTree(mtree, ''), mtree
146
def test_renames(self):
147
"""Ensure that file renames have the proper effect on children"""
148
btree = self.make_tree_1()[0]
149
self.assertEqual(btree.old_path("grandparent"), "grandparent")
150
self.assertEqual(btree.old_path("grandparent/parent"),
151
"grandparent/parent")
152
self.assertEqual(btree.old_path("grandparent/parent/file"),
153
"grandparent/parent/file")
155
self.assertEqual(btree.id2path("a"), "grandparent")
156
self.assertEqual(btree.id2path("b"), "grandparent/parent")
157
self.assertEqual(btree.id2path("c"), "grandparent/parent/file")
159
self.assertEqual(btree.path2id("grandparent"), "a")
160
self.assertEqual(btree.path2id("grandparent/parent"), "b")
161
self.assertEqual(btree.path2id("grandparent/parent/file"), "c")
163
assert btree.path2id("grandparent2") is None
164
assert btree.path2id("grandparent2/parent") is None
165
assert btree.path2id("grandparent2/parent/file") is None
167
btree.note_rename("grandparent", "grandparent2")
168
assert btree.old_path("grandparent") is None
169
assert btree.old_path("grandparent/parent") is None
170
assert btree.old_path("grandparent/parent/file") is None
172
self.assertEqual(btree.id2path("a"), "grandparent2")
173
self.assertEqual(btree.id2path("b"), "grandparent2/parent")
174
self.assertEqual(btree.id2path("c"), "grandparent2/parent/file")
176
self.assertEqual(btree.path2id("grandparent2"), "a")
177
self.assertEqual(btree.path2id("grandparent2/parent"), "b")
178
self.assertEqual(btree.path2id("grandparent2/parent/file"), "c")
180
assert btree.path2id("grandparent") is None
181
assert btree.path2id("grandparent/parent") is None
182
assert btree.path2id("grandparent/parent/file") is None
184
btree.note_rename("grandparent/parent", "grandparent2/parent2")
185
self.assertEqual(btree.id2path("a"), "grandparent2")
186
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
187
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file")
189
self.assertEqual(btree.path2id("grandparent2"), "a")
190
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
191
self.assertEqual(btree.path2id("grandparent2/parent2/file"), "c")
193
assert btree.path2id("grandparent2/parent") is None
194
assert btree.path2id("grandparent2/parent/file") is None
196
btree.note_rename("grandparent/parent/file",
197
"grandparent2/parent2/file2")
198
self.assertEqual(btree.id2path("a"), "grandparent2")
199
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
200
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file2")
202
self.assertEqual(btree.path2id("grandparent2"), "a")
203
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
204
self.assertEqual(btree.path2id("grandparent2/parent2/file2"), "c")
206
assert btree.path2id("grandparent2/parent2/file") is None
208
def test_moves(self):
209
"""Ensure that file moves have the proper effect on children"""
210
btree = self.make_tree_1()[0]
211
btree.note_rename("grandparent/parent/file",
212
"grandparent/alt_parent/file")
213
self.assertEqual(btree.id2path("c"), "grandparent/alt_parent/file")
214
self.assertEqual(btree.path2id("grandparent/alt_parent/file"), "c")
215
assert btree.path2id("grandparent/parent/file") is None
217
def unified_diff(self, old, new):
219
internal_diff("old", old, "new", new, out)
223
def make_tree_2(self):
224
btree = self.make_tree_1()[0]
225
btree.note_rename("grandparent/parent/file",
226
"grandparent/alt_parent/file")
227
assert btree.id2path("e") is None
228
assert btree.path2id("grandparent/parent/file") is None
229
btree.note_id("e", "grandparent/parent/file")
233
"""File/inventory adds"""
234
btree = self.make_tree_2()
235
add_patch = self.unified_diff([], ["Extra cheese\n"])
236
btree.note_patch("grandparent/parent/file", add_patch)
237
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
238
btree.note_target('grandparent/parent/symlink', 'venus')
239
self.adds_test(btree)
241
def adds_test(self, btree):
242
self.assertEqual(btree.id2path("e"), "grandparent/parent/file")
243
self.assertEqual(btree.path2id("grandparent/parent/file"), "e")
244
self.assertEqual(btree.get_file("e").read(), "Extra cheese\n")
245
self.assertEqual(btree.get_symlink_target('f'), 'venus')
247
def test_adds2(self):
248
"""File/inventory adds, with patch-compatibile renames"""
249
btree = self.make_tree_2()
250
btree.contents_by_id = False
251
add_patch = self.unified_diff(["Hello\n"], ["Extra cheese\n"])
252
btree.note_patch("grandparent/parent/file", add_patch)
253
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
254
btree.note_target('grandparent/parent/symlink', 'venus')
255
self.adds_test(btree)
257
def make_tree_3(self):
258
btree, mtree = self.make_tree_1()
259
mtree.add_file("e", "grandparent/parent/topping", "Anchovies\n")
260
btree.note_rename("grandparent/parent/file",
261
"grandparent/alt_parent/file")
262
btree.note_rename("grandparent/parent/topping",
263
"grandparent/alt_parent/stopping")
266
def get_file_test(self, btree):
267
self.assertEqual(btree.get_file("e").read(), "Lemon\n")
268
self.assertEqual(btree.get_file("c").read(), "Hello\n")
270
def test_get_file(self):
271
"""Get file contents"""
272
btree = self.make_tree_3()
273
mod_patch = self.unified_diff(["Anchovies\n"], ["Lemon\n"])
274
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
275
self.get_file_test(btree)
277
def test_get_file2(self):
278
"""Get file contents, with patch-compatibile renames"""
279
btree = self.make_tree_3()
280
btree.contents_by_id = False
281
mod_patch = self.unified_diff([], ["Lemon\n"])
282
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
283
mod_patch = self.unified_diff([], ["Hello\n"])
284
btree.note_patch("grandparent/alt_parent/file", mod_patch)
285
self.get_file_test(btree)
287
def test_delete(self):
289
btree = self.make_tree_1()[0]
290
self.assertEqual(btree.get_file("c").read(), "Hello\n")
291
btree.note_deletion("grandparent/parent/file")
292
assert btree.id2path("c") is None
293
assert btree.path2id("grandparent/parent/file") is None
295
def sorted_ids(self, tree):
300
def test_iteration(self):
301
"""Ensure that iteration through ids works properly"""
302
btree = self.make_tree_1()[0]
303
self.assertEqual(self.sorted_ids(btree),
304
[inventory.ROOT_ID, 'a', 'b', 'c', 'd'])
305
btree.note_deletion("grandparent/parent/file")
306
btree.note_id("e", "grandparent/alt_parent/fool", kind="directory")
307
btree.note_last_changed("grandparent/alt_parent/fool",
309
self.assertEqual(self.sorted_ids(btree),
310
[inventory.ROOT_ID, 'a', 'b', 'd', 'e'])
313
class BundleTester1(TestCaseWithTransport):
315
def test_mismatched_bundle(self):
316
format = bzrdir.BzrDirMetaFormat1()
317
format.repository_format = knitrepo.RepositoryFormatKnit3()
318
serializer = BundleSerializerV08('0.8')
319
b = self.make_branch('.', format=format)
320
self.assertRaises(errors.IncompatibleBundleFormat, serializer.write,
321
b.repository, [], {}, StringIO())
323
def test_matched_bundle(self):
324
"""Don't raise IncompatibleBundleFormat for knit2 and bundle0.9"""
325
format = bzrdir.BzrDirMetaFormat1()
326
format.repository_format = knitrepo.RepositoryFormatKnit3()
327
serializer = BundleSerializerV09('0.9')
328
b = self.make_branch('.', format=format)
329
serializer.write(b.repository, [], {}, StringIO())
331
def test_mismatched_model(self):
332
"""Try copying a bundle from knit2 to knit1"""
333
format = bzrdir.BzrDirMetaFormat1()
334
format.repository_format = knitrepo.RepositoryFormatKnit3()
335
source = self.make_branch_and_tree('source', format=format)
336
source.commit('one', rev_id='one-id')
337
source.commit('two', rev_id='two-id')
339
write_bundle(source.branch.repository, 'two-id', 'null:', text,
343
format = bzrdir.BzrDirMetaFormat1()
344
format.repository_format = knitrepo.RepositoryFormatKnit1()
345
target = self.make_branch('target', format=format)
346
self.assertRaises(errors.IncompatibleRevision, install_bundle,
347
target.repository, read_bundle(text))
350
class BundleTester(object):
352
def bzrdir_format(self):
353
format = bzrdir.BzrDirMetaFormat1()
354
format.repository_format = knitrepo.RepositoryFormatKnit1()
357
def make_branch_and_tree(self, path, format=None):
359
format = self.bzrdir_format()
360
return TestCaseWithTransport.make_branch_and_tree(self, path, format)
362
def make_branch(self, path, format=None):
364
format = self.bzrdir_format()
365
return TestCaseWithTransport.make_branch(self, path, format)
367
def create_bundle_text(self, base_rev_id, rev_id):
368
bundle_txt = StringIO()
369
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
370
bundle_txt, format=self.format)
372
self.assertEqual(bundle_txt.readline(),
373
'# Bazaar revision bundle v%s\n' % self.format)
374
self.assertEqual(bundle_txt.readline(), '#\n')
376
rev = self.b1.repository.get_revision(rev_id)
377
self.assertEqual(bundle_txt.readline().decode('utf-8'),
380
return bundle_txt, rev_ids
382
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
383
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
384
Make sure that the text generated is valid, and that it
385
can be applied against the base, and generate the same information.
387
:return: The in-memory bundle
389
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
391
# This should also validate the generated bundle
392
bundle = read_bundle(bundle_txt)
393
repository = self.b1.repository
394
for bundle_rev in bundle.real_revisions:
395
# These really should have already been checked when we read the
396
# bundle, since it computes the sha1 hash for the revision, which
397
# only will match if everything is okay, but lets be explicit about
399
branch_rev = repository.get_revision(bundle_rev.revision_id)
400
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
401
'timestamp', 'timezone', 'message', 'committer',
402
'parent_ids', 'properties'):
403
self.assertEqual(getattr(branch_rev, a),
404
getattr(bundle_rev, a))
405
self.assertEqual(len(branch_rev.parent_ids),
406
len(bundle_rev.parent_ids))
407
self.assertEqual(rev_ids,
408
[r.revision_id for r in bundle.real_revisions])
409
self.valid_apply_bundle(base_rev_id, bundle,
410
checkout_dir=checkout_dir)
414
def get_invalid_bundle(self, base_rev_id, rev_id):
415
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
416
Munge the text so that it's invalid.
418
:return: The in-memory bundle
420
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
421
new_text = bundle_txt.getvalue().replace('executable:no',
423
bundle_txt = StringIO(new_text)
424
bundle = read_bundle(bundle_txt)
425
self.valid_apply_bundle(base_rev_id, bundle)
428
def test_non_bundle(self):
429
self.assertRaises(NotABundle, read_bundle, StringIO('#!/bin/sh\n'))
431
def test_malformed(self):
432
self.assertRaises(BadBundle, read_bundle,
433
StringIO('# Bazaar revision bundle v'))
435
def test_crlf_bundle(self):
437
read_bundle(StringIO('# Bazaar revision bundle v0.8\r\n'))
439
# It is currently permitted for bundles with crlf line endings to
440
# make read_bundle raise a BadBundle, but this should be fixed.
441
# Anything else, especially NotABundle, is an error.
444
def get_checkout(self, rev_id, checkout_dir=None):
445
"""Get a new tree, with the specified revision in it.
448
if checkout_dir is None:
449
checkout_dir = tempfile.mkdtemp(prefix='test-branch-', dir='.')
451
if not os.path.exists(checkout_dir):
452
os.mkdir(checkout_dir)
453
tree = self.make_branch_and_tree(checkout_dir)
455
ancestors = write_bundle(self.b1.repository, rev_id, 'null:', s,
458
assert isinstance(s.getvalue(), str), (
459
"Bundle isn't a bytestring:\n %s..." % repr(s.getvalue())[:40])
460
install_bundle(tree.branch.repository, read_bundle(s))
461
for ancestor in ancestors:
462
old = self.b1.repository.revision_tree(ancestor)
463
new = tree.branch.repository.revision_tree(ancestor)
465
# Check that there aren't any inventory level changes
466
delta = new.changes_from(old)
467
self.assertFalse(delta.has_changed(),
468
'Revision %s not copied correctly.'
471
# Now check that the file contents are all correct
472
for inventory_id in old:
474
old_file = old.get_file(inventory_id)
479
self.assertEqual(old_file.read(),
480
new.get_file(inventory_id).read())
481
if not _mod_revision.is_null(rev_id):
482
rh = self.b1.revision_history()
483
tree.branch.set_revision_history(rh[:rh.index(rev_id)+1])
485
delta = tree.changes_from(self.b1.repository.revision_tree(rev_id))
486
self.assertFalse(delta.has_changed(),
487
'Working tree has modifications: %s' % delta)
490
def valid_apply_bundle(self, base_rev_id, info, checkout_dir=None):
491
"""Get the base revision, apply the changes, and make
492
sure everything matches the builtin branch.
494
to_tree = self.get_checkout(base_rev_id, checkout_dir=checkout_dir)
495
original_parents = to_tree.get_parent_ids()
496
repository = to_tree.branch.repository
497
original_parents = to_tree.get_parent_ids()
498
self.assertIs(repository.has_revision(base_rev_id), True)
499
for rev in info.real_revisions:
500
self.assert_(not repository.has_revision(rev.revision_id),
501
'Revision {%s} present before applying bundle'
503
merge_bundle(info, to_tree, True, Merge3Merger, False, False)
505
for rev in info.real_revisions:
506
self.assert_(repository.has_revision(rev.revision_id),
507
'Missing revision {%s} after applying bundle'
510
self.assert_(to_tree.branch.repository.has_revision(info.target))
511
# Do we also want to verify that all the texts have been added?
513
self.assertEqual(original_parents + [info.target],
514
to_tree.get_parent_ids())
516
rev = info.real_revisions[-1]
517
base_tree = self.b1.repository.revision_tree(rev.revision_id)
518
to_tree = to_tree.branch.repository.revision_tree(rev.revision_id)
520
# TODO: make sure the target tree is identical to base tree
521
# we might also check the working tree.
523
base_files = list(base_tree.list_files())
524
to_files = list(to_tree.list_files())
525
self.assertEqual(len(base_files), len(to_files))
526
for base_file, to_file in zip(base_files, to_files):
527
self.assertEqual(base_file, to_file)
529
for path, status, kind, fileid, entry in base_files:
530
# Check that the meta information is the same
531
self.assertEqual(base_tree.get_file_size(fileid),
532
to_tree.get_file_size(fileid))
533
self.assertEqual(base_tree.get_file_sha1(fileid),
534
to_tree.get_file_sha1(fileid))
535
# Check that the contents are the same
536
# This is pretty expensive
537
# self.assertEqual(base_tree.get_file(fileid).read(),
538
# to_tree.get_file(fileid).read())
540
def test_bundle(self):
541
self.tree1 = self.make_branch_and_tree('b1')
542
self.b1 = self.tree1.branch
544
open('b1/one', 'wb').write('one\n')
545
self.tree1.add('one')
546
self.tree1.commit('add one', rev_id='a@cset-0-1')
548
bundle = self.get_valid_bundle('null:', 'a@cset-0-1')
550
# Make sure we can handle files with spaces, tabs, other
555
, 'b1/dir/filein subdir.c'
556
, 'b1/dir/WithCaps.txt'
557
, 'b1/dir/ pre space'
560
, 'b1/sub/sub/nonempty.txt'
562
open('b1/sub/sub/emptyfile.txt', 'wb').close()
563
open('b1/dir/nolastnewline.txt', 'wb').write('bloop')
564
tt = TreeTransform(self.tree1)
565
tt.new_file('executable', tt.root, '#!/bin/sh\n', 'exe-1', True)
567
# have to fix length of file-id so that we can predictably rewrite
568
# a (length-prefixed) record containing it later.
569
self.tree1.add('with space.txt', 'withspace-id')
572
, 'dir/filein subdir.c'
575
, 'dir/nolastnewline.txt'
578
, 'sub/sub/nonempty.txt'
579
, 'sub/sub/emptyfile.txt'
581
self.tree1.commit('add whitespace', rev_id='a@cset-0-2')
583
bundle = self.get_valid_bundle('a@cset-0-1', 'a@cset-0-2')
585
# Check a rollup bundle
586
bundle = self.get_valid_bundle('null:', 'a@cset-0-2')
590
['sub/sub/nonempty.txt'
591
, 'sub/sub/emptyfile.txt'
594
tt = TreeTransform(self.tree1)
595
trans_id = tt.trans_id_tree_file_id('exe-1')
596
tt.set_executability(False, trans_id)
598
self.tree1.commit('removed', rev_id='a@cset-0-3')
600
bundle = self.get_valid_bundle('a@cset-0-2', 'a@cset-0-3')
601
self.assertRaises((TestamentMismatch,
602
errors.VersionedFileInvalidChecksum), self.get_invalid_bundle,
603
'a@cset-0-2', 'a@cset-0-3')
604
# Check a rollup bundle
605
bundle = self.get_valid_bundle('null:', 'a@cset-0-3')
607
# Now move the directory
608
self.tree1.rename_one('dir', 'sub/dir')
609
self.tree1.commit('rename dir', rev_id='a@cset-0-4')
611
bundle = self.get_valid_bundle('a@cset-0-3', 'a@cset-0-4')
612
# Check a rollup bundle
613
bundle = self.get_valid_bundle('null:', 'a@cset-0-4')
616
open('b1/sub/dir/WithCaps.txt', 'ab').write('\nAdding some text\n')
617
open('b1/sub/dir/ pre space', 'ab').write(
618
'\r\nAdding some\r\nDOS format lines\r\n')
619
open('b1/sub/dir/nolastnewline.txt', 'ab').write('\n')
620
self.tree1.rename_one('sub/dir/ pre space',
622
self.tree1.commit('Modified files', rev_id='a@cset-0-5')
623
bundle = self.get_valid_bundle('a@cset-0-4', 'a@cset-0-5')
625
self.tree1.rename_one('sub/dir/WithCaps.txt', 'temp')
626
self.tree1.rename_one('with space.txt', 'WithCaps.txt')
627
self.tree1.rename_one('temp', 'with space.txt')
628
self.tree1.commit(u'swap filenames', rev_id='a@cset-0-6',
630
bundle = self.get_valid_bundle('a@cset-0-5', 'a@cset-0-6')
631
other = self.get_checkout('a@cset-0-5')
632
tree1_inv = self.tree1.branch.repository.get_inventory_xml(
634
tree2_inv = other.branch.repository.get_inventory_xml('a@cset-0-5')
635
self.assertEqualDiff(tree1_inv, tree2_inv)
636
other.rename_one('sub/dir/nolastnewline.txt', 'sub/nolastnewline.txt')
637
other.commit('rename file', rev_id='a@cset-0-6b')
638
self.tree1.merge_from_branch(other.branch)
639
self.tree1.commit(u'Merge', rev_id='a@cset-0-7',
641
bundle = self.get_valid_bundle('a@cset-0-6', 'a@cset-0-7')
643
def test_symlink_bundle(self):
644
if not has_symlinks():
645
raise TestSkipped("No symlink support")
646
self.tree1 = self.make_branch_and_tree('b1')
647
self.b1 = self.tree1.branch
648
tt = TreeTransform(self.tree1)
649
tt.new_symlink('link', tt.root, 'bar/foo', 'link-1')
651
self.tree1.commit('add symlink', rev_id='l@cset-0-1')
652
self.get_valid_bundle('null:', 'l@cset-0-1')
653
tt = TreeTransform(self.tree1)
654
trans_id = tt.trans_id_tree_file_id('link-1')
655
tt.adjust_path('link2', tt.root, trans_id)
656
tt.delete_contents(trans_id)
657
tt.create_symlink('mars', trans_id)
659
self.tree1.commit('rename and change symlink', rev_id='l@cset-0-2')
660
self.get_valid_bundle('l@cset-0-1', 'l@cset-0-2')
661
tt = TreeTransform(self.tree1)
662
trans_id = tt.trans_id_tree_file_id('link-1')
663
tt.delete_contents(trans_id)
664
tt.create_symlink('jupiter', trans_id)
666
self.tree1.commit('just change symlink target', rev_id='l@cset-0-3')
667
self.get_valid_bundle('l@cset-0-2', 'l@cset-0-3')
668
tt = TreeTransform(self.tree1)
669
trans_id = tt.trans_id_tree_file_id('link-1')
670
tt.delete_contents(trans_id)
672
self.tree1.commit('Delete symlink', rev_id='l@cset-0-4')
673
self.get_valid_bundle('l@cset-0-3', 'l@cset-0-4')
675
def test_binary_bundle(self):
676
self.tree1 = self.make_branch_and_tree('b1')
677
self.b1 = self.tree1.branch
678
tt = TreeTransform(self.tree1)
681
tt.new_file('file', tt.root, '\x00\n\x00\r\x01\n\x02\r\xff', 'binary-1')
682
tt.new_file('file2', tt.root, '\x01\n\x02\r\x03\n\x04\r\xff',
685
self.tree1.commit('add binary', rev_id='b@cset-0-1')
686
self.get_valid_bundle('null:', 'b@cset-0-1')
689
tt = TreeTransform(self.tree1)
690
trans_id = tt.trans_id_tree_file_id('binary-1')
691
tt.delete_contents(trans_id)
693
self.tree1.commit('delete binary', rev_id='b@cset-0-2')
694
self.get_valid_bundle('b@cset-0-1', 'b@cset-0-2')
697
tt = TreeTransform(self.tree1)
698
trans_id = tt.trans_id_tree_file_id('binary-2')
699
tt.adjust_path('file3', tt.root, trans_id)
700
tt.delete_contents(trans_id)
701
tt.create_file('file\rcontents\x00\n\x00', trans_id)
703
self.tree1.commit('rename and modify binary', rev_id='b@cset-0-3')
704
self.get_valid_bundle('b@cset-0-2', 'b@cset-0-3')
707
tt = TreeTransform(self.tree1)
708
trans_id = tt.trans_id_tree_file_id('binary-2')
709
tt.delete_contents(trans_id)
710
tt.create_file('\x00file\rcontents', trans_id)
712
self.tree1.commit('just modify binary', rev_id='b@cset-0-4')
713
self.get_valid_bundle('b@cset-0-3', 'b@cset-0-4')
716
self.get_valid_bundle('null:', 'b@cset-0-4')
718
def test_last_modified(self):
719
self.tree1 = self.make_branch_and_tree('b1')
720
self.b1 = self.tree1.branch
721
tt = TreeTransform(self.tree1)
722
tt.new_file('file', tt.root, 'file', 'file')
724
self.tree1.commit('create file', rev_id='a@lmod-0-1')
726
tt = TreeTransform(self.tree1)
727
trans_id = tt.trans_id_tree_file_id('file')
728
tt.delete_contents(trans_id)
729
tt.create_file('file2', trans_id)
731
self.tree1.commit('modify text', rev_id='a@lmod-0-2a')
733
other = self.get_checkout('a@lmod-0-1')
734
tt = TreeTransform(other)
735
trans_id = tt.trans_id_tree_file_id('file')
736
tt.delete_contents(trans_id)
737
tt.create_file('file2', trans_id)
739
other.commit('modify text in another tree', rev_id='a@lmod-0-2b')
740
self.tree1.merge_from_branch(other.branch)
741
self.tree1.commit(u'Merge', rev_id='a@lmod-0-3',
743
self.tree1.commit(u'Merge', rev_id='a@lmod-0-4')
744
bundle = self.get_valid_bundle('a@lmod-0-2a', 'a@lmod-0-4')
746
def test_hide_history(self):
747
self.tree1 = self.make_branch_and_tree('b1')
748
self.b1 = self.tree1.branch
750
open('b1/one', 'wb').write('one\n')
751
self.tree1.add('one')
752
self.tree1.commit('add file', rev_id='a@cset-0-1')
753
open('b1/one', 'wb').write('two\n')
754
self.tree1.commit('modify', rev_id='a@cset-0-2')
755
open('b1/one', 'wb').write('three\n')
756
self.tree1.commit('modify', rev_id='a@cset-0-3')
757
bundle_file = StringIO()
758
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-3',
759
'a@cset-0-1', bundle_file, format=self.format)
760
self.assertNotContainsRe(bundle_file.getvalue(), '\btwo\b')
761
self.assertContainsRe(self.get_raw(bundle_file), 'one')
762
self.assertContainsRe(self.get_raw(bundle_file), 'three')
764
def test_bundle_same_basis(self):
765
"""Ensure using the basis as the target doesn't cause an error"""
766
self.tree1 = self.make_branch_and_tree('b1')
767
self.tree1.commit('add file', rev_id='a@cset-0-1')
768
bundle_file = StringIO()
769
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-1',
770
'a@cset-0-1', bundle_file)
773
def get_raw(bundle_file):
774
return bundle_file.getvalue()
776
def test_unicode_bundle(self):
777
# Handle international characters
780
f = open(u'b1/with Dod\xe9', 'wb')
781
except UnicodeEncodeError:
782
raise TestSkipped("Filesystem doesn't support unicode")
784
self.tree1 = self.make_branch_and_tree('b1')
785
self.b1 = self.tree1.branch
788
u'With international man of mystery\n'
789
u'William Dod\xe9\n').encode('utf-8'))
792
self.tree1.add([u'with Dod\xe9'], ['withdod-id'])
793
self.tree1.commit(u'i18n commit from William Dod\xe9',
794
rev_id='i18n-1', committer=u'William Dod\xe9')
796
if sys.platform == 'darwin':
797
from bzrlib.workingtree import WorkingTree3
798
if type(self.tree1) is WorkingTree3:
799
self.knownFailure("Mac OSX doesn't preserve unicode"
800
" combining characters"
801
" and WorkingTree3 failed to detect"
804
# On Mac the '\xe9' gets changed to 'e\u0301'
805
self.assertEqual([u'.bzr', u'with Dode\u0301'],
806
sorted(os.listdir(u'b1')))
807
delta = self.tree1.changes_from(self.tree1.basis_tree())
808
self.assertEqual([(u'with Dod\xe9', 'withdod-id', 'file')],
810
self.knownFailure("Mac OSX doesn't preserve unicode"
811
" combining characters.")
814
bundle = self.get_valid_bundle('null:', 'i18n-1')
817
f = open(u'b1/with Dod\xe9', 'wb')
818
f.write(u'Modified \xb5\n'.encode('utf8'))
820
self.tree1.commit(u'modified', rev_id='i18n-2')
822
bundle = self.get_valid_bundle('i18n-1', 'i18n-2')
825
self.tree1.rename_one(u'with Dod\xe9', u'B\xe5gfors')
826
self.tree1.commit(u'renamed, the new i18n man', rev_id='i18n-3',
827
committer=u'Erik B\xe5gfors')
829
bundle = self.get_valid_bundle('i18n-2', 'i18n-3')
832
self.tree1.remove([u'B\xe5gfors'])
833
self.tree1.commit(u'removed', rev_id='i18n-4')
835
bundle = self.get_valid_bundle('i18n-3', 'i18n-4')
838
bundle = self.get_valid_bundle('null:', 'i18n-4')
841
def test_whitespace_bundle(self):
842
if sys.platform in ('win32', 'cygwin'):
843
raise TestSkipped('Windows doesn\'t support filenames'
844
' with tabs or trailing spaces')
845
self.tree1 = self.make_branch_and_tree('b1')
846
self.b1 = self.tree1.branch
848
self.build_tree(['b1/trailing space '])
849
self.tree1.add(['trailing space '])
850
# TODO: jam 20060701 Check for handling files with '\t' characters
851
# once we actually support them
854
self.tree1.commit('funky whitespace', rev_id='white-1')
856
bundle = self.get_valid_bundle('null:', 'white-1')
859
open('b1/trailing space ', 'ab').write('add some text\n')
860
self.tree1.commit('add text', rev_id='white-2')
862
bundle = self.get_valid_bundle('white-1', 'white-2')
865
self.tree1.rename_one('trailing space ', ' start and end space ')
866
self.tree1.commit('rename', rev_id='white-3')
868
bundle = self.get_valid_bundle('white-2', 'white-3')
871
self.tree1.remove([' start and end space '])
872
self.tree1.commit('removed', rev_id='white-4')
874
bundle = self.get_valid_bundle('white-3', 'white-4')
876
# Now test a complet roll-up
877
bundle = self.get_valid_bundle('null:', 'white-4')
879
def test_alt_timezone_bundle(self):
880
self.tree1 = self.make_branch_and_memory_tree('b1')
881
self.b1 = self.tree1.branch
882
builder = treebuilder.TreeBuilder()
884
self.tree1.lock_write()
885
builder.start_tree(self.tree1)
886
builder.build(['newfile'])
887
builder.finish_tree()
889
# Asia/Colombo offset = 5 hours 30 minutes
890
self.tree1.commit('non-hour offset timezone', rev_id='tz-1',
891
timezone=19800, timestamp=1152544886.0)
893
bundle = self.get_valid_bundle('null:', 'tz-1')
895
rev = bundle.revisions[0]
896
self.assertEqual('Mon 2006-07-10 20:51:26.000000000 +0530', rev.date)
897
self.assertEqual(19800, rev.timezone)
898
self.assertEqual(1152544886.0, rev.timestamp)
901
def test_bundle_root_id(self):
902
self.tree1 = self.make_branch_and_tree('b1')
903
self.b1 = self.tree1.branch
904
self.tree1.commit('message', rev_id='revid1')
905
bundle = self.get_valid_bundle('null:', 'revid1')
906
tree = self.get_bundle_tree(bundle, 'revid1')
907
self.assertEqual('revid1', tree.inventory.root.revision)
909
def test_install_revisions(self):
910
self.tree1 = self.make_branch_and_tree('b1')
911
self.b1 = self.tree1.branch
912
self.tree1.commit('message', rev_id='rev2a')
913
bundle = self.get_valid_bundle('null:', 'rev2a')
914
branch2 = self.make_branch('b2')
915
self.assertFalse(branch2.repository.has_revision('rev2a'))
916
target_revision = bundle.install_revisions(branch2.repository)
917
self.assertTrue(branch2.repository.has_revision('rev2a'))
918
self.assertEqual('rev2a', target_revision)
920
def test_bundle_empty_property(self):
921
"""Test serializing revision properties with an empty value."""
922
tree = self.make_branch_and_memory_tree('tree')
924
self.addCleanup(tree.unlock)
925
tree.add([''], ['TREE_ROOT'])
926
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
927
self.b1 = tree.branch
928
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
929
bundle = read_bundle(bundle_sio)
930
revision_info = bundle.revisions[0]
931
self.assertEqual('rev1', revision_info.revision_id)
932
rev = revision_info.as_revision()
933
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
936
def test_bundle_sorted_properties(self):
937
"""For stability the writer should write properties in sorted order."""
938
tree = self.make_branch_and_memory_tree('tree')
940
self.addCleanup(tree.unlock)
942
tree.add([''], ['TREE_ROOT'])
943
tree.commit('One', rev_id='rev1',
944
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
945
self.b1 = tree.branch
946
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
947
bundle = read_bundle(bundle_sio)
948
revision_info = bundle.revisions[0]
949
self.assertEqual('rev1', revision_info.revision_id)
950
rev = revision_info.as_revision()
951
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
952
'd':'1'}, rev.properties)
954
def test_bundle_unicode_properties(self):
955
"""We should be able to round trip a non-ascii property."""
956
tree = self.make_branch_and_memory_tree('tree')
958
self.addCleanup(tree.unlock)
960
tree.add([''], ['TREE_ROOT'])
961
# Revisions themselves do not require anything about revision property
962
# keys, other than that they are a basestring, and do not contain
964
# However, Testaments assert than they are str(), and thus should not
966
tree.commit('One', rev_id='rev1',
967
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
968
self.b1 = tree.branch
969
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
970
bundle = read_bundle(bundle_sio)
971
revision_info = bundle.revisions[0]
972
self.assertEqual('rev1', revision_info.revision_id)
973
rev = revision_info.as_revision()
974
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
975
'alpha':u'\u03b1'}, rev.properties)
977
def test_bundle_with_ghosts(self):
978
tree = self.make_branch_and_tree('tree')
979
self.b1 = tree.branch
980
self.build_tree_contents([('tree/file', 'content1')])
983
self.build_tree_contents([('tree/file', 'content2')])
984
tree.add_parent_tree_id('ghost')
985
tree.commit('rev2', rev_id='rev2')
986
bundle = self.get_valid_bundle('null:', 'rev2')
988
def make_simple_tree(self, format=None):
989
tree = self.make_branch_and_tree('b1', format=format)
990
self.b1 = tree.branch
991
self.build_tree(['b1/file'])
995
def test_across_serializers(self):
996
tree = self.make_simple_tree('knit')
997
tree.commit('hello', rev_id='rev1')
998
tree.commit('hello', rev_id='rev2')
999
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1000
repo = self.make_repository('repo', format='dirstate-with-subtree')
1001
bundle.install_revisions(repo)
1002
inv_text = repo.get_inventory_xml('rev2')
1003
self.assertNotContainsRe(inv_text, 'format="5"')
1004
self.assertContainsRe(inv_text, 'format="7"')
1006
def test_across_models(self):
1007
tree = self.make_simple_tree('knit')
1008
tree.commit('hello', rev_id='rev1')
1009
tree.commit('hello', rev_id='rev2')
1010
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1011
repo = self.make_repository('repo', format='dirstate-with-subtree')
1012
bundle.install_revisions(repo)
1013
inv = repo.get_inventory('rev2')
1014
self.assertEqual('rev2', inv.root.revision)
1015
root_vf = repo.weave_store.get_weave(inv.root.file_id,
1016
repo.get_transaction())
1017
self.assertEqual(root_vf.versions(), ['rev1', 'rev2'])
1019
def test_across_models_incompatible(self):
1020
tree = self.make_simple_tree('dirstate-with-subtree')
1021
tree.commit('hello', rev_id='rev1')
1022
tree.commit('hello', rev_id='rev2')
1024
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1025
except errors.IncompatibleBundleFormat:
1026
raise TestSkipped("Format 0.8 doesn't work with knit3")
1027
repo = self.make_repository('repo', format='knit')
1028
bundle.install_revisions(repo)
1030
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1031
self.assertRaises(errors.IncompatibleRevision,
1032
bundle.install_revisions, repo)
1034
def test_get_merge_request(self):
1035
tree = self.make_simple_tree()
1036
tree.commit('hello', rev_id='rev1')
1037
tree.commit('hello', rev_id='rev2')
1038
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1039
result = bundle.get_merge_request(tree.branch.repository)
1040
self.assertEqual((None, 'rev1', 'inapplicable'), result)
1042
def test_with_subtree(self):
1043
tree = self.make_branch_and_tree('tree',
1044
format='dirstate-with-subtree')
1045
self.b1 = tree.branch
1046
subtree = self.make_branch_and_tree('tree/subtree',
1047
format='dirstate-with-subtree')
1049
tree.commit('hello', rev_id='rev1')
1051
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1052
except errors.IncompatibleBundleFormat:
1053
raise TestSkipped("Format 0.8 doesn't work with knit3")
1054
if isinstance(bundle, v09.BundleInfo09):
1055
raise TestSkipped("Format 0.9 doesn't work with subtrees")
1056
repo = self.make_repository('repo', format='knit')
1057
self.assertRaises(errors.IncompatibleRevision,
1058
bundle.install_revisions, repo)
1059
repo2 = self.make_repository('repo2', format='dirstate-with-subtree')
1060
bundle.install_revisions(repo2)
1062
def test_revision_id_with_slash(self):
1063
self.tree1 = self.make_branch_and_tree('tree')
1064
self.b1 = self.tree1.branch
1066
self.tree1.commit('Revision/id/with/slashes', rev_id='rev/id')
1068
raise TestSkipped("Repository doesn't support revision ids with"
1070
bundle = self.get_valid_bundle('null:', 'rev/id')
1072
def test_skip_file(self):
1073
"""Make sure we don't accidentally write to the wrong versionedfile"""
1074
self.tree1 = self.make_branch_and_tree('tree')
1075
self.b1 = self.tree1.branch
1076
# rev1 is not present in bundle, done by fetch
1077
self.build_tree_contents([('tree/file2', 'contents1')])
1078
self.tree1.add('file2', 'file2-id')
1079
self.tree1.commit('rev1', rev_id='reva')
1080
self.build_tree_contents([('tree/file3', 'contents2')])
1081
# rev2 is present in bundle, and done by fetch
1082
# having file1 in the bunle causes file1's versionedfile to be opened.
1083
self.tree1.add('file3', 'file3-id')
1084
self.tree1.commit('rev2')
1085
# Updating file2 should not cause an attempt to add to file1's vf
1086
target = self.tree1.bzrdir.sprout('target').open_workingtree()
1087
self.build_tree_contents([('tree/file2', 'contents3')])
1088
self.tree1.commit('rev3', rev_id='rev3')
1089
bundle = self.get_valid_bundle('reva', 'rev3')
1090
if getattr(bundle, 'get_bundle_reader', None) is None:
1091
raise TestSkipped('Bundle format cannot provide reader')
1092
# be sure that file1 comes before file2
1093
for b, m, k, r, f in bundle.get_bundle_reader().iter_records():
1096
self.assertNotEqual(f, 'file2-id')
1097
bundle.install_revisions(target.branch.repository)
1100
class V08BundleTester(BundleTester, TestCaseWithTransport):
1104
def test_bundle_empty_property(self):
1105
"""Test serializing revision properties with an empty value."""
1106
tree = self.make_branch_and_memory_tree('tree')
1108
self.addCleanup(tree.unlock)
1109
tree.add([''], ['TREE_ROOT'])
1110
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1111
self.b1 = tree.branch
1112
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1113
self.assertContainsRe(bundle_sio.getvalue(),
1115
'# branch-nick: tree\n'
1119
bundle = read_bundle(bundle_sio)
1120
revision_info = bundle.revisions[0]
1121
self.assertEqual('rev1', revision_info.revision_id)
1122
rev = revision_info.as_revision()
1123
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1126
def get_bundle_tree(self, bundle, revision_id):
1127
repository = self.make_repository('repo')
1128
return bundle.revision_tree(repository, 'revid1')
1130
def test_bundle_empty_property_alt(self):
1131
"""Test serializing revision properties with an empty value.
1133
Older readers had a bug when reading an empty property.
1134
They assumed that all keys ended in ': \n'. However they would write an
1135
empty value as ':\n'. This tests make sure that all newer bzr versions
1136
can handle th second form.
1138
tree = self.make_branch_and_memory_tree('tree')
1140
self.addCleanup(tree.unlock)
1141
tree.add([''], ['TREE_ROOT'])
1142
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1143
self.b1 = tree.branch
1144
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1145
txt = bundle_sio.getvalue()
1146
loc = txt.find('# empty: ') + len('# empty:')
1147
# Create a new bundle, which strips the trailing space after empty
1148
bundle_sio = StringIO(txt[:loc] + txt[loc+1:])
1150
self.assertContainsRe(bundle_sio.getvalue(),
1152
'# branch-nick: tree\n'
1156
bundle = read_bundle(bundle_sio)
1157
revision_info = bundle.revisions[0]
1158
self.assertEqual('rev1', revision_info.revision_id)
1159
rev = revision_info.as_revision()
1160
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1163
def test_bundle_sorted_properties(self):
1164
"""For stability the writer should write properties in sorted order."""
1165
tree = self.make_branch_and_memory_tree('tree')
1167
self.addCleanup(tree.unlock)
1169
tree.add([''], ['TREE_ROOT'])
1170
tree.commit('One', rev_id='rev1',
1171
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1172
self.b1 = tree.branch
1173
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1174
self.assertContainsRe(bundle_sio.getvalue(),
1178
'# branch-nick: tree\n'
1182
bundle = read_bundle(bundle_sio)
1183
revision_info = bundle.revisions[0]
1184
self.assertEqual('rev1', revision_info.revision_id)
1185
rev = revision_info.as_revision()
1186
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1187
'd':'1'}, rev.properties)
1189
def test_bundle_unicode_properties(self):
1190
"""We should be able to round trip a non-ascii property."""
1191
tree = self.make_branch_and_memory_tree('tree')
1193
self.addCleanup(tree.unlock)
1195
tree.add([''], ['TREE_ROOT'])
1196
# Revisions themselves do not require anything about revision property
1197
# keys, other than that they are a basestring, and do not contain
1199
# However, Testaments assert than they are str(), and thus should not
1201
tree.commit('One', rev_id='rev1',
1202
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1203
self.b1 = tree.branch
1204
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1205
self.assertContainsRe(bundle_sio.getvalue(),
1207
'# alpha: \xce\xb1\n'
1208
'# branch-nick: tree\n'
1209
'# omega: \xce\xa9\n'
1211
bundle = read_bundle(bundle_sio)
1212
revision_info = bundle.revisions[0]
1213
self.assertEqual('rev1', revision_info.revision_id)
1214
rev = revision_info.as_revision()
1215
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1216
'alpha':u'\u03b1'}, rev.properties)
1219
class V09BundleKnit2Tester(V08BundleTester):
1223
def bzrdir_format(self):
1224
format = bzrdir.BzrDirMetaFormat1()
1225
format.repository_format = knitrepo.RepositoryFormatKnit3()
1229
class V09BundleKnit1Tester(V08BundleTester):
1233
def bzrdir_format(self):
1234
format = bzrdir.BzrDirMetaFormat1()
1235
format.repository_format = knitrepo.RepositoryFormatKnit1()
1239
class V4BundleTester(BundleTester, TestCaseWithTransport):
1243
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
1244
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1245
Make sure that the text generated is valid, and that it
1246
can be applied against the base, and generate the same information.
1248
:return: The in-memory bundle
1250
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1252
# This should also validate the generated bundle
1253
bundle = read_bundle(bundle_txt)
1254
repository = self.b1.repository
1255
for bundle_rev in bundle.real_revisions:
1256
# These really should have already been checked when we read the
1257
# bundle, since it computes the sha1 hash for the revision, which
1258
# only will match if everything is okay, but lets be explicit about
1260
branch_rev = repository.get_revision(bundle_rev.revision_id)
1261
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
1262
'timestamp', 'timezone', 'message', 'committer',
1263
'parent_ids', 'properties'):
1264
self.assertEqual(getattr(branch_rev, a),
1265
getattr(bundle_rev, a))
1266
self.assertEqual(len(branch_rev.parent_ids),
1267
len(bundle_rev.parent_ids))
1268
self.assertEqual(set(rev_ids),
1269
set([r.revision_id for r in bundle.real_revisions]))
1270
self.valid_apply_bundle(base_rev_id, bundle,
1271
checkout_dir=checkout_dir)
1275
def get_invalid_bundle(self, base_rev_id, rev_id):
1276
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1277
Munge the text so that it's invalid.
1279
:return: The in-memory bundle
1281
from bzrlib.bundle import serializer
1282
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1283
new_text = self.get_raw(StringIO(''.join(bundle_txt)))
1284
new_text = new_text.replace('<file file_id="exe-1"',
1285
'<file executable="y" file_id="exe-1"')
1286
new_text = new_text.replace('B222', 'B237')
1287
bundle_txt = StringIO()
1288
bundle_txt.write(serializer._get_bundle_header('4'))
1289
bundle_txt.write('\n')
1290
bundle_txt.write(new_text.encode('bz2'))
1292
bundle = read_bundle(bundle_txt)
1293
self.valid_apply_bundle(base_rev_id, bundle)
1296
def create_bundle_text(self, base_rev_id, rev_id):
1297
bundle_txt = StringIO()
1298
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
1299
bundle_txt, format=self.format)
1301
self.assertEqual(bundle_txt.readline(),
1302
'# Bazaar revision bundle v%s\n' % self.format)
1303
self.assertEqual(bundle_txt.readline(), '#\n')
1304
rev = self.b1.repository.get_revision(rev_id)
1306
return bundle_txt, rev_ids
1308
def get_bundle_tree(self, bundle, revision_id):
1309
repository = self.make_repository('repo')
1310
bundle.install_revisions(repository)
1311
return repository.revision_tree(revision_id)
1313
def test_creation(self):
1314
tree = self.make_branch_and_tree('tree')
1315
self.build_tree_contents([('tree/file', 'contents1\nstatic\n')])
1316
tree.add('file', 'fileid-2')
1317
tree.commit('added file', rev_id='rev1')
1318
self.build_tree_contents([('tree/file', 'contents2\nstatic\n')])
1319
tree.commit('changed file', rev_id='rev2')
1321
serializer = BundleSerializerV4('1.0')
1322
serializer.write(tree.branch.repository, ['rev1', 'rev2'], {}, s)
1324
tree2 = self.make_branch_and_tree('target')
1325
target_repo = tree2.branch.repository
1326
install_bundle(target_repo, serializer.read(s))
1327
vf = target_repo.weave_store.get_weave('fileid-2',
1328
target_repo.get_transaction())
1329
self.assertEqual('contents1\nstatic\n', vf.get_text('rev1'))
1330
self.assertEqual('contents2\nstatic\n', vf.get_text('rev2'))
1331
rtree = target_repo.revision_tree('rev2')
1332
inventory_vf = target_repo.get_inventory_weave()
1333
self.assertEqual(['rev1'], inventory_vf.get_parents('rev2'))
1334
self.assertEqual('changed file',
1335
target_repo.get_revision('rev2').message)
1338
def get_raw(bundle_file):
1340
line = bundle_file.readline()
1341
line = bundle_file.readline()
1342
lines = bundle_file.readlines()
1343
return ''.join(lines).decode('bz2')
1345
def test_copy_signatures(self):
1346
tree_a = self.make_branch_and_tree('tree_a')
1348
import bzrlib.commit as commit
1349
oldstrategy = bzrlib.gpg.GPGStrategy
1350
branch = tree_a.branch
1351
repo_a = branch.repository
1352
tree_a.commit("base", allow_pointless=True, rev_id='A')
1353
self.failIf(branch.repository.has_signature_for_revision_id('A'))
1355
from bzrlib.testament import Testament
1356
# monkey patch gpg signing mechanism
1357
bzrlib.gpg.GPGStrategy = bzrlib.gpg.LoopbackGPGStrategy
1358
new_config = test_commit.MustSignConfig(branch)
1359
commit.Commit(config=new_config).commit(message="base",
1360
allow_pointless=True,
1362
working_tree=tree_a)
1364
return bzrlib.gpg.LoopbackGPGStrategy(None).sign(text)
1365
self.assertTrue(repo_a.has_signature_for_revision_id('B'))
1367
bzrlib.gpg.GPGStrategy = oldstrategy
1368
tree_b = self.make_branch_and_tree('tree_b')
1369
repo_b = tree_b.branch.repository
1371
serializer = BundleSerializerV4('4')
1372
serializer.write(tree_a.branch.repository, ['A', 'B'], {}, s)
1374
install_bundle(repo_b, serializer.read(s))
1375
self.assertTrue(repo_b.has_signature_for_revision_id('B'))
1376
self.assertEqual(repo_b.get_signature_text('B'),
1377
repo_a.get_signature_text('B'))
1379
# ensure repeat installs are harmless
1380
install_bundle(repo_b, serializer.read(s))
1383
class V4WeaveBundleTester(V4BundleTester):
1385
def bzrdir_format(self):
1389
class MungedBundleTester(object):
1391
def build_test_bundle(self):
1392
wt = self.make_branch_and_tree('b1')
1394
self.build_tree(['b1/one'])
1396
wt.commit('add one', rev_id='a@cset-0-1')
1397
self.build_tree(['b1/two'])
1399
wt.commit('add two', rev_id='a@cset-0-2',
1400
revprops={'branch-nick':'test'})
1402
bundle_txt = StringIO()
1403
rev_ids = write_bundle(wt.branch.repository, 'a@cset-0-2',
1404
'a@cset-0-1', bundle_txt, self.format)
1405
self.assertEqual(set(['a@cset-0-2']), set(rev_ids))
1406
bundle_txt.seek(0, 0)
1409
def check_valid(self, bundle):
1410
"""Check that after whatever munging, the final object is valid."""
1411
self.assertEqual(['a@cset-0-2'],
1412
[r.revision_id for r in bundle.real_revisions])
1414
def test_extra_whitespace(self):
1415
bundle_txt = self.build_test_bundle()
1417
# Seek to the end of the file
1418
# Adding one extra newline used to give us
1419
# TypeError: float() argument must be a string or a number
1420
bundle_txt.seek(0, 2)
1421
bundle_txt.write('\n')
1424
bundle = read_bundle(bundle_txt)
1425
self.check_valid(bundle)
1427
def test_extra_whitespace_2(self):
1428
bundle_txt = self.build_test_bundle()
1430
# Seek to the end of the file
1431
# Adding two extra newlines used to give us
1432
# MalformedPatches: The first line of all patches should be ...
1433
bundle_txt.seek(0, 2)
1434
bundle_txt.write('\n\n')
1437
bundle = read_bundle(bundle_txt)
1438
self.check_valid(bundle)
1441
class MungedBundleTesterV09(TestCaseWithTransport, MungedBundleTester):
1445
def test_missing_trailing_whitespace(self):
1446
bundle_txt = self.build_test_bundle()
1448
# Remove a trailing newline, it shouldn't kill the parser
1449
raw = bundle_txt.getvalue()
1450
# The contents of the bundle don't have to be this, but this
1451
# test is concerned with the exact case where the serializer
1452
# creates a blank line at the end, and fails if that
1454
self.assertEqual('\n\n', raw[-2:])
1455
bundle_txt = StringIO(raw[:-1])
1457
bundle = read_bundle(bundle_txt)
1458
self.check_valid(bundle)
1460
def test_opening_text(self):
1461
bundle_txt = self.build_test_bundle()
1463
bundle_txt = StringIO("Some random\nemail comments\n"
1464
+ bundle_txt.getvalue())
1466
bundle = read_bundle(bundle_txt)
1467
self.check_valid(bundle)
1469
def test_trailing_text(self):
1470
bundle_txt = self.build_test_bundle()
1472
bundle_txt = StringIO(bundle_txt.getvalue() +
1473
"Some trailing\nrandom\ntext\n")
1475
bundle = read_bundle(bundle_txt)
1476
self.check_valid(bundle)
1479
class MungedBundleTesterV4(TestCaseWithTransport, MungedBundleTester):
1484
class TestBundleWriterReader(TestCase):
1486
def test_roundtrip_record(self):
1487
fileobj = StringIO()
1488
writer = v4.BundleWriter(fileobj)
1490
writer.add_info_record(foo='bar')
1491
writer._add_record("Record body", {'parents': ['1', '3'],
1492
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1495
reader = v4.BundleReader(fileobj, stream_input=True)
1496
record_iter = reader.iter_records()
1497
record = record_iter.next()
1498
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1499
'info', None, None), record)
1500
record = record_iter.next()
1501
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1502
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1505
def test_roundtrip_record_memory_hungry(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=False)
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_encode_name(self):
1525
self.assertEqual('revision/rev1',
1526
v4.BundleWriter.encode_name('revision', 'rev1'))
1527
self.assertEqual('file/rev//1/file-id-1',
1528
v4.BundleWriter.encode_name('file', 'rev/1', 'file-id-1'))
1529
self.assertEqual('info',
1530
v4.BundleWriter.encode_name('info', None, None))
1532
def test_decode_name(self):
1533
self.assertEqual(('revision', 'rev1', None),
1534
v4.BundleReader.decode_name('revision/rev1'))
1535
self.assertEqual(('file', 'rev/1', 'file-id-1'),
1536
v4.BundleReader.decode_name('file/rev//1/file-id-1'))
1537
self.assertEqual(('info', None, None),
1538
v4.BundleReader.decode_name('info'))
1540
def test_too_many_names(self):
1541
fileobj = StringIO()
1542
writer = v4.BundleWriter(fileobj)
1544
writer.add_info_record(foo='bar')
1545
writer._container.add_bytes_record('blah', ['two', 'names'])
1548
record_iter = v4.BundleReader(fileobj).iter_records()
1549
record = record_iter.next()
1550
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1551
'info', None, None), record)
1552
self.assertRaises(BadBundle, record_iter.next)