1
# Copyright (C) 2005-2013, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
import SocketServer as socketserver
29
revision as _mod_revision,
37
from ..bundle import read_mergeable_from_url
38
from ..bundle.apply_bundle import install_bundle, merge_bundle
39
from ..bundle.bundle_data import BundleTree
40
from ..directory_service import directories
41
from ..bundle.serializer import write_bundle, read_bundle, v09, v4
42
from ..bundle.serializer.v08 import BundleSerializerV08
43
from ..bundle.serializer.v09 import BundleSerializerV09
44
from ..bundle.serializer.v4 import BundleSerializerV4
45
from ..bzr import knitrepo
46
from ..sixish import (
55
from ..transform import TreeTransform
58
def get_text(vf, key):
59
"""Get the fulltext for a given revision id that is present in the vf"""
60
stream = vf.get_record_stream([key], 'unordered', True)
62
return record.get_bytes_as('fulltext')
65
def get_inventory_text(repo, revision_id):
66
"""Get the fulltext for the inventory at revision id"""
69
return get_text(repo.inventories, (revision_id,))
74
class MockTree(object):
77
from ..bzr.inventory import InventoryDirectory, ROOT_ID
79
self.paths = {ROOT_ID: ""}
80
self.ids = {"": ROOT_ID}
82
self.root = InventoryDirectory(ROOT_ID, '', None)
84
inventory = property(lambda x:x)
85
root_inventory = property(lambda x:x)
87
def get_root_id(self):
88
return self.root.file_id
90
def all_file_ids(self):
91
return set(self.paths.keys())
93
def is_executable(self, file_id):
94
# Not all the files are executable.
97
def __getitem__(self, file_id):
98
if file_id == self.root.file_id:
101
return self.make_entry(file_id, self.paths[file_id])
103
def parent_id(self, file_id):
104
parent_dir = os.path.dirname(self.paths[file_id])
107
return self.ids[parent_dir]
109
def iter_entries(self):
110
for path, file_id in self.ids.items():
111
yield path, self[file_id]
113
def kind(self, file_id):
114
if file_id in self.contents:
120
def make_entry(self, file_id, path):
121
from ..bzr.inventory import (InventoryFile , InventoryDirectory,
123
name = os.path.basename(path)
124
kind = self.kind(file_id)
125
parent_id = self.parent_id(file_id)
126
text_sha_1, text_size = self.contents_stats(file_id)
127
if kind == 'directory':
128
ie = InventoryDirectory(file_id, name, parent_id)
130
ie = InventoryFile(file_id, name, parent_id)
131
ie.text_sha1 = text_sha_1
132
ie.text_size = text_size
133
elif kind == 'symlink':
134
ie = InventoryLink(file_id, name, parent_id)
136
raise errors.BzrError('unknown kind %r' % kind)
139
def add_dir(self, file_id, path):
140
self.paths[file_id] = path
141
self.ids[path] = file_id
143
def add_file(self, file_id, path, contents):
144
self.add_dir(file_id, path)
145
self.contents[file_id] = contents
147
def path2id(self, path):
148
return self.ids.get(path)
150
def id2path(self, file_id):
151
return self.paths.get(file_id)
153
def has_id(self, file_id):
154
return self.id2path(file_id) is not None
156
def get_file(self, file_id):
158
result.write(self.contents[file_id])
162
def get_file_revision(self, file_id):
163
return self.inventory[file_id].revision
165
def get_file_size(self, file_id):
166
return self.inventory[file_id].text_size
168
def get_file_sha1(self, file_id):
169
return self.inventory[file_id].text_sha1
171
def contents_stats(self, file_id):
172
if file_id not in self.contents:
174
text_sha1 = osutils.sha_file(self.get_file(file_id))
175
return text_sha1, len(self.contents[file_id])
178
class BTreeTester(tests.TestCase):
179
"""A simple unittest tester for the BundleTree class."""
181
def make_tree_1(self):
183
mtree.add_dir("a", "grandparent")
184
mtree.add_dir("b", "grandparent/parent")
185
mtree.add_file("c", "grandparent/parent/file", "Hello\n")
186
mtree.add_dir("d", "grandparent/alt_parent")
187
return BundleTree(mtree, ''), mtree
189
def test_renames(self):
190
"""Ensure that file renames have the proper effect on children"""
191
btree = self.make_tree_1()[0]
192
self.assertEqual(btree.old_path("grandparent"), "grandparent")
193
self.assertEqual(btree.old_path("grandparent/parent"),
194
"grandparent/parent")
195
self.assertEqual(btree.old_path("grandparent/parent/file"),
196
"grandparent/parent/file")
198
self.assertEqual(btree.id2path("a"), "grandparent")
199
self.assertEqual(btree.id2path("b"), "grandparent/parent")
200
self.assertEqual(btree.id2path("c"), "grandparent/parent/file")
202
self.assertEqual(btree.path2id("grandparent"), "a")
203
self.assertEqual(btree.path2id("grandparent/parent"), "b")
204
self.assertEqual(btree.path2id("grandparent/parent/file"), "c")
206
self.assertTrue(btree.path2id("grandparent2") is None)
207
self.assertTrue(btree.path2id("grandparent2/parent") is None)
208
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
210
btree.note_rename("grandparent", "grandparent2")
211
self.assertTrue(btree.old_path("grandparent") is None)
212
self.assertTrue(btree.old_path("grandparent/parent") is None)
213
self.assertTrue(btree.old_path("grandparent/parent/file") is None)
215
self.assertEqual(btree.id2path("a"), "grandparent2")
216
self.assertEqual(btree.id2path("b"), "grandparent2/parent")
217
self.assertEqual(btree.id2path("c"), "grandparent2/parent/file")
219
self.assertEqual(btree.path2id("grandparent2"), "a")
220
self.assertEqual(btree.path2id("grandparent2/parent"), "b")
221
self.assertEqual(btree.path2id("grandparent2/parent/file"), "c")
223
self.assertTrue(btree.path2id("grandparent") is None)
224
self.assertTrue(btree.path2id("grandparent/parent") is None)
225
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
227
btree.note_rename("grandparent/parent", "grandparent2/parent2")
228
self.assertEqual(btree.id2path("a"), "grandparent2")
229
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
230
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file")
232
self.assertEqual(btree.path2id("grandparent2"), "a")
233
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
234
self.assertEqual(btree.path2id("grandparent2/parent2/file"), "c")
236
self.assertTrue(btree.path2id("grandparent2/parent") is None)
237
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
239
btree.note_rename("grandparent/parent/file",
240
"grandparent2/parent2/file2")
241
self.assertEqual(btree.id2path("a"), "grandparent2")
242
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
243
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file2")
245
self.assertEqual(btree.path2id("grandparent2"), "a")
246
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
247
self.assertEqual(btree.path2id("grandparent2/parent2/file2"), "c")
249
self.assertTrue(btree.path2id("grandparent2/parent2/file") is None)
251
def test_moves(self):
252
"""Ensure that file moves have the proper effect on children"""
253
btree = self.make_tree_1()[0]
254
btree.note_rename("grandparent/parent/file",
255
"grandparent/alt_parent/file")
256
self.assertEqual(btree.id2path("c"), "grandparent/alt_parent/file")
257
self.assertEqual(btree.path2id("grandparent/alt_parent/file"), "c")
258
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
260
def unified_diff(self, old, new):
262
diff.internal_diff("old", old, "new", new, out)
266
def make_tree_2(self):
267
btree = self.make_tree_1()[0]
268
btree.note_rename("grandparent/parent/file",
269
"grandparent/alt_parent/file")
270
self.assertTrue(btree.id2path("e") is None)
271
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
272
btree.note_id("e", "grandparent/parent/file")
276
"""File/inventory adds"""
277
btree = self.make_tree_2()
278
add_patch = self.unified_diff([], ["Extra cheese\n"])
279
btree.note_patch("grandparent/parent/file", add_patch)
280
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
281
btree.note_target('grandparent/parent/symlink', 'venus')
282
self.adds_test(btree)
284
def adds_test(self, btree):
285
self.assertEqual(btree.id2path("e"), "grandparent/parent/file")
286
self.assertEqual(btree.path2id("grandparent/parent/file"), "e")
287
self.assertEqual(btree.get_file("e").read(), "Extra cheese\n")
288
self.assertEqual(btree.get_symlink_target('f'), 'venus')
290
def test_adds2(self):
291
"""File/inventory adds, with patch-compatibile renames"""
292
btree = self.make_tree_2()
293
btree.contents_by_id = False
294
add_patch = self.unified_diff(["Hello\n"], ["Extra cheese\n"])
295
btree.note_patch("grandparent/parent/file", add_patch)
296
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
297
btree.note_target('grandparent/parent/symlink', 'venus')
298
self.adds_test(btree)
300
def make_tree_3(self):
301
btree, mtree = self.make_tree_1()
302
mtree.add_file("e", "grandparent/parent/topping", "Anchovies\n")
303
btree.note_rename("grandparent/parent/file",
304
"grandparent/alt_parent/file")
305
btree.note_rename("grandparent/parent/topping",
306
"grandparent/alt_parent/stopping")
309
def get_file_test(self, btree):
310
self.assertEqual(btree.get_file("e").read(), "Lemon\n")
311
self.assertEqual(btree.get_file("c").read(), "Hello\n")
313
def test_get_file(self):
314
"""Get file contents"""
315
btree = self.make_tree_3()
316
mod_patch = self.unified_diff(["Anchovies\n"], ["Lemon\n"])
317
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
318
self.get_file_test(btree)
320
def test_get_file2(self):
321
"""Get file contents, with patch-compatibile renames"""
322
btree = self.make_tree_3()
323
btree.contents_by_id = False
324
mod_patch = self.unified_diff([], ["Lemon\n"])
325
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
326
mod_patch = self.unified_diff([], ["Hello\n"])
327
btree.note_patch("grandparent/alt_parent/file", mod_patch)
328
self.get_file_test(btree)
330
def test_delete(self):
332
btree = self.make_tree_1()[0]
333
self.assertEqual(btree.get_file("c").read(), "Hello\n")
334
btree.note_deletion("grandparent/parent/file")
335
self.assertTrue(btree.id2path("c") is None)
336
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
338
def sorted_ids(self, tree):
339
ids = sorted(tree.all_file_ids())
342
def test_iteration(self):
343
"""Ensure that iteration through ids works properly"""
344
btree = self.make_tree_1()[0]
345
self.assertEqual(self.sorted_ids(btree),
346
[inventory.ROOT_ID, 'a', 'b', 'c', 'd'])
347
btree.note_deletion("grandparent/parent/file")
348
btree.note_id("e", "grandparent/alt_parent/fool", kind="directory")
349
btree.note_last_changed("grandparent/alt_parent/fool",
351
self.assertEqual(self.sorted_ids(btree),
352
[inventory.ROOT_ID, 'a', 'b', 'd', 'e'])
355
class BundleTester1(tests.TestCaseWithTransport):
357
def test_mismatched_bundle(self):
358
format = bzrdir.BzrDirMetaFormat1()
359
format.repository_format = knitrepo.RepositoryFormatKnit3()
360
serializer = BundleSerializerV08('0.8')
361
b = self.make_branch('.', format=format)
362
self.assertRaises(errors.IncompatibleBundleFormat, serializer.write,
363
b.repository, [], {}, BytesIO())
365
def test_matched_bundle(self):
366
"""Don't raise IncompatibleBundleFormat for knit2 and bundle0.9"""
367
format = bzrdir.BzrDirMetaFormat1()
368
format.repository_format = knitrepo.RepositoryFormatKnit3()
369
serializer = BundleSerializerV09('0.9')
370
b = self.make_branch('.', format=format)
371
serializer.write(b.repository, [], {}, BytesIO())
373
def test_mismatched_model(self):
374
"""Try copying a bundle from knit2 to knit1"""
375
format = bzrdir.BzrDirMetaFormat1()
376
format.repository_format = knitrepo.RepositoryFormatKnit3()
377
source = self.make_branch_and_tree('source', format=format)
378
source.commit('one', rev_id='one-id')
379
source.commit('two', rev_id='two-id')
381
write_bundle(source.branch.repository, 'two-id', 'null:', text,
385
format = bzrdir.BzrDirMetaFormat1()
386
format.repository_format = knitrepo.RepositoryFormatKnit1()
387
target = self.make_branch('target', format=format)
388
self.assertRaises(errors.IncompatibleRevision, install_bundle,
389
target.repository, read_bundle(text))
392
class BundleTester(object):
394
def bzrdir_format(self):
395
format = bzrdir.BzrDirMetaFormat1()
396
format.repository_format = knitrepo.RepositoryFormatKnit1()
399
def make_branch_and_tree(self, path, format=None):
401
format = self.bzrdir_format()
402
return tests.TestCaseWithTransport.make_branch_and_tree(
405
def make_branch(self, path, format=None):
407
format = self.bzrdir_format()
408
return tests.TestCaseWithTransport.make_branch(self, path, format)
410
def create_bundle_text(self, base_rev_id, rev_id):
411
bundle_txt = BytesIO()
412
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
413
bundle_txt, format=self.format)
415
self.assertEqual(bundle_txt.readline(),
416
'# Bazaar revision bundle v%s\n' % self.format)
417
self.assertEqual(bundle_txt.readline(), '#\n')
419
rev = self.b1.repository.get_revision(rev_id)
420
self.assertEqual(bundle_txt.readline().decode('utf-8'),
423
return bundle_txt, rev_ids
425
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
426
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
427
Make sure that the text generated is valid, and that it
428
can be applied against the base, and generate the same information.
430
:return: The in-memory bundle
432
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
434
# This should also validate the generated bundle
435
bundle = read_bundle(bundle_txt)
436
repository = self.b1.repository
437
for bundle_rev in bundle.real_revisions:
438
# These really should have already been checked when we read the
439
# bundle, since it computes the sha1 hash for the revision, which
440
# only will match if everything is okay, but lets be explicit about
442
branch_rev = repository.get_revision(bundle_rev.revision_id)
443
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
444
'timestamp', 'timezone', 'message', 'committer',
445
'parent_ids', 'properties'):
446
self.assertEqual(getattr(branch_rev, a),
447
getattr(bundle_rev, a))
448
self.assertEqual(len(branch_rev.parent_ids),
449
len(bundle_rev.parent_ids))
450
self.assertEqual(rev_ids,
451
[r.revision_id for r in bundle.real_revisions])
452
self.valid_apply_bundle(base_rev_id, bundle,
453
checkout_dir=checkout_dir)
457
def get_invalid_bundle(self, base_rev_id, rev_id):
458
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
459
Munge the text so that it's invalid.
461
:return: The in-memory bundle
463
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
464
new_text = bundle_txt.getvalue().replace('executable:no',
466
bundle_txt = BytesIO(new_text)
467
bundle = read_bundle(bundle_txt)
468
self.valid_apply_bundle(base_rev_id, bundle)
471
def test_non_bundle(self):
472
self.assertRaises(errors.NotABundle,
473
read_bundle, BytesIO(b'#!/bin/sh\n'))
475
def test_malformed(self):
476
self.assertRaises(errors.BadBundle, read_bundle,
477
BytesIO(b'# Bazaar revision bundle v'))
479
def test_crlf_bundle(self):
481
read_bundle(BytesIO(b'# Bazaar revision bundle v0.8\r\n'))
482
except errors.BadBundle:
483
# It is currently permitted for bundles with crlf line endings to
484
# make read_bundle raise a BadBundle, but this should be fixed.
485
# Anything else, especially NotABundle, is an error.
488
def get_checkout(self, rev_id, checkout_dir=None):
489
"""Get a new tree, with the specified revision in it.
492
if checkout_dir is None:
493
checkout_dir = osutils.mkdtemp(prefix='test-branch-', dir='.')
495
if not os.path.exists(checkout_dir):
496
os.mkdir(checkout_dir)
497
tree = self.make_branch_and_tree(checkout_dir)
499
ancestors = write_bundle(self.b1.repository, rev_id, 'null:', s,
502
self.assertIsInstance(s.getvalue(), str)
503
install_bundle(tree.branch.repository, read_bundle(s))
504
for ancestor in ancestors:
505
old = self.b1.repository.revision_tree(ancestor)
506
new = tree.branch.repository.revision_tree(ancestor)
510
# Check that there aren't any inventory level changes
511
delta = new.changes_from(old)
512
self.assertFalse(delta.has_changed(),
513
'Revision %s not copied correctly.'
516
# Now check that the file contents are all correct
517
for inventory_id in old.all_file_ids():
519
old_file = old.get_file(inventory_id)
520
except errors.NoSuchFile:
524
self.assertEqual(old_file.read(),
525
new.get_file(inventory_id).read())
529
if not _mod_revision.is_null(rev_id):
530
tree.branch.generate_revision_history(rev_id)
532
delta = tree.changes_from(self.b1.repository.revision_tree(rev_id))
533
self.assertFalse(delta.has_changed(),
534
'Working tree has modifications: %s' % delta)
537
def valid_apply_bundle(self, base_rev_id, info, checkout_dir=None):
538
"""Get the base revision, apply the changes, and make
539
sure everything matches the builtin branch.
541
to_tree = self.get_checkout(base_rev_id, checkout_dir=checkout_dir)
544
self._valid_apply_bundle(base_rev_id, info, to_tree)
548
def _valid_apply_bundle(self, base_rev_id, info, to_tree):
549
original_parents = to_tree.get_parent_ids()
550
repository = to_tree.branch.repository
551
original_parents = to_tree.get_parent_ids()
552
self.assertIs(repository.has_revision(base_rev_id), True)
553
for rev in info.real_revisions:
554
self.assertTrue(not repository.has_revision(rev.revision_id),
555
'Revision {%s} present before applying bundle'
557
merge_bundle(info, to_tree, True, merge.Merge3Merger, False, False)
559
for rev in info.real_revisions:
560
self.assertTrue(repository.has_revision(rev.revision_id),
561
'Missing revision {%s} after applying bundle'
564
self.assertTrue(to_tree.branch.repository.has_revision(info.target))
565
# Do we also want to verify that all the texts have been added?
567
self.assertEqual(original_parents + [info.target],
568
to_tree.get_parent_ids())
570
rev = info.real_revisions[-1]
571
base_tree = self.b1.repository.revision_tree(rev.revision_id)
572
to_tree = to_tree.branch.repository.revision_tree(rev.revision_id)
574
# TODO: make sure the target tree is identical to base tree
575
# we might also check the working tree.
577
base_files = list(base_tree.list_files())
578
to_files = list(to_tree.list_files())
579
self.assertEqual(len(base_files), len(to_files))
580
for base_file, to_file in zip(base_files, to_files):
581
self.assertEqual(base_file, to_file)
583
for path, status, kind, fileid, entry in base_files:
584
# Check that the meta information is the same
585
self.assertEqual(base_tree.get_file_size(fileid),
586
to_tree.get_file_size(fileid))
587
self.assertEqual(base_tree.get_file_sha1(fileid),
588
to_tree.get_file_sha1(fileid))
589
# Check that the contents are the same
590
# This is pretty expensive
591
# self.assertEqual(base_tree.get_file(fileid).read(),
592
# to_tree.get_file(fileid).read())
594
def test_bundle(self):
595
self.tree1 = self.make_branch_and_tree('b1')
596
self.b1 = self.tree1.branch
598
self.build_tree_contents([('b1/one', 'one\n')])
599
self.tree1.add('one', 'one-id')
600
self.tree1.set_root_id('root-id')
601
self.tree1.commit('add one', rev_id='a@cset-0-1')
603
bundle = self.get_valid_bundle('null:', 'a@cset-0-1')
605
# Make sure we can handle files with spaces, tabs, other
610
, 'b1/dir/filein subdir.c'
611
, 'b1/dir/WithCaps.txt'
612
, 'b1/dir/ pre space'
615
, 'b1/sub/sub/nonempty.txt'
617
self.build_tree_contents([('b1/sub/sub/emptyfile.txt', ''),
618
('b1/dir/nolastnewline.txt', 'bloop')])
619
tt = TreeTransform(self.tree1)
620
tt.new_file('executable', tt.root, '#!/bin/sh\n', 'exe-1', True)
622
# have to fix length of file-id so that we can predictably rewrite
623
# a (length-prefixed) record containing it later.
624
self.tree1.add('with space.txt', 'withspace-id')
627
, 'dir/filein subdir.c'
630
, 'dir/nolastnewline.txt'
633
, 'sub/sub/nonempty.txt'
634
, 'sub/sub/emptyfile.txt'
636
self.tree1.commit('add whitespace', rev_id='a@cset-0-2')
638
bundle = self.get_valid_bundle('a@cset-0-1', 'a@cset-0-2')
640
# Check a rollup bundle
641
bundle = self.get_valid_bundle('null:', 'a@cset-0-2')
645
['sub/sub/nonempty.txt'
646
, 'sub/sub/emptyfile.txt'
649
tt = TreeTransform(self.tree1)
650
trans_id = tt.trans_id_tree_file_id('exe-1')
651
tt.set_executability(False, trans_id)
653
self.tree1.commit('removed', rev_id='a@cset-0-3')
655
bundle = self.get_valid_bundle('a@cset-0-2', 'a@cset-0-3')
656
self.assertRaises((errors.TestamentMismatch,
657
errors.VersionedFileInvalidChecksum,
658
errors.BadBundle), self.get_invalid_bundle,
659
'a@cset-0-2', 'a@cset-0-3')
660
# Check a rollup bundle
661
bundle = self.get_valid_bundle('null:', 'a@cset-0-3')
663
# Now move the directory
664
self.tree1.rename_one('dir', 'sub/dir')
665
self.tree1.commit('rename dir', rev_id='a@cset-0-4')
667
bundle = self.get_valid_bundle('a@cset-0-3', 'a@cset-0-4')
668
# Check a rollup bundle
669
bundle = self.get_valid_bundle('null:', 'a@cset-0-4')
672
with open('b1/sub/dir/WithCaps.txt', 'ab') as f: f.write('\nAdding some text\n')
673
with open('b1/sub/dir/ pre space', 'ab') as f: f.write(
674
'\r\nAdding some\r\nDOS format lines\r\n')
675
with open('b1/sub/dir/nolastnewline.txt', 'ab') as f: f.write('\n')
676
self.tree1.rename_one('sub/dir/ pre space',
678
self.tree1.commit('Modified files', rev_id='a@cset-0-5')
679
bundle = self.get_valid_bundle('a@cset-0-4', 'a@cset-0-5')
681
self.tree1.rename_one('sub/dir/WithCaps.txt', 'temp')
682
self.tree1.rename_one('with space.txt', 'WithCaps.txt')
683
self.tree1.rename_one('temp', 'with space.txt')
684
self.tree1.commit(u'swap filenames', rev_id='a@cset-0-6',
686
bundle = self.get_valid_bundle('a@cset-0-5', 'a@cset-0-6')
687
other = self.get_checkout('a@cset-0-5')
688
tree1_inv = get_inventory_text(self.tree1.branch.repository,
690
tree2_inv = get_inventory_text(other.branch.repository,
692
self.assertEqualDiff(tree1_inv, tree2_inv)
693
other.rename_one('sub/dir/nolastnewline.txt', 'sub/nolastnewline.txt')
694
other.commit('rename file', rev_id='a@cset-0-6b')
695
self.tree1.merge_from_branch(other.branch)
696
self.tree1.commit(u'Merge', rev_id='a@cset-0-7',
698
bundle = self.get_valid_bundle('a@cset-0-6', 'a@cset-0-7')
700
def _test_symlink_bundle(self, link_name, link_target, new_link_target):
703
self.requireFeature(features.SymlinkFeature)
704
self.tree1 = self.make_branch_and_tree('b1')
705
self.b1 = self.tree1.branch
707
tt = TreeTransform(self.tree1)
708
tt.new_symlink(link_name, tt.root, link_target, link_id)
710
self.tree1.commit('add symlink', rev_id='l@cset-0-1')
711
bundle = self.get_valid_bundle('null:', 'l@cset-0-1')
712
if getattr(bundle ,'revision_tree', None) is not None:
713
# Not all bundle formats supports revision_tree
714
bund_tree = bundle.revision_tree(self.b1.repository, 'l@cset-0-1')
715
self.assertEqual(link_target, bund_tree.get_symlink_target(link_id))
717
tt = TreeTransform(self.tree1)
718
trans_id = tt.trans_id_tree_file_id(link_id)
719
tt.adjust_path('link2', tt.root, trans_id)
720
tt.delete_contents(trans_id)
721
tt.create_symlink(new_link_target, trans_id)
723
self.tree1.commit('rename and change symlink', rev_id='l@cset-0-2')
724
bundle = self.get_valid_bundle('l@cset-0-1', 'l@cset-0-2')
725
if getattr(bundle ,'revision_tree', None) is not None:
726
# Not all bundle formats supports revision_tree
727
bund_tree = bundle.revision_tree(self.b1.repository, 'l@cset-0-2')
728
self.assertEqual(new_link_target,
729
bund_tree.get_symlink_target(link_id))
731
tt = TreeTransform(self.tree1)
732
trans_id = tt.trans_id_tree_file_id(link_id)
733
tt.delete_contents(trans_id)
734
tt.create_symlink('jupiter', trans_id)
736
self.tree1.commit('just change symlink target', rev_id='l@cset-0-3')
737
bundle = self.get_valid_bundle('l@cset-0-2', 'l@cset-0-3')
739
tt = TreeTransform(self.tree1)
740
trans_id = tt.trans_id_tree_file_id(link_id)
741
tt.delete_contents(trans_id)
743
self.tree1.commit('Delete symlink', rev_id='l@cset-0-4')
744
bundle = self.get_valid_bundle('l@cset-0-3', 'l@cset-0-4')
746
def test_symlink_bundle(self):
747
self._test_symlink_bundle('link', 'bar/foo', 'mars')
749
def test_unicode_symlink_bundle(self):
750
self.requireFeature(features.UnicodeFilenameFeature)
751
self._test_symlink_bundle(u'\N{Euro Sign}link',
752
u'bar/\N{Euro Sign}foo',
753
u'mars\N{Euro Sign}')
755
def test_binary_bundle(self):
756
self.tree1 = self.make_branch_and_tree('b1')
757
self.b1 = self.tree1.branch
758
tt = TreeTransform(self.tree1)
761
tt.new_file('file', tt.root, '\x00\n\x00\r\x01\n\x02\r\xff', 'binary-1')
762
tt.new_file('file2', tt.root, '\x01\n\x02\r\x03\n\x04\r\xff',
765
self.tree1.commit('add binary', rev_id='b@cset-0-1')
766
self.get_valid_bundle('null:', 'b@cset-0-1')
769
tt = TreeTransform(self.tree1)
770
trans_id = tt.trans_id_tree_file_id('binary-1')
771
tt.delete_contents(trans_id)
773
self.tree1.commit('delete binary', rev_id='b@cset-0-2')
774
self.get_valid_bundle('b@cset-0-1', 'b@cset-0-2')
777
tt = TreeTransform(self.tree1)
778
trans_id = tt.trans_id_tree_file_id('binary-2')
779
tt.adjust_path('file3', tt.root, trans_id)
780
tt.delete_contents(trans_id)
781
tt.create_file('file\rcontents\x00\n\x00', trans_id)
783
self.tree1.commit('rename and modify binary', rev_id='b@cset-0-3')
784
self.get_valid_bundle('b@cset-0-2', 'b@cset-0-3')
787
tt = TreeTransform(self.tree1)
788
trans_id = tt.trans_id_tree_file_id('binary-2')
789
tt.delete_contents(trans_id)
790
tt.create_file('\x00file\rcontents', trans_id)
792
self.tree1.commit('just modify binary', rev_id='b@cset-0-4')
793
self.get_valid_bundle('b@cset-0-3', 'b@cset-0-4')
796
self.get_valid_bundle('null:', 'b@cset-0-4')
798
def test_last_modified(self):
799
self.tree1 = self.make_branch_and_tree('b1')
800
self.b1 = self.tree1.branch
801
tt = TreeTransform(self.tree1)
802
tt.new_file('file', tt.root, 'file', 'file')
804
self.tree1.commit('create file', rev_id='a@lmod-0-1')
806
tt = TreeTransform(self.tree1)
807
trans_id = tt.trans_id_tree_file_id('file')
808
tt.delete_contents(trans_id)
809
tt.create_file('file2', trans_id)
811
self.tree1.commit('modify text', rev_id='a@lmod-0-2a')
813
other = self.get_checkout('a@lmod-0-1')
814
tt = TreeTransform(other)
815
trans_id = tt.trans_id_tree_file_id('file')
816
tt.delete_contents(trans_id)
817
tt.create_file('file2', trans_id)
819
other.commit('modify text in another tree', rev_id='a@lmod-0-2b')
820
self.tree1.merge_from_branch(other.branch)
821
self.tree1.commit(u'Merge', rev_id='a@lmod-0-3',
823
self.tree1.commit(u'Merge', rev_id='a@lmod-0-4')
824
bundle = self.get_valid_bundle('a@lmod-0-2a', 'a@lmod-0-4')
826
def test_hide_history(self):
827
self.tree1 = self.make_branch_and_tree('b1')
828
self.b1 = self.tree1.branch
830
with open('b1/one', 'wb') as f: f.write('one\n')
831
self.tree1.add('one')
832
self.tree1.commit('add file', rev_id='a@cset-0-1')
833
with open('b1/one', 'wb') as f: f.write('two\n')
834
self.tree1.commit('modify', rev_id='a@cset-0-2')
835
with open('b1/one', 'wb') as f: f.write('three\n')
836
self.tree1.commit('modify', rev_id='a@cset-0-3')
837
bundle_file = BytesIO()
838
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-3',
839
'a@cset-0-1', bundle_file, format=self.format)
840
self.assertNotContainsRe(bundle_file.getvalue(), '\btwo\b')
841
self.assertContainsRe(self.get_raw(bundle_file), 'one')
842
self.assertContainsRe(self.get_raw(bundle_file), 'three')
844
def test_bundle_same_basis(self):
845
"""Ensure using the basis as the target doesn't cause an error"""
846
self.tree1 = self.make_branch_and_tree('b1')
847
self.tree1.commit('add file', rev_id='a@cset-0-1')
848
bundle_file = BytesIO()
849
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-1',
850
'a@cset-0-1', bundle_file)
853
def get_raw(bundle_file):
854
return bundle_file.getvalue()
856
def test_unicode_bundle(self):
857
self.requireFeature(features.UnicodeFilenameFeature)
858
# Handle international characters
860
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
862
self.tree1 = self.make_branch_and_tree('b1')
863
self.b1 = self.tree1.branch
866
u'With international man of mystery\n'
867
u'William Dod\xe9\n').encode('utf-8'))
870
self.tree1.add([u'with Dod\N{Euro Sign}'], ['withdod-id'])
871
self.tree1.commit(u'i18n commit from William Dod\xe9',
872
rev_id='i18n-1', committer=u'William Dod\xe9')
875
bundle = self.get_valid_bundle('null:', 'i18n-1')
878
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
879
f.write(u'Modified \xb5\n'.encode('utf8'))
881
self.tree1.commit(u'modified', rev_id='i18n-2')
883
bundle = self.get_valid_bundle('i18n-1', 'i18n-2')
886
self.tree1.rename_one(u'with Dod\N{Euro Sign}', u'B\N{Euro Sign}gfors')
887
self.tree1.commit(u'renamed, the new i18n man', rev_id='i18n-3',
888
committer=u'Erik B\xe5gfors')
890
bundle = self.get_valid_bundle('i18n-2', 'i18n-3')
893
self.tree1.remove([u'B\N{Euro Sign}gfors'])
894
self.tree1.commit(u'removed', rev_id='i18n-4')
896
bundle = self.get_valid_bundle('i18n-3', 'i18n-4')
899
bundle = self.get_valid_bundle('null:', 'i18n-4')
902
def test_whitespace_bundle(self):
903
if sys.platform in ('win32', 'cygwin'):
904
raise tests.TestSkipped('Windows doesn\'t support filenames'
905
' with tabs or trailing spaces')
906
self.tree1 = self.make_branch_and_tree('b1')
907
self.b1 = self.tree1.branch
909
self.build_tree(['b1/trailing space '])
910
self.tree1.add(['trailing space '])
911
# TODO: jam 20060701 Check for handling files with '\t' characters
912
# once we actually support them
915
self.tree1.commit('funky whitespace', rev_id='white-1')
917
bundle = self.get_valid_bundle('null:', 'white-1')
920
with open('b1/trailing space ', 'ab') as f: f.write('add some text\n')
921
self.tree1.commit('add text', rev_id='white-2')
923
bundle = self.get_valid_bundle('white-1', 'white-2')
926
self.tree1.rename_one('trailing space ', ' start and end space ')
927
self.tree1.commit('rename', rev_id='white-3')
929
bundle = self.get_valid_bundle('white-2', 'white-3')
932
self.tree1.remove([' start and end space '])
933
self.tree1.commit('removed', rev_id='white-4')
935
bundle = self.get_valid_bundle('white-3', 'white-4')
937
# Now test a complet roll-up
938
bundle = self.get_valid_bundle('null:', 'white-4')
940
def test_alt_timezone_bundle(self):
941
self.tree1 = self.make_branch_and_memory_tree('b1')
942
self.b1 = self.tree1.branch
943
builder = treebuilder.TreeBuilder()
945
self.tree1.lock_write()
946
builder.start_tree(self.tree1)
947
builder.build(['newfile'])
948
builder.finish_tree()
950
# Asia/Colombo offset = 5 hours 30 minutes
951
self.tree1.commit('non-hour offset timezone', rev_id='tz-1',
952
timezone=19800, timestamp=1152544886.0)
954
bundle = self.get_valid_bundle('null:', 'tz-1')
956
rev = bundle.revisions[0]
957
self.assertEqual('Mon 2006-07-10 20:51:26.000000000 +0530', rev.date)
958
self.assertEqual(19800, rev.timezone)
959
self.assertEqual(1152544886.0, rev.timestamp)
962
def test_bundle_root_id(self):
963
self.tree1 = self.make_branch_and_tree('b1')
964
self.b1 = self.tree1.branch
965
self.tree1.commit('message', rev_id='revid1')
966
bundle = self.get_valid_bundle('null:', 'revid1')
967
tree = self.get_bundle_tree(bundle, 'revid1')
968
root_revision = tree.get_file_revision(tree.get_root_id())
969
self.assertEqual('revid1', root_revision)
971
def test_install_revisions(self):
972
self.tree1 = self.make_branch_and_tree('b1')
973
self.b1 = self.tree1.branch
974
self.tree1.commit('message', rev_id='rev2a')
975
bundle = self.get_valid_bundle('null:', 'rev2a')
976
branch2 = self.make_branch('b2')
977
self.assertFalse(branch2.repository.has_revision('rev2a'))
978
target_revision = bundle.install_revisions(branch2.repository)
979
self.assertTrue(branch2.repository.has_revision('rev2a'))
980
self.assertEqual('rev2a', target_revision)
982
def test_bundle_empty_property(self):
983
"""Test serializing revision properties with an empty value."""
984
tree = self.make_branch_and_memory_tree('tree')
986
self.addCleanup(tree.unlock)
987
tree.add([''], ['TREE_ROOT'])
988
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
989
self.b1 = tree.branch
990
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
991
bundle = read_bundle(bundle_sio)
992
revision_info = bundle.revisions[0]
993
self.assertEqual('rev1', revision_info.revision_id)
994
rev = revision_info.as_revision()
995
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
998
def test_bundle_sorted_properties(self):
999
"""For stability the writer should write properties in sorted order."""
1000
tree = self.make_branch_and_memory_tree('tree')
1002
self.addCleanup(tree.unlock)
1004
tree.add([''], ['TREE_ROOT'])
1005
tree.commit('One', rev_id='rev1',
1006
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1007
self.b1 = tree.branch
1008
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1009
bundle = read_bundle(bundle_sio)
1010
revision_info = bundle.revisions[0]
1011
self.assertEqual('rev1', revision_info.revision_id)
1012
rev = revision_info.as_revision()
1013
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1014
'd':'1'}, rev.properties)
1016
def test_bundle_unicode_properties(self):
1017
"""We should be able to round trip a non-ascii property."""
1018
tree = self.make_branch_and_memory_tree('tree')
1020
self.addCleanup(tree.unlock)
1022
tree.add([''], ['TREE_ROOT'])
1023
# Revisions themselves do not require anything about revision property
1024
# keys, other than that they are a basestring, and do not contain
1026
# However, Testaments assert than they are str(), and thus should not
1028
tree.commit('One', rev_id='rev1',
1029
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1030
self.b1 = tree.branch
1031
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1032
bundle = read_bundle(bundle_sio)
1033
revision_info = bundle.revisions[0]
1034
self.assertEqual('rev1', revision_info.revision_id)
1035
rev = revision_info.as_revision()
1036
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1037
'alpha':u'\u03b1'}, rev.properties)
1039
def test_bundle_with_ghosts(self):
1040
tree = self.make_branch_and_tree('tree')
1041
self.b1 = tree.branch
1042
self.build_tree_contents([('tree/file', 'content1')])
1045
self.build_tree_contents([('tree/file', 'content2')])
1046
tree.add_parent_tree_id('ghost')
1047
tree.commit('rev2', rev_id='rev2')
1048
bundle = self.get_valid_bundle('null:', 'rev2')
1050
def make_simple_tree(self, format=None):
1051
tree = self.make_branch_and_tree('b1', format=format)
1052
self.b1 = tree.branch
1053
self.build_tree(['b1/file'])
1057
def test_across_serializers(self):
1058
tree = self.make_simple_tree('knit')
1059
tree.commit('hello', rev_id='rev1')
1060
tree.commit('hello', rev_id='rev2')
1061
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1062
repo = self.make_repository('repo', format='dirstate-with-subtree')
1063
bundle.install_revisions(repo)
1064
inv_text = repo._get_inventory_xml('rev2')
1065
self.assertNotContainsRe(inv_text, 'format="5"')
1066
self.assertContainsRe(inv_text, 'format="7"')
1068
def make_repo_with_installed_revisions(self):
1069
tree = self.make_simple_tree('knit')
1070
tree.commit('hello', rev_id='rev1')
1071
tree.commit('hello', rev_id='rev2')
1072
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1073
repo = self.make_repository('repo', format='dirstate-with-subtree')
1074
bundle.install_revisions(repo)
1077
def test_across_models(self):
1078
repo = self.make_repo_with_installed_revisions()
1079
inv = repo.get_inventory('rev2')
1080
self.assertEqual('rev2', inv.root.revision)
1081
root_id = inv.root.file_id
1083
self.addCleanup(repo.unlock)
1084
self.assertEqual({(root_id, 'rev1'):(),
1085
(root_id, 'rev2'):((root_id, 'rev1'),)},
1086
repo.texts.get_parent_map([(root_id, 'rev1'), (root_id, 'rev2')]))
1088
def test_inv_hash_across_serializers(self):
1089
repo = self.make_repo_with_installed_revisions()
1090
recorded_inv_sha1 = repo.get_revision('rev2').inventory_sha1
1091
xml = repo._get_inventory_xml('rev2')
1092
self.assertEqual(osutils.sha_string(xml), recorded_inv_sha1)
1094
def test_across_models_incompatible(self):
1095
tree = self.make_simple_tree('dirstate-with-subtree')
1096
tree.commit('hello', rev_id='rev1')
1097
tree.commit('hello', rev_id='rev2')
1099
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1100
except errors.IncompatibleBundleFormat:
1101
raise tests.TestSkipped("Format 0.8 doesn't work with knit3")
1102
repo = self.make_repository('repo', format='knit')
1103
bundle.install_revisions(repo)
1105
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1106
self.assertRaises(errors.IncompatibleRevision,
1107
bundle.install_revisions, repo)
1109
def test_get_merge_request(self):
1110
tree = self.make_simple_tree()
1111
tree.commit('hello', rev_id='rev1')
1112
tree.commit('hello', rev_id='rev2')
1113
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1114
result = bundle.get_merge_request(tree.branch.repository)
1115
self.assertEqual((None, 'rev1', 'inapplicable'), result)
1117
def test_with_subtree(self):
1118
tree = self.make_branch_and_tree('tree',
1119
format='dirstate-with-subtree')
1120
self.b1 = tree.branch
1121
subtree = self.make_branch_and_tree('tree/subtree',
1122
format='dirstate-with-subtree')
1124
tree.commit('hello', rev_id='rev1')
1126
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1127
except errors.IncompatibleBundleFormat:
1128
raise tests.TestSkipped("Format 0.8 doesn't work with knit3")
1129
if isinstance(bundle, v09.BundleInfo09):
1130
raise tests.TestSkipped("Format 0.9 doesn't work with subtrees")
1131
repo = self.make_repository('repo', format='knit')
1132
self.assertRaises(errors.IncompatibleRevision,
1133
bundle.install_revisions, repo)
1134
repo2 = self.make_repository('repo2', format='dirstate-with-subtree')
1135
bundle.install_revisions(repo2)
1137
def test_revision_id_with_slash(self):
1138
self.tree1 = self.make_branch_and_tree('tree')
1139
self.b1 = self.tree1.branch
1141
self.tree1.commit('Revision/id/with/slashes', rev_id='rev/id')
1143
raise tests.TestSkipped(
1144
"Repository doesn't support revision ids with slashes")
1145
bundle = self.get_valid_bundle('null:', 'rev/id')
1147
def test_skip_file(self):
1148
"""Make sure we don't accidentally write to the wrong versionedfile"""
1149
self.tree1 = self.make_branch_and_tree('tree')
1150
self.b1 = self.tree1.branch
1151
# rev1 is not present in bundle, done by fetch
1152
self.build_tree_contents([('tree/file2', 'contents1')])
1153
self.tree1.add('file2', 'file2-id')
1154
self.tree1.commit('rev1', rev_id='reva')
1155
self.build_tree_contents([('tree/file3', 'contents2')])
1156
# rev2 is present in bundle, and done by fetch
1157
# having file1 in the bunle causes file1's versionedfile to be opened.
1158
self.tree1.add('file3', 'file3-id')
1159
self.tree1.commit('rev2')
1160
# Updating file2 should not cause an attempt to add to file1's vf
1161
target = self.tree1.controldir.sprout('target').open_workingtree()
1162
self.build_tree_contents([('tree/file2', 'contents3')])
1163
self.tree1.commit('rev3', rev_id='rev3')
1164
bundle = self.get_valid_bundle('reva', 'rev3')
1165
if getattr(bundle, 'get_bundle_reader', None) is None:
1166
raise tests.TestSkipped('Bundle format cannot provide reader')
1167
# be sure that file1 comes before file2
1168
for b, m, k, r, f in bundle.get_bundle_reader().iter_records():
1171
self.assertNotEqual(f, 'file2-id')
1172
bundle.install_revisions(target.branch.repository)
1175
class V08BundleTester(BundleTester, tests.TestCaseWithTransport):
1179
def test_bundle_empty_property(self):
1180
"""Test serializing revision properties with an empty value."""
1181
tree = self.make_branch_and_memory_tree('tree')
1183
self.addCleanup(tree.unlock)
1184
tree.add([''], ['TREE_ROOT'])
1185
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1186
self.b1 = tree.branch
1187
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1188
self.assertContainsRe(bundle_sio.getvalue(),
1190
'# branch-nick: tree\n'
1194
bundle = read_bundle(bundle_sio)
1195
revision_info = bundle.revisions[0]
1196
self.assertEqual('rev1', revision_info.revision_id)
1197
rev = revision_info.as_revision()
1198
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1201
def get_bundle_tree(self, bundle, revision_id):
1202
repository = self.make_repository('repo')
1203
return bundle.revision_tree(repository, 'revid1')
1205
def test_bundle_empty_property_alt(self):
1206
"""Test serializing revision properties with an empty value.
1208
Older readers had a bug when reading an empty property.
1209
They assumed that all keys ended in ': \n'. However they would write an
1210
empty value as ':\n'. This tests make sure that all newer bzr versions
1211
can handle th second form.
1213
tree = self.make_branch_and_memory_tree('tree')
1215
self.addCleanup(tree.unlock)
1216
tree.add([''], ['TREE_ROOT'])
1217
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1218
self.b1 = tree.branch
1219
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1220
txt = bundle_sio.getvalue()
1221
loc = txt.find('# empty: ') + len('# empty:')
1222
# Create a new bundle, which strips the trailing space after empty
1223
bundle_sio = BytesIO(txt[:loc] + txt[loc+1:])
1225
self.assertContainsRe(bundle_sio.getvalue(),
1227
'# branch-nick: tree\n'
1231
bundle = read_bundle(bundle_sio)
1232
revision_info = bundle.revisions[0]
1233
self.assertEqual('rev1', revision_info.revision_id)
1234
rev = revision_info.as_revision()
1235
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1238
def test_bundle_sorted_properties(self):
1239
"""For stability the writer should write properties in sorted order."""
1240
tree = self.make_branch_and_memory_tree('tree')
1242
self.addCleanup(tree.unlock)
1244
tree.add([''], ['TREE_ROOT'])
1245
tree.commit('One', rev_id='rev1',
1246
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1247
self.b1 = tree.branch
1248
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1249
self.assertContainsRe(bundle_sio.getvalue(),
1253
'# branch-nick: tree\n'
1257
bundle = read_bundle(bundle_sio)
1258
revision_info = bundle.revisions[0]
1259
self.assertEqual('rev1', revision_info.revision_id)
1260
rev = revision_info.as_revision()
1261
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1262
'd':'1'}, rev.properties)
1264
def test_bundle_unicode_properties(self):
1265
"""We should be able to round trip a non-ascii property."""
1266
tree = self.make_branch_and_memory_tree('tree')
1268
self.addCleanup(tree.unlock)
1270
tree.add([''], ['TREE_ROOT'])
1271
# Revisions themselves do not require anything about revision property
1272
# keys, other than that they are a basestring, and do not contain
1274
# However, Testaments assert than they are str(), and thus should not
1276
tree.commit('One', rev_id='rev1',
1277
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1278
self.b1 = tree.branch
1279
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1280
self.assertContainsRe(bundle_sio.getvalue(),
1282
'# alpha: \xce\xb1\n'
1283
'# branch-nick: tree\n'
1284
'# omega: \xce\xa9\n'
1286
bundle = read_bundle(bundle_sio)
1287
revision_info = bundle.revisions[0]
1288
self.assertEqual('rev1', revision_info.revision_id)
1289
rev = revision_info.as_revision()
1290
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1291
'alpha':u'\u03b1'}, rev.properties)
1294
class V09BundleKnit2Tester(V08BundleTester):
1298
def bzrdir_format(self):
1299
format = bzrdir.BzrDirMetaFormat1()
1300
format.repository_format = knitrepo.RepositoryFormatKnit3()
1304
class V09BundleKnit1Tester(V08BundleTester):
1308
def bzrdir_format(self):
1309
format = bzrdir.BzrDirMetaFormat1()
1310
format.repository_format = knitrepo.RepositoryFormatKnit1()
1314
class V4BundleTester(BundleTester, tests.TestCaseWithTransport):
1318
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
1319
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1320
Make sure that the text generated is valid, and that it
1321
can be applied against the base, and generate the same information.
1323
:return: The in-memory bundle
1325
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1327
# This should also validate the generated bundle
1328
bundle = read_bundle(bundle_txt)
1329
repository = self.b1.repository
1330
for bundle_rev in bundle.real_revisions:
1331
# These really should have already been checked when we read the
1332
# bundle, since it computes the sha1 hash for the revision, which
1333
# only will match if everything is okay, but lets be explicit about
1335
branch_rev = repository.get_revision(bundle_rev.revision_id)
1336
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
1337
'timestamp', 'timezone', 'message', 'committer',
1338
'parent_ids', 'properties'):
1339
self.assertEqual(getattr(branch_rev, a),
1340
getattr(bundle_rev, a))
1341
self.assertEqual(len(branch_rev.parent_ids),
1342
len(bundle_rev.parent_ids))
1343
self.assertEqual(set(rev_ids),
1344
{r.revision_id for r in bundle.real_revisions})
1345
self.valid_apply_bundle(base_rev_id, bundle,
1346
checkout_dir=checkout_dir)
1350
def get_invalid_bundle(self, base_rev_id, rev_id):
1351
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1352
Munge the text so that it's invalid.
1354
:return: The in-memory bundle
1356
from ..bundle import serializer
1357
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1358
new_text = self.get_raw(BytesIO(b''.join(bundle_txt)))
1359
new_text = new_text.replace('<file file_id="exe-1"',
1360
'<file executable="y" file_id="exe-1"')
1361
new_text = new_text.replace('B260', 'B275')
1362
bundle_txt = BytesIO()
1363
bundle_txt.write(serializer._get_bundle_header('4'))
1364
bundle_txt.write('\n')
1365
bundle_txt.write(new_text.encode('bz2'))
1367
bundle = read_bundle(bundle_txt)
1368
self.valid_apply_bundle(base_rev_id, bundle)
1371
def create_bundle_text(self, base_rev_id, rev_id):
1372
bundle_txt = BytesIO()
1373
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
1374
bundle_txt, format=self.format)
1376
self.assertEqual(bundle_txt.readline(),
1377
'# Bazaar revision bundle v%s\n' % self.format)
1378
self.assertEqual(bundle_txt.readline(), '#\n')
1379
rev = self.b1.repository.get_revision(rev_id)
1381
return bundle_txt, rev_ids
1383
def get_bundle_tree(self, bundle, revision_id):
1384
repository = self.make_repository('repo')
1385
bundle.install_revisions(repository)
1386
return repository.revision_tree(revision_id)
1388
def test_creation(self):
1389
tree = self.make_branch_and_tree('tree')
1390
self.build_tree_contents([('tree/file', 'contents1\nstatic\n')])
1391
tree.add('file', 'fileid-2')
1392
tree.commit('added file', rev_id='rev1')
1393
self.build_tree_contents([('tree/file', 'contents2\nstatic\n')])
1394
tree.commit('changed file', rev_id='rev2')
1396
serializer = BundleSerializerV4('1.0')
1397
serializer.write(tree.branch.repository, ['rev1', 'rev2'], {}, s)
1399
tree2 = self.make_branch_and_tree('target')
1400
target_repo = tree2.branch.repository
1401
install_bundle(target_repo, serializer.read(s))
1402
target_repo.lock_read()
1403
self.addCleanup(target_repo.unlock)
1404
# Turn the 'iterators_of_bytes' back into simple strings for comparison
1405
repo_texts = dict((i, ''.join(content)) for i, content
1406
in target_repo.iter_files_bytes(
1407
[('fileid-2', 'rev1', '1'),
1408
('fileid-2', 'rev2', '2')]))
1409
self.assertEqual({'1':'contents1\nstatic\n',
1410
'2':'contents2\nstatic\n'},
1412
rtree = target_repo.revision_tree('rev2')
1413
inventory_vf = target_repo.inventories
1414
# If the inventory store has a graph, it must match the revision graph.
1416
[inventory_vf.get_parent_map([('rev2',)])[('rev2',)]],
1417
[None, (('rev1',),)])
1418
self.assertEqual('changed file',
1419
target_repo.get_revision('rev2').message)
1422
def get_raw(bundle_file):
1424
line = bundle_file.readline()
1425
line = bundle_file.readline()
1426
lines = bundle_file.readlines()
1427
return ''.join(lines).decode('bz2')
1429
def test_copy_signatures(self):
1430
tree_a = self.make_branch_and_tree('tree_a')
1432
import breezy.commit as commit
1433
oldstrategy = breezy.gpg.GPGStrategy
1434
branch = tree_a.branch
1435
repo_a = branch.repository
1436
tree_a.commit("base", allow_pointless=True, rev_id='A')
1437
self.assertFalse(branch.repository.has_signature_for_revision_id('A'))
1439
from ..testament import Testament
1440
# monkey patch gpg signing mechanism
1441
breezy.gpg.GPGStrategy = breezy.gpg.LoopbackGPGStrategy
1442
new_config = test_commit.MustSignConfig()
1443
commit.Commit(config_stack=new_config).commit(message="base",
1444
allow_pointless=True,
1446
working_tree=tree_a)
1448
return breezy.gpg.LoopbackGPGStrategy(None).sign(text)
1449
self.assertTrue(repo_a.has_signature_for_revision_id('B'))
1451
breezy.gpg.GPGStrategy = oldstrategy
1452
tree_b = self.make_branch_and_tree('tree_b')
1453
repo_b = tree_b.branch.repository
1455
serializer = BundleSerializerV4('4')
1456
serializer.write(tree_a.branch.repository, ['A', 'B'], {}, s)
1458
install_bundle(repo_b, serializer.read(s))
1459
self.assertTrue(repo_b.has_signature_for_revision_id('B'))
1460
self.assertEqual(repo_b.get_signature_text('B'),
1461
repo_a.get_signature_text('B'))
1463
# ensure repeat installs are harmless
1464
install_bundle(repo_b, serializer.read(s))
1467
class V4_2aBundleTester(V4BundleTester):
1469
def bzrdir_format(self):
1472
def get_invalid_bundle(self, base_rev_id, rev_id):
1473
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1474
Munge the text so that it's invalid.
1476
:return: The in-memory bundle
1478
from ..bundle import serializer
1479
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1480
new_text = self.get_raw(BytesIO(b''.join(bundle_txt)))
1481
# We are going to be replacing some text to set the executable bit on a
1482
# file. Make sure the text replacement actually works correctly.
1483
self.assertContainsRe(new_text, '(?m)B244\n\ni 1\n<inventory')
1484
new_text = new_text.replace('<file file_id="exe-1"',
1485
'<file executable="y" file_id="exe-1"')
1486
new_text = new_text.replace('B244', 'B259')
1487
bundle_txt = BytesIO()
1488
bundle_txt.write(serializer._get_bundle_header('4'))
1489
bundle_txt.write('\n')
1490
bundle_txt.write(new_text.encode('bz2'))
1492
bundle = read_bundle(bundle_txt)
1493
self.valid_apply_bundle(base_rev_id, bundle)
1496
def make_merged_branch(self):
1497
builder = self.make_branch_builder('source')
1498
builder.start_series()
1499
builder.build_snapshot('a@cset-0-1', None, [
1500
('add', ('', 'root-id', 'directory', None)),
1501
('add', ('file', 'file-id', 'file', 'original content\n')),
1503
builder.build_snapshot('a@cset-0-2a', ['a@cset-0-1'], [
1504
('modify', ('file-id', 'new-content\n')),
1506
builder.build_snapshot('a@cset-0-2b', ['a@cset-0-1'], [
1507
('add', ('other-file', 'file2-id', 'file', 'file2-content\n')),
1509
builder.build_snapshot('a@cset-0-3', ['a@cset-0-2a', 'a@cset-0-2b'], [
1510
('add', ('other-file', 'file2-id', 'file', 'file2-content\n')),
1512
builder.finish_series()
1513
self.b1 = builder.get_branch()
1515
self.addCleanup(self.b1.unlock)
1517
def make_bundle_just_inventories(self, base_revision_id,
1521
writer = v4.BundleWriteOperation(base_revision_id, target_revision_id,
1522
self.b1.repository, sio)
1523
writer.bundle.begin()
1524
writer._add_inventory_mpdiffs_from_serializer(revision_ids)
1529
def test_single_inventory_multiple_parents_as_xml(self):
1530
self.make_merged_branch()
1531
sio = self.make_bundle_just_inventories('a@cset-0-1', 'a@cset-0-3',
1533
reader = v4.BundleReader(sio, stream_input=False)
1534
records = list(reader.iter_records())
1535
self.assertEqual(1, len(records))
1536
(bytes, metadata, repo_kind, revision_id,
1537
file_id) = records[0]
1538
self.assertIs(None, file_id)
1539
self.assertEqual('a@cset-0-3', revision_id)
1540
self.assertEqual('inventory', repo_kind)
1541
self.assertEqual({'parents': ['a@cset-0-2a', 'a@cset-0-2b'],
1542
'sha1': '09c53b0c4de0895e11a2aacc34fef60a6e70865c',
1543
'storage_kind': 'mpdiff',
1545
# We should have an mpdiff that takes some lines from both parents.
1546
self.assertEqualDiff(
1548
'<inventory format="10" revision_id="a@cset-0-3">\n'
1551
'c 1 3 3 2\n', bytes)
1553
def test_single_inv_no_parents_as_xml(self):
1554
self.make_merged_branch()
1555
sio = self.make_bundle_just_inventories('null:', 'a@cset-0-1',
1557
reader = v4.BundleReader(sio, stream_input=False)
1558
records = list(reader.iter_records())
1559
self.assertEqual(1, len(records))
1560
(bytes, metadata, repo_kind, revision_id,
1561
file_id) = records[0]
1562
self.assertIs(None, file_id)
1563
self.assertEqual('a@cset-0-1', revision_id)
1564
self.assertEqual('inventory', repo_kind)
1565
self.assertEqual({'parents': [],
1566
'sha1': 'a13f42b142d544aac9b085c42595d304150e31a2',
1567
'storage_kind': 'mpdiff',
1569
# We should have an mpdiff that takes some lines from both parents.
1570
self.assertEqualDiff(
1572
'<inventory format="10" revision_id="a@cset-0-1">\n'
1573
'<directory file_id="root-id" name=""'
1574
' revision="a@cset-0-1" />\n'
1575
'<file file_id="file-id" name="file" parent_id="root-id"'
1576
' revision="a@cset-0-1"'
1577
' text_sha1="09c2f8647e14e49e922b955c194102070597c2d1"'
1578
' text_size="17" />\n'
1582
def test_multiple_inventories_as_xml(self):
1583
self.make_merged_branch()
1584
sio = self.make_bundle_just_inventories('a@cset-0-1', 'a@cset-0-3',
1585
['a@cset-0-2a', 'a@cset-0-2b', 'a@cset-0-3'])
1586
reader = v4.BundleReader(sio, stream_input=False)
1587
records = list(reader.iter_records())
1588
self.assertEqual(3, len(records))
1589
revision_ids = [rev_id for b, m, k, rev_id, f in records]
1590
self.assertEqual(['a@cset-0-2a', 'a@cset-0-2b', 'a@cset-0-3'],
1592
metadata_2a = records[0][1]
1593
self.assertEqual({'parents': ['a@cset-0-1'],
1594
'sha1': '1e105886d62d510763e22885eec733b66f5f09bf',
1595
'storage_kind': 'mpdiff',
1597
metadata_2b = records[1][1]
1598
self.assertEqual({'parents': ['a@cset-0-1'],
1599
'sha1': 'f03f12574bdb5ed2204c28636c98a8547544ccd8',
1600
'storage_kind': 'mpdiff',
1602
metadata_3 = records[2][1]
1603
self.assertEqual({'parents': ['a@cset-0-2a', 'a@cset-0-2b'],
1604
'sha1': '09c53b0c4de0895e11a2aacc34fef60a6e70865c',
1605
'storage_kind': 'mpdiff',
1607
bytes_2a = records[0][0]
1608
self.assertEqualDiff(
1610
'<inventory format="10" revision_id="a@cset-0-2a">\n'
1614
'<file file_id="file-id" name="file" parent_id="root-id"'
1615
' revision="a@cset-0-2a"'
1616
' text_sha1="50f545ff40e57b6924b1f3174b267ffc4576e9a9"'
1617
' text_size="12" />\n'
1619
'c 0 3 3 1\n', bytes_2a)
1620
bytes_2b = records[1][0]
1621
self.assertEqualDiff(
1623
'<inventory format="10" revision_id="a@cset-0-2b">\n'
1627
'<file file_id="file2-id" name="other-file" parent_id="root-id"'
1628
' revision="a@cset-0-2b"'
1629
' text_sha1="b46c0c8ea1e5ef8e46fc8894bfd4752a88ec939e"'
1630
' text_size="14" />\n'
1632
'c 0 3 4 1\n', bytes_2b)
1633
bytes_3 = records[2][0]
1634
self.assertEqualDiff(
1636
'<inventory format="10" revision_id="a@cset-0-3">\n'
1639
'c 1 3 3 2\n', bytes_3)
1641
def test_creating_bundle_preserves_chk_pages(self):
1642
self.make_merged_branch()
1643
target = self.b1.controldir.sprout('target',
1644
revision_id='a@cset-0-2a').open_branch()
1645
bundle_txt, rev_ids = self.create_bundle_text('a@cset-0-2a',
1647
self.assertEqual(['a@cset-0-2b', 'a@cset-0-3'], rev_ids)
1648
bundle = read_bundle(bundle_txt)
1650
self.addCleanup(target.unlock)
1651
install_bundle(target.repository, bundle)
1652
inv1 = self.b1.repository.inventories.get_record_stream([
1653
('a@cset-0-3',)], 'unordered',
1654
True).next().get_bytes_as('fulltext')
1655
inv2 = target.repository.inventories.get_record_stream([
1656
('a@cset-0-3',)], 'unordered',
1657
True).next().get_bytes_as('fulltext')
1658
self.assertEqualDiff(inv1, inv2)
1661
class MungedBundleTester(object):
1663
def build_test_bundle(self):
1664
wt = self.make_branch_and_tree('b1')
1666
self.build_tree(['b1/one'])
1668
wt.commit('add one', rev_id='a@cset-0-1')
1669
self.build_tree(['b1/two'])
1671
wt.commit('add two', rev_id='a@cset-0-2',
1672
revprops={'branch-nick':'test'})
1674
bundle_txt = BytesIO()
1675
rev_ids = write_bundle(wt.branch.repository, 'a@cset-0-2',
1676
'a@cset-0-1', bundle_txt, self.format)
1677
self.assertEqual({'a@cset-0-2'}, set(rev_ids))
1678
bundle_txt.seek(0, 0)
1681
def check_valid(self, bundle):
1682
"""Check that after whatever munging, the final object is valid."""
1683
self.assertEqual(['a@cset-0-2'],
1684
[r.revision_id for r in bundle.real_revisions])
1686
def test_extra_whitespace(self):
1687
bundle_txt = self.build_test_bundle()
1689
# Seek to the end of the file
1690
# Adding one extra newline used to give us
1691
# TypeError: float() argument must be a string or a number
1692
bundle_txt.seek(0, 2)
1693
bundle_txt.write('\n')
1696
bundle = read_bundle(bundle_txt)
1697
self.check_valid(bundle)
1699
def test_extra_whitespace_2(self):
1700
bundle_txt = self.build_test_bundle()
1702
# Seek to the end of the file
1703
# Adding two extra newlines used to give us
1704
# MalformedPatches: The first line of all patches should be ...
1705
bundle_txt.seek(0, 2)
1706
bundle_txt.write('\n\n')
1709
bundle = read_bundle(bundle_txt)
1710
self.check_valid(bundle)
1713
class MungedBundleTesterV09(tests.TestCaseWithTransport, MungedBundleTester):
1717
def test_missing_trailing_whitespace(self):
1718
bundle_txt = self.build_test_bundle()
1720
# Remove a trailing newline, it shouldn't kill the parser
1721
raw = bundle_txt.getvalue()
1722
# The contents of the bundle don't have to be this, but this
1723
# test is concerned with the exact case where the serializer
1724
# creates a blank line at the end, and fails if that
1726
self.assertEqual('\n\n', raw[-2:])
1727
bundle_txt = BytesIO(raw[:-1])
1729
bundle = read_bundle(bundle_txt)
1730
self.check_valid(bundle)
1732
def test_opening_text(self):
1733
bundle_txt = self.build_test_bundle()
1735
bundle_txt = BytesIO(
1736
b"Some random\nemail comments\n" + bundle_txt.getvalue())
1738
bundle = read_bundle(bundle_txt)
1739
self.check_valid(bundle)
1741
def test_trailing_text(self):
1742
bundle_txt = self.build_test_bundle()
1744
bundle_txt = BytesIO(
1745
bundle_txt.getvalue() + b"Some trailing\nrandom\ntext\n")
1747
bundle = read_bundle(bundle_txt)
1748
self.check_valid(bundle)
1751
class MungedBundleTesterV4(tests.TestCaseWithTransport, MungedBundleTester):
1756
class TestBundleWriterReader(tests.TestCase):
1758
def test_roundtrip_record(self):
1760
writer = v4.BundleWriter(fileobj)
1762
writer.add_info_record(foo='bar')
1763
writer._add_record("Record body", {'parents': ['1', '3'],
1764
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1767
reader = v4.BundleReader(fileobj, stream_input=True)
1768
record_iter = reader.iter_records()
1769
record = next(record_iter)
1770
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1771
'info', None, None), record)
1772
record = next(record_iter)
1773
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1774
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1777
def test_roundtrip_record_memory_hungry(self):
1779
writer = v4.BundleWriter(fileobj)
1781
writer.add_info_record(foo='bar')
1782
writer._add_record("Record body", {'parents': ['1', '3'],
1783
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1786
reader = v4.BundleReader(fileobj, stream_input=False)
1787
record_iter = reader.iter_records()
1788
record = next(record_iter)
1789
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1790
'info', None, None), record)
1791
record = next(record_iter)
1792
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1793
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1796
def test_encode_name(self):
1797
self.assertEqual('revision/rev1',
1798
v4.BundleWriter.encode_name('revision', 'rev1'))
1799
self.assertEqual('file/rev//1/file-id-1',
1800
v4.BundleWriter.encode_name('file', 'rev/1', 'file-id-1'))
1801
self.assertEqual('info',
1802
v4.BundleWriter.encode_name('info', None, None))
1804
def test_decode_name(self):
1805
self.assertEqual(('revision', 'rev1', None),
1806
v4.BundleReader.decode_name('revision/rev1'))
1807
self.assertEqual(('file', 'rev/1', 'file-id-1'),
1808
v4.BundleReader.decode_name('file/rev//1/file-id-1'))
1809
self.assertEqual(('info', None, None),
1810
v4.BundleReader.decode_name('info'))
1812
def test_too_many_names(self):
1814
writer = v4.BundleWriter(fileobj)
1816
writer.add_info_record(foo='bar')
1817
writer._container.add_bytes_record('blah', ['two', 'names'])
1820
record_iter = v4.BundleReader(fileobj).iter_records()
1821
record = next(record_iter)
1822
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1823
'info', None, None), record)
1824
self.assertRaises(errors.BadBundle, next, record_iter)
1827
class TestReadMergeableFromUrl(tests.TestCaseWithTransport):
1829
def test_read_mergeable_skips_local(self):
1830
"""A local bundle named like the URL should not be read.
1832
out, wt = test_read_bundle.create_bundle_file(self)
1833
class FooService(object):
1834
"""A directory service that always returns source"""
1836
def look_up(self, name, url):
1838
directories.register('foo:', FooService, 'Testing directory service')
1839
self.addCleanup(directories.remove, 'foo:')
1840
self.build_tree_contents([('./foo:bar', out.getvalue())])
1841
self.assertRaises(errors.NotABundle, read_mergeable_from_url,
1844
def test_infinite_redirects_are_not_a_bundle(self):
1845
"""If a URL causes TooManyRedirections then NotABundle is raised.
1847
from .blackbox.test_push import RedirectingMemoryServer
1848
server = RedirectingMemoryServer()
1849
self.start_server(server)
1850
url = server.get_url() + 'infinite-loop'
1851
self.assertRaises(errors.NotABundle, read_mergeable_from_url, url)
1853
def test_smart_server_connection_reset(self):
1854
"""If a smart server connection fails during the attempt to read a
1855
bundle, then the ConnectionReset error should be propagated.
1857
# Instantiate a server that will provoke a ConnectionReset
1858
sock_server = DisconnectingServer()
1859
self.start_server(sock_server)
1860
# We don't really care what the url is since the server will close the
1861
# connection without interpreting it
1862
url = sock_server.get_url()
1863
self.assertRaises(errors.ConnectionReset, read_mergeable_from_url, url)
1866
class DisconnectingHandler(socketserver.BaseRequestHandler):
1867
"""A request handler that immediately closes any connection made to it."""
1870
self.request.close()
1873
class DisconnectingServer(test_server.TestingTCPServerInAThread):
1876
super(DisconnectingServer, self).__init__(
1878
test_server.TestingTCPServer,
1879
DisconnectingHandler)
1882
"""Return the url of the server"""
1883
return "bzr://%s:%d/" % self.server.server_address