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
31
revision as _mod_revision,
35
from ..bundle import read_mergeable_from_url
36
from ..bundle.apply_bundle import install_bundle, merge_bundle
37
from ..bundle.bundle_data import BundleTree
38
from ..directory_service import directories
39
from ..bundle.serializer import write_bundle, read_bundle, v09, v4
40
from ..bundle.serializer.v08 import BundleSerializerV08
41
from ..bundle.serializer.v09 import BundleSerializerV09
42
from ..bundle.serializer.v4 import BundleSerializerV4
43
from ..repofmt import knitrepo
44
from ..sixish import (
53
from ..transform import TreeTransform
56
def get_text(vf, key):
57
"""Get the fulltext for a given revision id that is present in the vf"""
58
stream = vf.get_record_stream([key], 'unordered', True)
60
return record.get_bytes_as('fulltext')
63
def get_inventory_text(repo, revision_id):
64
"""Get the fulltext for the inventory at revision id"""
67
return get_text(repo.inventories, (revision_id,))
72
class MockTree(object):
75
from ..inventory import InventoryDirectory, ROOT_ID
77
self.paths = {ROOT_ID: ""}
78
self.ids = {"": ROOT_ID}
80
self.root = InventoryDirectory(ROOT_ID, '', None)
82
inventory = property(lambda x:x)
83
root_inventory = property(lambda x:x)
85
def get_root_id(self):
86
return self.root.file_id
88
def all_file_ids(self):
89
return set(self.paths.keys())
91
def is_executable(self, file_id):
92
# Not all the files are executable.
95
def __getitem__(self, file_id):
96
if file_id == self.root.file_id:
99
return self.make_entry(file_id, self.paths[file_id])
101
def parent_id(self, file_id):
102
parent_dir = os.path.dirname(self.paths[file_id])
105
return self.ids[parent_dir]
107
def iter_entries(self):
108
for path, file_id in self.ids.items():
109
yield path, self[file_id]
111
def kind(self, file_id):
112
if file_id in self.contents:
118
def make_entry(self, file_id, path):
119
from ..inventory import (InventoryFile , InventoryDirectory,
121
name = os.path.basename(path)
122
kind = self.kind(file_id)
123
parent_id = self.parent_id(file_id)
124
text_sha_1, text_size = self.contents_stats(file_id)
125
if kind == 'directory':
126
ie = InventoryDirectory(file_id, name, parent_id)
128
ie = InventoryFile(file_id, name, parent_id)
129
ie.text_sha1 = text_sha_1
130
ie.text_size = text_size
131
elif kind == 'symlink':
132
ie = InventoryLink(file_id, name, parent_id)
134
raise errors.BzrError('unknown kind %r' % kind)
137
def add_dir(self, file_id, path):
138
self.paths[file_id] = path
139
self.ids[path] = file_id
141
def add_file(self, file_id, path, contents):
142
self.add_dir(file_id, path)
143
self.contents[file_id] = contents
145
def path2id(self, path):
146
return self.ids.get(path)
148
def id2path(self, file_id):
149
return self.paths.get(file_id)
151
def has_id(self, file_id):
152
return self.id2path(file_id) is not None
154
def get_file(self, file_id):
156
result.write(self.contents[file_id])
160
def get_file_revision(self, file_id):
161
return self.inventory[file_id].revision
163
def get_file_size(self, file_id):
164
return self.inventory[file_id].text_size
166
def get_file_sha1(self, file_id):
167
return self.inventory[file_id].text_sha1
169
def contents_stats(self, file_id):
170
if file_id not in self.contents:
172
text_sha1 = osutils.sha_file(self.get_file(file_id))
173
return text_sha1, len(self.contents[file_id])
176
class BTreeTester(tests.TestCase):
177
"""A simple unittest tester for the BundleTree class."""
179
def make_tree_1(self):
181
mtree.add_dir("a", "grandparent")
182
mtree.add_dir("b", "grandparent/parent")
183
mtree.add_file("c", "grandparent/parent/file", "Hello\n")
184
mtree.add_dir("d", "grandparent/alt_parent")
185
return BundleTree(mtree, ''), mtree
187
def test_renames(self):
188
"""Ensure that file renames have the proper effect on children"""
189
btree = self.make_tree_1()[0]
190
self.assertEqual(btree.old_path("grandparent"), "grandparent")
191
self.assertEqual(btree.old_path("grandparent/parent"),
192
"grandparent/parent")
193
self.assertEqual(btree.old_path("grandparent/parent/file"),
194
"grandparent/parent/file")
196
self.assertEqual(btree.id2path("a"), "grandparent")
197
self.assertEqual(btree.id2path("b"), "grandparent/parent")
198
self.assertEqual(btree.id2path("c"), "grandparent/parent/file")
200
self.assertEqual(btree.path2id("grandparent"), "a")
201
self.assertEqual(btree.path2id("grandparent/parent"), "b")
202
self.assertEqual(btree.path2id("grandparent/parent/file"), "c")
204
self.assertTrue(btree.path2id("grandparent2") is None)
205
self.assertTrue(btree.path2id("grandparent2/parent") is None)
206
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
208
btree.note_rename("grandparent", "grandparent2")
209
self.assertTrue(btree.old_path("grandparent") is None)
210
self.assertTrue(btree.old_path("grandparent/parent") is None)
211
self.assertTrue(btree.old_path("grandparent/parent/file") is None)
213
self.assertEqual(btree.id2path("a"), "grandparent2")
214
self.assertEqual(btree.id2path("b"), "grandparent2/parent")
215
self.assertEqual(btree.id2path("c"), "grandparent2/parent/file")
217
self.assertEqual(btree.path2id("grandparent2"), "a")
218
self.assertEqual(btree.path2id("grandparent2/parent"), "b")
219
self.assertEqual(btree.path2id("grandparent2/parent/file"), "c")
221
self.assertTrue(btree.path2id("grandparent") is None)
222
self.assertTrue(btree.path2id("grandparent/parent") is None)
223
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
225
btree.note_rename("grandparent/parent", "grandparent2/parent2")
226
self.assertEqual(btree.id2path("a"), "grandparent2")
227
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
228
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file")
230
self.assertEqual(btree.path2id("grandparent2"), "a")
231
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
232
self.assertEqual(btree.path2id("grandparent2/parent2/file"), "c")
234
self.assertTrue(btree.path2id("grandparent2/parent") is None)
235
self.assertTrue(btree.path2id("grandparent2/parent/file") is None)
237
btree.note_rename("grandparent/parent/file",
238
"grandparent2/parent2/file2")
239
self.assertEqual(btree.id2path("a"), "grandparent2")
240
self.assertEqual(btree.id2path("b"), "grandparent2/parent2")
241
self.assertEqual(btree.id2path("c"), "grandparent2/parent2/file2")
243
self.assertEqual(btree.path2id("grandparent2"), "a")
244
self.assertEqual(btree.path2id("grandparent2/parent2"), "b")
245
self.assertEqual(btree.path2id("grandparent2/parent2/file2"), "c")
247
self.assertTrue(btree.path2id("grandparent2/parent2/file") is None)
249
def test_moves(self):
250
"""Ensure that file moves have the proper effect on children"""
251
btree = self.make_tree_1()[0]
252
btree.note_rename("grandparent/parent/file",
253
"grandparent/alt_parent/file")
254
self.assertEqual(btree.id2path("c"), "grandparent/alt_parent/file")
255
self.assertEqual(btree.path2id("grandparent/alt_parent/file"), "c")
256
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
258
def unified_diff(self, old, new):
260
diff.internal_diff("old", old, "new", new, out)
264
def make_tree_2(self):
265
btree = self.make_tree_1()[0]
266
btree.note_rename("grandparent/parent/file",
267
"grandparent/alt_parent/file")
268
self.assertTrue(btree.id2path("e") is None)
269
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
270
btree.note_id("e", "grandparent/parent/file")
274
"""File/inventory adds"""
275
btree = self.make_tree_2()
276
add_patch = self.unified_diff([], ["Extra cheese\n"])
277
btree.note_patch("grandparent/parent/file", add_patch)
278
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
279
btree.note_target('grandparent/parent/symlink', 'venus')
280
self.adds_test(btree)
282
def adds_test(self, btree):
283
self.assertEqual(btree.id2path("e"), "grandparent/parent/file")
284
self.assertEqual(btree.path2id("grandparent/parent/file"), "e")
285
self.assertEqual(btree.get_file("e").read(), "Extra cheese\n")
286
self.assertEqual(btree.get_symlink_target('f'), 'venus')
288
def test_adds2(self):
289
"""File/inventory adds, with patch-compatibile renames"""
290
btree = self.make_tree_2()
291
btree.contents_by_id = False
292
add_patch = self.unified_diff(["Hello\n"], ["Extra cheese\n"])
293
btree.note_patch("grandparent/parent/file", add_patch)
294
btree.note_id('f', 'grandparent/parent/symlink', kind='symlink')
295
btree.note_target('grandparent/parent/symlink', 'venus')
296
self.adds_test(btree)
298
def make_tree_3(self):
299
btree, mtree = self.make_tree_1()
300
mtree.add_file("e", "grandparent/parent/topping", "Anchovies\n")
301
btree.note_rename("grandparent/parent/file",
302
"grandparent/alt_parent/file")
303
btree.note_rename("grandparent/parent/topping",
304
"grandparent/alt_parent/stopping")
307
def get_file_test(self, btree):
308
self.assertEqual(btree.get_file("e").read(), "Lemon\n")
309
self.assertEqual(btree.get_file("c").read(), "Hello\n")
311
def test_get_file(self):
312
"""Get file contents"""
313
btree = self.make_tree_3()
314
mod_patch = self.unified_diff(["Anchovies\n"], ["Lemon\n"])
315
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
316
self.get_file_test(btree)
318
def test_get_file2(self):
319
"""Get file contents, with patch-compatibile renames"""
320
btree = self.make_tree_3()
321
btree.contents_by_id = False
322
mod_patch = self.unified_diff([], ["Lemon\n"])
323
btree.note_patch("grandparent/alt_parent/stopping", mod_patch)
324
mod_patch = self.unified_diff([], ["Hello\n"])
325
btree.note_patch("grandparent/alt_parent/file", mod_patch)
326
self.get_file_test(btree)
328
def test_delete(self):
330
btree = self.make_tree_1()[0]
331
self.assertEqual(btree.get_file("c").read(), "Hello\n")
332
btree.note_deletion("grandparent/parent/file")
333
self.assertTrue(btree.id2path("c") is None)
334
self.assertTrue(btree.path2id("grandparent/parent/file") is None)
336
def sorted_ids(self, tree):
337
ids = sorted(tree.all_file_ids())
340
def test_iteration(self):
341
"""Ensure that iteration through ids works properly"""
342
btree = self.make_tree_1()[0]
343
self.assertEqual(self.sorted_ids(btree),
344
[inventory.ROOT_ID, 'a', 'b', 'c', 'd'])
345
btree.note_deletion("grandparent/parent/file")
346
btree.note_id("e", "grandparent/alt_parent/fool", kind="directory")
347
btree.note_last_changed("grandparent/alt_parent/fool",
349
self.assertEqual(self.sorted_ids(btree),
350
[inventory.ROOT_ID, 'a', 'b', 'd', 'e'])
353
class BundleTester1(tests.TestCaseWithTransport):
355
def test_mismatched_bundle(self):
356
format = bzrdir.BzrDirMetaFormat1()
357
format.repository_format = knitrepo.RepositoryFormatKnit3()
358
serializer = BundleSerializerV08('0.8')
359
b = self.make_branch('.', format=format)
360
self.assertRaises(errors.IncompatibleBundleFormat, serializer.write,
361
b.repository, [], {}, BytesIO())
363
def test_matched_bundle(self):
364
"""Don't raise IncompatibleBundleFormat for knit2 and bundle0.9"""
365
format = bzrdir.BzrDirMetaFormat1()
366
format.repository_format = knitrepo.RepositoryFormatKnit3()
367
serializer = BundleSerializerV09('0.9')
368
b = self.make_branch('.', format=format)
369
serializer.write(b.repository, [], {}, BytesIO())
371
def test_mismatched_model(self):
372
"""Try copying a bundle from knit2 to knit1"""
373
format = bzrdir.BzrDirMetaFormat1()
374
format.repository_format = knitrepo.RepositoryFormatKnit3()
375
source = self.make_branch_and_tree('source', format=format)
376
source.commit('one', rev_id='one-id')
377
source.commit('two', rev_id='two-id')
379
write_bundle(source.branch.repository, 'two-id', 'null:', text,
383
format = bzrdir.BzrDirMetaFormat1()
384
format.repository_format = knitrepo.RepositoryFormatKnit1()
385
target = self.make_branch('target', format=format)
386
self.assertRaises(errors.IncompatibleRevision, install_bundle,
387
target.repository, read_bundle(text))
390
class BundleTester(object):
392
def bzrdir_format(self):
393
format = bzrdir.BzrDirMetaFormat1()
394
format.repository_format = knitrepo.RepositoryFormatKnit1()
397
def make_branch_and_tree(self, path, format=None):
399
format = self.bzrdir_format()
400
return tests.TestCaseWithTransport.make_branch_and_tree(
403
def make_branch(self, path, format=None):
405
format = self.bzrdir_format()
406
return tests.TestCaseWithTransport.make_branch(self, path, format)
408
def create_bundle_text(self, base_rev_id, rev_id):
409
bundle_txt = BytesIO()
410
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
411
bundle_txt, format=self.format)
413
self.assertEqual(bundle_txt.readline(),
414
'# Bazaar revision bundle v%s\n' % self.format)
415
self.assertEqual(bundle_txt.readline(), '#\n')
417
rev = self.b1.repository.get_revision(rev_id)
418
self.assertEqual(bundle_txt.readline().decode('utf-8'),
421
return bundle_txt, rev_ids
423
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
424
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
425
Make sure that the text generated is valid, and that it
426
can be applied against the base, and generate the same information.
428
:return: The in-memory bundle
430
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
432
# This should also validate the generated bundle
433
bundle = read_bundle(bundle_txt)
434
repository = self.b1.repository
435
for bundle_rev in bundle.real_revisions:
436
# These really should have already been checked when we read the
437
# bundle, since it computes the sha1 hash for the revision, which
438
# only will match if everything is okay, but lets be explicit about
440
branch_rev = repository.get_revision(bundle_rev.revision_id)
441
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
442
'timestamp', 'timezone', 'message', 'committer',
443
'parent_ids', 'properties'):
444
self.assertEqual(getattr(branch_rev, a),
445
getattr(bundle_rev, a))
446
self.assertEqual(len(branch_rev.parent_ids),
447
len(bundle_rev.parent_ids))
448
self.assertEqual(rev_ids,
449
[r.revision_id for r in bundle.real_revisions])
450
self.valid_apply_bundle(base_rev_id, bundle,
451
checkout_dir=checkout_dir)
455
def get_invalid_bundle(self, base_rev_id, rev_id):
456
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
457
Munge the text so that it's invalid.
459
:return: The in-memory bundle
461
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
462
new_text = bundle_txt.getvalue().replace('executable:no',
464
bundle_txt = BytesIO(new_text)
465
bundle = read_bundle(bundle_txt)
466
self.valid_apply_bundle(base_rev_id, bundle)
469
def test_non_bundle(self):
470
self.assertRaises(errors.NotABundle,
471
read_bundle, BytesIO(b'#!/bin/sh\n'))
473
def test_malformed(self):
474
self.assertRaises(errors.BadBundle, read_bundle,
475
BytesIO(b'# Bazaar revision bundle v'))
477
def test_crlf_bundle(self):
479
read_bundle(BytesIO(b'# Bazaar revision bundle v0.8\r\n'))
480
except errors.BadBundle:
481
# It is currently permitted for bundles with crlf line endings to
482
# make read_bundle raise a BadBundle, but this should be fixed.
483
# Anything else, especially NotABundle, is an error.
486
def get_checkout(self, rev_id, checkout_dir=None):
487
"""Get a new tree, with the specified revision in it.
490
if checkout_dir is None:
491
checkout_dir = osutils.mkdtemp(prefix='test-branch-', dir='.')
493
if not os.path.exists(checkout_dir):
494
os.mkdir(checkout_dir)
495
tree = self.make_branch_and_tree(checkout_dir)
497
ancestors = write_bundle(self.b1.repository, rev_id, 'null:', s,
500
self.assertIsInstance(s.getvalue(), str)
501
install_bundle(tree.branch.repository, read_bundle(s))
502
for ancestor in ancestors:
503
old = self.b1.repository.revision_tree(ancestor)
504
new = tree.branch.repository.revision_tree(ancestor)
508
# Check that there aren't any inventory level changes
509
delta = new.changes_from(old)
510
self.assertFalse(delta.has_changed(),
511
'Revision %s not copied correctly.'
514
# Now check that the file contents are all correct
515
for inventory_id in old.all_file_ids():
517
old_file = old.get_file(inventory_id)
518
except errors.NoSuchFile:
522
self.assertEqual(old_file.read(),
523
new.get_file(inventory_id).read())
527
if not _mod_revision.is_null(rev_id):
528
tree.branch.generate_revision_history(rev_id)
530
delta = tree.changes_from(self.b1.repository.revision_tree(rev_id))
531
self.assertFalse(delta.has_changed(),
532
'Working tree has modifications: %s' % delta)
535
def valid_apply_bundle(self, base_rev_id, info, checkout_dir=None):
536
"""Get the base revision, apply the changes, and make
537
sure everything matches the builtin branch.
539
to_tree = self.get_checkout(base_rev_id, checkout_dir=checkout_dir)
542
self._valid_apply_bundle(base_rev_id, info, to_tree)
546
def _valid_apply_bundle(self, base_rev_id, info, to_tree):
547
original_parents = to_tree.get_parent_ids()
548
repository = to_tree.branch.repository
549
original_parents = to_tree.get_parent_ids()
550
self.assertIs(repository.has_revision(base_rev_id), True)
551
for rev in info.real_revisions:
552
self.assertTrue(not repository.has_revision(rev.revision_id),
553
'Revision {%s} present before applying bundle'
555
merge_bundle(info, to_tree, True, merge.Merge3Merger, False, False)
557
for rev in info.real_revisions:
558
self.assertTrue(repository.has_revision(rev.revision_id),
559
'Missing revision {%s} after applying bundle'
562
self.assertTrue(to_tree.branch.repository.has_revision(info.target))
563
# Do we also want to verify that all the texts have been added?
565
self.assertEqual(original_parents + [info.target],
566
to_tree.get_parent_ids())
568
rev = info.real_revisions[-1]
569
base_tree = self.b1.repository.revision_tree(rev.revision_id)
570
to_tree = to_tree.branch.repository.revision_tree(rev.revision_id)
572
# TODO: make sure the target tree is identical to base tree
573
# we might also check the working tree.
575
base_files = list(base_tree.list_files())
576
to_files = list(to_tree.list_files())
577
self.assertEqual(len(base_files), len(to_files))
578
for base_file, to_file in zip(base_files, to_files):
579
self.assertEqual(base_file, to_file)
581
for path, status, kind, fileid, entry in base_files:
582
# Check that the meta information is the same
583
self.assertEqual(base_tree.get_file_size(fileid),
584
to_tree.get_file_size(fileid))
585
self.assertEqual(base_tree.get_file_sha1(fileid),
586
to_tree.get_file_sha1(fileid))
587
# Check that the contents are the same
588
# This is pretty expensive
589
# self.assertEqual(base_tree.get_file(fileid).read(),
590
# to_tree.get_file(fileid).read())
592
def test_bundle(self):
593
self.tree1 = self.make_branch_and_tree('b1')
594
self.b1 = self.tree1.branch
596
self.build_tree_contents([('b1/one', 'one\n')])
597
self.tree1.add('one', 'one-id')
598
self.tree1.set_root_id('root-id')
599
self.tree1.commit('add one', rev_id='a@cset-0-1')
601
bundle = self.get_valid_bundle('null:', 'a@cset-0-1')
603
# Make sure we can handle files with spaces, tabs, other
608
, 'b1/dir/filein subdir.c'
609
, 'b1/dir/WithCaps.txt'
610
, 'b1/dir/ pre space'
613
, 'b1/sub/sub/nonempty.txt'
615
self.build_tree_contents([('b1/sub/sub/emptyfile.txt', ''),
616
('b1/dir/nolastnewline.txt', 'bloop')])
617
tt = TreeTransform(self.tree1)
618
tt.new_file('executable', tt.root, '#!/bin/sh\n', 'exe-1', True)
620
# have to fix length of file-id so that we can predictably rewrite
621
# a (length-prefixed) record containing it later.
622
self.tree1.add('with space.txt', 'withspace-id')
625
, 'dir/filein subdir.c'
628
, 'dir/nolastnewline.txt'
631
, 'sub/sub/nonempty.txt'
632
, 'sub/sub/emptyfile.txt'
634
self.tree1.commit('add whitespace', rev_id='a@cset-0-2')
636
bundle = self.get_valid_bundle('a@cset-0-1', 'a@cset-0-2')
638
# Check a rollup bundle
639
bundle = self.get_valid_bundle('null:', 'a@cset-0-2')
643
['sub/sub/nonempty.txt'
644
, 'sub/sub/emptyfile.txt'
647
tt = TreeTransform(self.tree1)
648
trans_id = tt.trans_id_tree_file_id('exe-1')
649
tt.set_executability(False, trans_id)
651
self.tree1.commit('removed', rev_id='a@cset-0-3')
653
bundle = self.get_valid_bundle('a@cset-0-2', 'a@cset-0-3')
654
self.assertRaises((errors.TestamentMismatch,
655
errors.VersionedFileInvalidChecksum,
656
errors.BadBundle), self.get_invalid_bundle,
657
'a@cset-0-2', 'a@cset-0-3')
658
# Check a rollup bundle
659
bundle = self.get_valid_bundle('null:', 'a@cset-0-3')
661
# Now move the directory
662
self.tree1.rename_one('dir', 'sub/dir')
663
self.tree1.commit('rename dir', rev_id='a@cset-0-4')
665
bundle = self.get_valid_bundle('a@cset-0-3', 'a@cset-0-4')
666
# Check a rollup bundle
667
bundle = self.get_valid_bundle('null:', 'a@cset-0-4')
670
with open('b1/sub/dir/WithCaps.txt', 'ab') as f: f.write('\nAdding some text\n')
671
with open('b1/sub/dir/ pre space', 'ab') as f: f.write(
672
'\r\nAdding some\r\nDOS format lines\r\n')
673
with open('b1/sub/dir/nolastnewline.txt', 'ab') as f: f.write('\n')
674
self.tree1.rename_one('sub/dir/ pre space',
676
self.tree1.commit('Modified files', rev_id='a@cset-0-5')
677
bundle = self.get_valid_bundle('a@cset-0-4', 'a@cset-0-5')
679
self.tree1.rename_one('sub/dir/WithCaps.txt', 'temp')
680
self.tree1.rename_one('with space.txt', 'WithCaps.txt')
681
self.tree1.rename_one('temp', 'with space.txt')
682
self.tree1.commit(u'swap filenames', rev_id='a@cset-0-6',
684
bundle = self.get_valid_bundle('a@cset-0-5', 'a@cset-0-6')
685
other = self.get_checkout('a@cset-0-5')
686
tree1_inv = get_inventory_text(self.tree1.branch.repository,
688
tree2_inv = get_inventory_text(other.branch.repository,
690
self.assertEqualDiff(tree1_inv, tree2_inv)
691
other.rename_one('sub/dir/nolastnewline.txt', 'sub/nolastnewline.txt')
692
other.commit('rename file', rev_id='a@cset-0-6b')
693
self.tree1.merge_from_branch(other.branch)
694
self.tree1.commit(u'Merge', rev_id='a@cset-0-7',
696
bundle = self.get_valid_bundle('a@cset-0-6', 'a@cset-0-7')
698
def _test_symlink_bundle(self, link_name, link_target, new_link_target):
701
self.requireFeature(features.SymlinkFeature)
702
self.tree1 = self.make_branch_and_tree('b1')
703
self.b1 = self.tree1.branch
705
tt = TreeTransform(self.tree1)
706
tt.new_symlink(link_name, tt.root, link_target, link_id)
708
self.tree1.commit('add symlink', rev_id='l@cset-0-1')
709
bundle = self.get_valid_bundle('null:', 'l@cset-0-1')
710
if getattr(bundle ,'revision_tree', None) is not None:
711
# Not all bundle formats supports revision_tree
712
bund_tree = bundle.revision_tree(self.b1.repository, 'l@cset-0-1')
713
self.assertEqual(link_target, bund_tree.get_symlink_target(link_id))
715
tt = TreeTransform(self.tree1)
716
trans_id = tt.trans_id_tree_file_id(link_id)
717
tt.adjust_path('link2', tt.root, trans_id)
718
tt.delete_contents(trans_id)
719
tt.create_symlink(new_link_target, trans_id)
721
self.tree1.commit('rename and change symlink', rev_id='l@cset-0-2')
722
bundle = self.get_valid_bundle('l@cset-0-1', 'l@cset-0-2')
723
if getattr(bundle ,'revision_tree', None) is not None:
724
# Not all bundle formats supports revision_tree
725
bund_tree = bundle.revision_tree(self.b1.repository, 'l@cset-0-2')
726
self.assertEqual(new_link_target,
727
bund_tree.get_symlink_target(link_id))
729
tt = TreeTransform(self.tree1)
730
trans_id = tt.trans_id_tree_file_id(link_id)
731
tt.delete_contents(trans_id)
732
tt.create_symlink('jupiter', trans_id)
734
self.tree1.commit('just change symlink target', rev_id='l@cset-0-3')
735
bundle = self.get_valid_bundle('l@cset-0-2', 'l@cset-0-3')
737
tt = TreeTransform(self.tree1)
738
trans_id = tt.trans_id_tree_file_id(link_id)
739
tt.delete_contents(trans_id)
741
self.tree1.commit('Delete symlink', rev_id='l@cset-0-4')
742
bundle = self.get_valid_bundle('l@cset-0-3', 'l@cset-0-4')
744
def test_symlink_bundle(self):
745
self._test_symlink_bundle('link', 'bar/foo', 'mars')
747
def test_unicode_symlink_bundle(self):
748
self.requireFeature(features.UnicodeFilenameFeature)
749
self._test_symlink_bundle(u'\N{Euro Sign}link',
750
u'bar/\N{Euro Sign}foo',
751
u'mars\N{Euro Sign}')
753
def test_binary_bundle(self):
754
self.tree1 = self.make_branch_and_tree('b1')
755
self.b1 = self.tree1.branch
756
tt = TreeTransform(self.tree1)
759
tt.new_file('file', tt.root, '\x00\n\x00\r\x01\n\x02\r\xff', 'binary-1')
760
tt.new_file('file2', tt.root, '\x01\n\x02\r\x03\n\x04\r\xff',
763
self.tree1.commit('add binary', rev_id='b@cset-0-1')
764
self.get_valid_bundle('null:', 'b@cset-0-1')
767
tt = TreeTransform(self.tree1)
768
trans_id = tt.trans_id_tree_file_id('binary-1')
769
tt.delete_contents(trans_id)
771
self.tree1.commit('delete binary', rev_id='b@cset-0-2')
772
self.get_valid_bundle('b@cset-0-1', 'b@cset-0-2')
775
tt = TreeTransform(self.tree1)
776
trans_id = tt.trans_id_tree_file_id('binary-2')
777
tt.adjust_path('file3', tt.root, trans_id)
778
tt.delete_contents(trans_id)
779
tt.create_file('file\rcontents\x00\n\x00', trans_id)
781
self.tree1.commit('rename and modify binary', rev_id='b@cset-0-3')
782
self.get_valid_bundle('b@cset-0-2', 'b@cset-0-3')
785
tt = TreeTransform(self.tree1)
786
trans_id = tt.trans_id_tree_file_id('binary-2')
787
tt.delete_contents(trans_id)
788
tt.create_file('\x00file\rcontents', trans_id)
790
self.tree1.commit('just modify binary', rev_id='b@cset-0-4')
791
self.get_valid_bundle('b@cset-0-3', 'b@cset-0-4')
794
self.get_valid_bundle('null:', 'b@cset-0-4')
796
def test_last_modified(self):
797
self.tree1 = self.make_branch_and_tree('b1')
798
self.b1 = self.tree1.branch
799
tt = TreeTransform(self.tree1)
800
tt.new_file('file', tt.root, 'file', 'file')
802
self.tree1.commit('create file', rev_id='a@lmod-0-1')
804
tt = TreeTransform(self.tree1)
805
trans_id = tt.trans_id_tree_file_id('file')
806
tt.delete_contents(trans_id)
807
tt.create_file('file2', trans_id)
809
self.tree1.commit('modify text', rev_id='a@lmod-0-2a')
811
other = self.get_checkout('a@lmod-0-1')
812
tt = TreeTransform(other)
813
trans_id = tt.trans_id_tree_file_id('file')
814
tt.delete_contents(trans_id)
815
tt.create_file('file2', trans_id)
817
other.commit('modify text in another tree', rev_id='a@lmod-0-2b')
818
self.tree1.merge_from_branch(other.branch)
819
self.tree1.commit(u'Merge', rev_id='a@lmod-0-3',
821
self.tree1.commit(u'Merge', rev_id='a@lmod-0-4')
822
bundle = self.get_valid_bundle('a@lmod-0-2a', 'a@lmod-0-4')
824
def test_hide_history(self):
825
self.tree1 = self.make_branch_and_tree('b1')
826
self.b1 = self.tree1.branch
828
with open('b1/one', 'wb') as f: f.write('one\n')
829
self.tree1.add('one')
830
self.tree1.commit('add file', rev_id='a@cset-0-1')
831
with open('b1/one', 'wb') as f: f.write('two\n')
832
self.tree1.commit('modify', rev_id='a@cset-0-2')
833
with open('b1/one', 'wb') as f: f.write('three\n')
834
self.tree1.commit('modify', rev_id='a@cset-0-3')
835
bundle_file = BytesIO()
836
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-3',
837
'a@cset-0-1', bundle_file, format=self.format)
838
self.assertNotContainsRe(bundle_file.getvalue(), '\btwo\b')
839
self.assertContainsRe(self.get_raw(bundle_file), 'one')
840
self.assertContainsRe(self.get_raw(bundle_file), 'three')
842
def test_bundle_same_basis(self):
843
"""Ensure using the basis as the target doesn't cause an error"""
844
self.tree1 = self.make_branch_and_tree('b1')
845
self.tree1.commit('add file', rev_id='a@cset-0-1')
846
bundle_file = BytesIO()
847
rev_ids = write_bundle(self.tree1.branch.repository, 'a@cset-0-1',
848
'a@cset-0-1', bundle_file)
851
def get_raw(bundle_file):
852
return bundle_file.getvalue()
854
def test_unicode_bundle(self):
855
self.requireFeature(features.UnicodeFilenameFeature)
856
# Handle international characters
858
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
860
self.tree1 = self.make_branch_and_tree('b1')
861
self.b1 = self.tree1.branch
864
u'With international man of mystery\n'
865
u'William Dod\xe9\n').encode('utf-8'))
868
self.tree1.add([u'with Dod\N{Euro Sign}'], ['withdod-id'])
869
self.tree1.commit(u'i18n commit from William Dod\xe9',
870
rev_id='i18n-1', committer=u'William Dod\xe9')
873
bundle = self.get_valid_bundle('null:', 'i18n-1')
876
f = open(u'b1/with Dod\N{Euro Sign}', 'wb')
877
f.write(u'Modified \xb5\n'.encode('utf8'))
879
self.tree1.commit(u'modified', rev_id='i18n-2')
881
bundle = self.get_valid_bundle('i18n-1', 'i18n-2')
884
self.tree1.rename_one(u'with Dod\N{Euro Sign}', u'B\N{Euro Sign}gfors')
885
self.tree1.commit(u'renamed, the new i18n man', rev_id='i18n-3',
886
committer=u'Erik B\xe5gfors')
888
bundle = self.get_valid_bundle('i18n-2', 'i18n-3')
891
self.tree1.remove([u'B\N{Euro Sign}gfors'])
892
self.tree1.commit(u'removed', rev_id='i18n-4')
894
bundle = self.get_valid_bundle('i18n-3', 'i18n-4')
897
bundle = self.get_valid_bundle('null:', 'i18n-4')
900
def test_whitespace_bundle(self):
901
if sys.platform in ('win32', 'cygwin'):
902
raise tests.TestSkipped('Windows doesn\'t support filenames'
903
' with tabs or trailing spaces')
904
self.tree1 = self.make_branch_and_tree('b1')
905
self.b1 = self.tree1.branch
907
self.build_tree(['b1/trailing space '])
908
self.tree1.add(['trailing space '])
909
# TODO: jam 20060701 Check for handling files with '\t' characters
910
# once we actually support them
913
self.tree1.commit('funky whitespace', rev_id='white-1')
915
bundle = self.get_valid_bundle('null:', 'white-1')
918
with open('b1/trailing space ', 'ab') as f: f.write('add some text\n')
919
self.tree1.commit('add text', rev_id='white-2')
921
bundle = self.get_valid_bundle('white-1', 'white-2')
924
self.tree1.rename_one('trailing space ', ' start and end space ')
925
self.tree1.commit('rename', rev_id='white-3')
927
bundle = self.get_valid_bundle('white-2', 'white-3')
930
self.tree1.remove([' start and end space '])
931
self.tree1.commit('removed', rev_id='white-4')
933
bundle = self.get_valid_bundle('white-3', 'white-4')
935
# Now test a complet roll-up
936
bundle = self.get_valid_bundle('null:', 'white-4')
938
def test_alt_timezone_bundle(self):
939
self.tree1 = self.make_branch_and_memory_tree('b1')
940
self.b1 = self.tree1.branch
941
builder = treebuilder.TreeBuilder()
943
self.tree1.lock_write()
944
builder.start_tree(self.tree1)
945
builder.build(['newfile'])
946
builder.finish_tree()
948
# Asia/Colombo offset = 5 hours 30 minutes
949
self.tree1.commit('non-hour offset timezone', rev_id='tz-1',
950
timezone=19800, timestamp=1152544886.0)
952
bundle = self.get_valid_bundle('null:', 'tz-1')
954
rev = bundle.revisions[0]
955
self.assertEqual('Mon 2006-07-10 20:51:26.000000000 +0530', rev.date)
956
self.assertEqual(19800, rev.timezone)
957
self.assertEqual(1152544886.0, rev.timestamp)
960
def test_bundle_root_id(self):
961
self.tree1 = self.make_branch_and_tree('b1')
962
self.b1 = self.tree1.branch
963
self.tree1.commit('message', rev_id='revid1')
964
bundle = self.get_valid_bundle('null:', 'revid1')
965
tree = self.get_bundle_tree(bundle, 'revid1')
966
root_revision = tree.get_file_revision(tree.get_root_id())
967
self.assertEqual('revid1', root_revision)
969
def test_install_revisions(self):
970
self.tree1 = self.make_branch_and_tree('b1')
971
self.b1 = self.tree1.branch
972
self.tree1.commit('message', rev_id='rev2a')
973
bundle = self.get_valid_bundle('null:', 'rev2a')
974
branch2 = self.make_branch('b2')
975
self.assertFalse(branch2.repository.has_revision('rev2a'))
976
target_revision = bundle.install_revisions(branch2.repository)
977
self.assertTrue(branch2.repository.has_revision('rev2a'))
978
self.assertEqual('rev2a', target_revision)
980
def test_bundle_empty_property(self):
981
"""Test serializing revision properties with an empty value."""
982
tree = self.make_branch_and_memory_tree('tree')
984
self.addCleanup(tree.unlock)
985
tree.add([''], ['TREE_ROOT'])
986
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
987
self.b1 = tree.branch
988
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
989
bundle = read_bundle(bundle_sio)
990
revision_info = bundle.revisions[0]
991
self.assertEqual('rev1', revision_info.revision_id)
992
rev = revision_info.as_revision()
993
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
996
def test_bundle_sorted_properties(self):
997
"""For stability the writer should write properties in sorted order."""
998
tree = self.make_branch_and_memory_tree('tree')
1000
self.addCleanup(tree.unlock)
1002
tree.add([''], ['TREE_ROOT'])
1003
tree.commit('One', rev_id='rev1',
1004
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1005
self.b1 = tree.branch
1006
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1007
bundle = read_bundle(bundle_sio)
1008
revision_info = bundle.revisions[0]
1009
self.assertEqual('rev1', revision_info.revision_id)
1010
rev = revision_info.as_revision()
1011
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1012
'd':'1'}, rev.properties)
1014
def test_bundle_unicode_properties(self):
1015
"""We should be able to round trip a non-ascii property."""
1016
tree = self.make_branch_and_memory_tree('tree')
1018
self.addCleanup(tree.unlock)
1020
tree.add([''], ['TREE_ROOT'])
1021
# Revisions themselves do not require anything about revision property
1022
# keys, other than that they are a basestring, and do not contain
1024
# However, Testaments assert than they are str(), and thus should not
1026
tree.commit('One', rev_id='rev1',
1027
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1028
self.b1 = tree.branch
1029
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1030
bundle = read_bundle(bundle_sio)
1031
revision_info = bundle.revisions[0]
1032
self.assertEqual('rev1', revision_info.revision_id)
1033
rev = revision_info.as_revision()
1034
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1035
'alpha':u'\u03b1'}, rev.properties)
1037
def test_bundle_with_ghosts(self):
1038
tree = self.make_branch_and_tree('tree')
1039
self.b1 = tree.branch
1040
self.build_tree_contents([('tree/file', 'content1')])
1043
self.build_tree_contents([('tree/file', 'content2')])
1044
tree.add_parent_tree_id('ghost')
1045
tree.commit('rev2', rev_id='rev2')
1046
bundle = self.get_valid_bundle('null:', 'rev2')
1048
def make_simple_tree(self, format=None):
1049
tree = self.make_branch_and_tree('b1', format=format)
1050
self.b1 = tree.branch
1051
self.build_tree(['b1/file'])
1055
def test_across_serializers(self):
1056
tree = self.make_simple_tree('knit')
1057
tree.commit('hello', rev_id='rev1')
1058
tree.commit('hello', rev_id='rev2')
1059
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1060
repo = self.make_repository('repo', format='dirstate-with-subtree')
1061
bundle.install_revisions(repo)
1062
inv_text = repo._get_inventory_xml('rev2')
1063
self.assertNotContainsRe(inv_text, 'format="5"')
1064
self.assertContainsRe(inv_text, 'format="7"')
1066
def make_repo_with_installed_revisions(self):
1067
tree = self.make_simple_tree('knit')
1068
tree.commit('hello', rev_id='rev1')
1069
tree.commit('hello', rev_id='rev2')
1070
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1071
repo = self.make_repository('repo', format='dirstate-with-subtree')
1072
bundle.install_revisions(repo)
1075
def test_across_models(self):
1076
repo = self.make_repo_with_installed_revisions()
1077
inv = repo.get_inventory('rev2')
1078
self.assertEqual('rev2', inv.root.revision)
1079
root_id = inv.root.file_id
1081
self.addCleanup(repo.unlock)
1082
self.assertEqual({(root_id, 'rev1'):(),
1083
(root_id, 'rev2'):((root_id, 'rev1'),)},
1084
repo.texts.get_parent_map([(root_id, 'rev1'), (root_id, 'rev2')]))
1086
def test_inv_hash_across_serializers(self):
1087
repo = self.make_repo_with_installed_revisions()
1088
recorded_inv_sha1 = repo.get_revision('rev2').inventory_sha1
1089
xml = repo._get_inventory_xml('rev2')
1090
self.assertEqual(osutils.sha_string(xml), recorded_inv_sha1)
1092
def test_across_models_incompatible(self):
1093
tree = self.make_simple_tree('dirstate-with-subtree')
1094
tree.commit('hello', rev_id='rev1')
1095
tree.commit('hello', rev_id='rev2')
1097
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1098
except errors.IncompatibleBundleFormat:
1099
raise tests.TestSkipped("Format 0.8 doesn't work with knit3")
1100
repo = self.make_repository('repo', format='knit')
1101
bundle.install_revisions(repo)
1103
bundle = read_bundle(self.create_bundle_text('null:', 'rev2')[0])
1104
self.assertRaises(errors.IncompatibleRevision,
1105
bundle.install_revisions, repo)
1107
def test_get_merge_request(self):
1108
tree = self.make_simple_tree()
1109
tree.commit('hello', rev_id='rev1')
1110
tree.commit('hello', rev_id='rev2')
1111
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1112
result = bundle.get_merge_request(tree.branch.repository)
1113
self.assertEqual((None, 'rev1', 'inapplicable'), result)
1115
def test_with_subtree(self):
1116
tree = self.make_branch_and_tree('tree',
1117
format='dirstate-with-subtree')
1118
self.b1 = tree.branch
1119
subtree = self.make_branch_and_tree('tree/subtree',
1120
format='dirstate-with-subtree')
1122
tree.commit('hello', rev_id='rev1')
1124
bundle = read_bundle(self.create_bundle_text('null:', 'rev1')[0])
1125
except errors.IncompatibleBundleFormat:
1126
raise tests.TestSkipped("Format 0.8 doesn't work with knit3")
1127
if isinstance(bundle, v09.BundleInfo09):
1128
raise tests.TestSkipped("Format 0.9 doesn't work with subtrees")
1129
repo = self.make_repository('repo', format='knit')
1130
self.assertRaises(errors.IncompatibleRevision,
1131
bundle.install_revisions, repo)
1132
repo2 = self.make_repository('repo2', format='dirstate-with-subtree')
1133
bundle.install_revisions(repo2)
1135
def test_revision_id_with_slash(self):
1136
self.tree1 = self.make_branch_and_tree('tree')
1137
self.b1 = self.tree1.branch
1139
self.tree1.commit('Revision/id/with/slashes', rev_id='rev/id')
1141
raise tests.TestSkipped(
1142
"Repository doesn't support revision ids with slashes")
1143
bundle = self.get_valid_bundle('null:', 'rev/id')
1145
def test_skip_file(self):
1146
"""Make sure we don't accidentally write to the wrong versionedfile"""
1147
self.tree1 = self.make_branch_and_tree('tree')
1148
self.b1 = self.tree1.branch
1149
# rev1 is not present in bundle, done by fetch
1150
self.build_tree_contents([('tree/file2', 'contents1')])
1151
self.tree1.add('file2', 'file2-id')
1152
self.tree1.commit('rev1', rev_id='reva')
1153
self.build_tree_contents([('tree/file3', 'contents2')])
1154
# rev2 is present in bundle, and done by fetch
1155
# having file1 in the bunle causes file1's versionedfile to be opened.
1156
self.tree1.add('file3', 'file3-id')
1157
self.tree1.commit('rev2')
1158
# Updating file2 should not cause an attempt to add to file1's vf
1159
target = self.tree1.bzrdir.sprout('target').open_workingtree()
1160
self.build_tree_contents([('tree/file2', 'contents3')])
1161
self.tree1.commit('rev3', rev_id='rev3')
1162
bundle = self.get_valid_bundle('reva', 'rev3')
1163
if getattr(bundle, 'get_bundle_reader', None) is None:
1164
raise tests.TestSkipped('Bundle format cannot provide reader')
1165
# be sure that file1 comes before file2
1166
for b, m, k, r, f in bundle.get_bundle_reader().iter_records():
1169
self.assertNotEqual(f, 'file2-id')
1170
bundle.install_revisions(target.branch.repository)
1173
class V08BundleTester(BundleTester, tests.TestCaseWithTransport):
1177
def test_bundle_empty_property(self):
1178
"""Test serializing revision properties with an empty value."""
1179
tree = self.make_branch_and_memory_tree('tree')
1181
self.addCleanup(tree.unlock)
1182
tree.add([''], ['TREE_ROOT'])
1183
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1184
self.b1 = tree.branch
1185
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1186
self.assertContainsRe(bundle_sio.getvalue(),
1188
'# branch-nick: tree\n'
1192
bundle = read_bundle(bundle_sio)
1193
revision_info = bundle.revisions[0]
1194
self.assertEqual('rev1', revision_info.revision_id)
1195
rev = revision_info.as_revision()
1196
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1199
def get_bundle_tree(self, bundle, revision_id):
1200
repository = self.make_repository('repo')
1201
return bundle.revision_tree(repository, 'revid1')
1203
def test_bundle_empty_property_alt(self):
1204
"""Test serializing revision properties with an empty value.
1206
Older readers had a bug when reading an empty property.
1207
They assumed that all keys ended in ': \n'. However they would write an
1208
empty value as ':\n'. This tests make sure that all newer bzr versions
1209
can handle th second form.
1211
tree = self.make_branch_and_memory_tree('tree')
1213
self.addCleanup(tree.unlock)
1214
tree.add([''], ['TREE_ROOT'])
1215
tree.commit('One', revprops={'one':'two', 'empty':''}, rev_id='rev1')
1216
self.b1 = tree.branch
1217
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1218
txt = bundle_sio.getvalue()
1219
loc = txt.find('# empty: ') + len('# empty:')
1220
# Create a new bundle, which strips the trailing space after empty
1221
bundle_sio = BytesIO(txt[:loc] + txt[loc+1:])
1223
self.assertContainsRe(bundle_sio.getvalue(),
1225
'# branch-nick: tree\n'
1229
bundle = read_bundle(bundle_sio)
1230
revision_info = bundle.revisions[0]
1231
self.assertEqual('rev1', revision_info.revision_id)
1232
rev = revision_info.as_revision()
1233
self.assertEqual({'branch-nick':'tree', 'empty':'', 'one':'two'},
1236
def test_bundle_sorted_properties(self):
1237
"""For stability the writer should write properties in sorted order."""
1238
tree = self.make_branch_and_memory_tree('tree')
1240
self.addCleanup(tree.unlock)
1242
tree.add([''], ['TREE_ROOT'])
1243
tree.commit('One', rev_id='rev1',
1244
revprops={'a':'4', 'b':'3', 'c':'2', 'd':'1'})
1245
self.b1 = tree.branch
1246
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1247
self.assertContainsRe(bundle_sio.getvalue(),
1251
'# branch-nick: tree\n'
1255
bundle = read_bundle(bundle_sio)
1256
revision_info = bundle.revisions[0]
1257
self.assertEqual('rev1', revision_info.revision_id)
1258
rev = revision_info.as_revision()
1259
self.assertEqual({'branch-nick':'tree', 'a':'4', 'b':'3', 'c':'2',
1260
'd':'1'}, rev.properties)
1262
def test_bundle_unicode_properties(self):
1263
"""We should be able to round trip a non-ascii property."""
1264
tree = self.make_branch_and_memory_tree('tree')
1266
self.addCleanup(tree.unlock)
1268
tree.add([''], ['TREE_ROOT'])
1269
# Revisions themselves do not require anything about revision property
1270
# keys, other than that they are a basestring, and do not contain
1272
# However, Testaments assert than they are str(), and thus should not
1274
tree.commit('One', rev_id='rev1',
1275
revprops={'omega':u'\u03a9', 'alpha':u'\u03b1'})
1276
self.b1 = tree.branch
1277
bundle_sio, revision_ids = self.create_bundle_text('null:', 'rev1')
1278
self.assertContainsRe(bundle_sio.getvalue(),
1280
'# alpha: \xce\xb1\n'
1281
'# branch-nick: tree\n'
1282
'# omega: \xce\xa9\n'
1284
bundle = read_bundle(bundle_sio)
1285
revision_info = bundle.revisions[0]
1286
self.assertEqual('rev1', revision_info.revision_id)
1287
rev = revision_info.as_revision()
1288
self.assertEqual({'branch-nick':'tree', 'omega':u'\u03a9',
1289
'alpha':u'\u03b1'}, rev.properties)
1292
class V09BundleKnit2Tester(V08BundleTester):
1296
def bzrdir_format(self):
1297
format = bzrdir.BzrDirMetaFormat1()
1298
format.repository_format = knitrepo.RepositoryFormatKnit3()
1302
class V09BundleKnit1Tester(V08BundleTester):
1306
def bzrdir_format(self):
1307
format = bzrdir.BzrDirMetaFormat1()
1308
format.repository_format = knitrepo.RepositoryFormatKnit1()
1312
class V4BundleTester(BundleTester, tests.TestCaseWithTransport):
1316
def get_valid_bundle(self, base_rev_id, rev_id, checkout_dir=None):
1317
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1318
Make sure that the text generated is valid, and that it
1319
can be applied against the base, and generate the same information.
1321
:return: The in-memory bundle
1323
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1325
# This should also validate the generated bundle
1326
bundle = read_bundle(bundle_txt)
1327
repository = self.b1.repository
1328
for bundle_rev in bundle.real_revisions:
1329
# These really should have already been checked when we read the
1330
# bundle, since it computes the sha1 hash for the revision, which
1331
# only will match if everything is okay, but lets be explicit about
1333
branch_rev = repository.get_revision(bundle_rev.revision_id)
1334
for a in ('inventory_sha1', 'revision_id', 'parent_ids',
1335
'timestamp', 'timezone', 'message', 'committer',
1336
'parent_ids', 'properties'):
1337
self.assertEqual(getattr(branch_rev, a),
1338
getattr(bundle_rev, a))
1339
self.assertEqual(len(branch_rev.parent_ids),
1340
len(bundle_rev.parent_ids))
1341
self.assertEqual(set(rev_ids),
1342
{r.revision_id for r in bundle.real_revisions})
1343
self.valid_apply_bundle(base_rev_id, bundle,
1344
checkout_dir=checkout_dir)
1348
def get_invalid_bundle(self, base_rev_id, rev_id):
1349
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1350
Munge the text so that it's invalid.
1352
:return: The in-memory bundle
1354
from ..bundle import serializer
1355
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1356
new_text = self.get_raw(BytesIO(b''.join(bundle_txt)))
1357
new_text = new_text.replace('<file file_id="exe-1"',
1358
'<file executable="y" file_id="exe-1"')
1359
new_text = new_text.replace('B260', 'B275')
1360
bundle_txt = BytesIO()
1361
bundle_txt.write(serializer._get_bundle_header('4'))
1362
bundle_txt.write('\n')
1363
bundle_txt.write(new_text.encode('bz2'))
1365
bundle = read_bundle(bundle_txt)
1366
self.valid_apply_bundle(base_rev_id, bundle)
1369
def create_bundle_text(self, base_rev_id, rev_id):
1370
bundle_txt = BytesIO()
1371
rev_ids = write_bundle(self.b1.repository, rev_id, base_rev_id,
1372
bundle_txt, format=self.format)
1374
self.assertEqual(bundle_txt.readline(),
1375
'# Bazaar revision bundle v%s\n' % self.format)
1376
self.assertEqual(bundle_txt.readline(), '#\n')
1377
rev = self.b1.repository.get_revision(rev_id)
1379
return bundle_txt, rev_ids
1381
def get_bundle_tree(self, bundle, revision_id):
1382
repository = self.make_repository('repo')
1383
bundle.install_revisions(repository)
1384
return repository.revision_tree(revision_id)
1386
def test_creation(self):
1387
tree = self.make_branch_and_tree('tree')
1388
self.build_tree_contents([('tree/file', 'contents1\nstatic\n')])
1389
tree.add('file', 'fileid-2')
1390
tree.commit('added file', rev_id='rev1')
1391
self.build_tree_contents([('tree/file', 'contents2\nstatic\n')])
1392
tree.commit('changed file', rev_id='rev2')
1394
serializer = BundleSerializerV4('1.0')
1395
serializer.write(tree.branch.repository, ['rev1', 'rev2'], {}, s)
1397
tree2 = self.make_branch_and_tree('target')
1398
target_repo = tree2.branch.repository
1399
install_bundle(target_repo, serializer.read(s))
1400
target_repo.lock_read()
1401
self.addCleanup(target_repo.unlock)
1402
# Turn the 'iterators_of_bytes' back into simple strings for comparison
1403
repo_texts = dict((i, ''.join(content)) for i, content
1404
in target_repo.iter_files_bytes(
1405
[('fileid-2', 'rev1', '1'),
1406
('fileid-2', 'rev2', '2')]))
1407
self.assertEqual({'1':'contents1\nstatic\n',
1408
'2':'contents2\nstatic\n'},
1410
rtree = target_repo.revision_tree('rev2')
1411
inventory_vf = target_repo.inventories
1412
# If the inventory store has a graph, it must match the revision graph.
1414
[inventory_vf.get_parent_map([('rev2',)])[('rev2',)]],
1415
[None, (('rev1',),)])
1416
self.assertEqual('changed file',
1417
target_repo.get_revision('rev2').message)
1420
def get_raw(bundle_file):
1422
line = bundle_file.readline()
1423
line = bundle_file.readline()
1424
lines = bundle_file.readlines()
1425
return ''.join(lines).decode('bz2')
1427
def test_copy_signatures(self):
1428
tree_a = self.make_branch_and_tree('tree_a')
1430
import breezy.commit as commit
1431
oldstrategy = breezy.gpg.GPGStrategy
1432
branch = tree_a.branch
1433
repo_a = branch.repository
1434
tree_a.commit("base", allow_pointless=True, rev_id='A')
1435
self.assertFalse(branch.repository.has_signature_for_revision_id('A'))
1437
from ..testament import Testament
1438
# monkey patch gpg signing mechanism
1439
breezy.gpg.GPGStrategy = breezy.gpg.LoopbackGPGStrategy
1440
new_config = test_commit.MustSignConfig()
1441
commit.Commit(config_stack=new_config).commit(message="base",
1442
allow_pointless=True,
1444
working_tree=tree_a)
1446
return breezy.gpg.LoopbackGPGStrategy(None).sign(text)
1447
self.assertTrue(repo_a.has_signature_for_revision_id('B'))
1449
breezy.gpg.GPGStrategy = oldstrategy
1450
tree_b = self.make_branch_and_tree('tree_b')
1451
repo_b = tree_b.branch.repository
1453
serializer = BundleSerializerV4('4')
1454
serializer.write(tree_a.branch.repository, ['A', 'B'], {}, s)
1456
install_bundle(repo_b, serializer.read(s))
1457
self.assertTrue(repo_b.has_signature_for_revision_id('B'))
1458
self.assertEqual(repo_b.get_signature_text('B'),
1459
repo_a.get_signature_text('B'))
1461
# ensure repeat installs are harmless
1462
install_bundle(repo_b, serializer.read(s))
1465
class V4_2aBundleTester(V4BundleTester):
1467
def bzrdir_format(self):
1470
def get_invalid_bundle(self, base_rev_id, rev_id):
1471
"""Create a bundle from base_rev_id -> rev_id in built-in branch.
1472
Munge the text so that it's invalid.
1474
:return: The in-memory bundle
1476
from ..bundle import serializer
1477
bundle_txt, rev_ids = self.create_bundle_text(base_rev_id, rev_id)
1478
new_text = self.get_raw(BytesIO(b''.join(bundle_txt)))
1479
# We are going to be replacing some text to set the executable bit on a
1480
# file. Make sure the text replacement actually works correctly.
1481
self.assertContainsRe(new_text, '(?m)B244\n\ni 1\n<inventory')
1482
new_text = new_text.replace('<file file_id="exe-1"',
1483
'<file executable="y" file_id="exe-1"')
1484
new_text = new_text.replace('B244', 'B259')
1485
bundle_txt = BytesIO()
1486
bundle_txt.write(serializer._get_bundle_header('4'))
1487
bundle_txt.write('\n')
1488
bundle_txt.write(new_text.encode('bz2'))
1490
bundle = read_bundle(bundle_txt)
1491
self.valid_apply_bundle(base_rev_id, bundle)
1494
def make_merged_branch(self):
1495
builder = self.make_branch_builder('source')
1496
builder.start_series()
1497
builder.build_snapshot('a@cset-0-1', None, [
1498
('add', ('', 'root-id', 'directory', None)),
1499
('add', ('file', 'file-id', 'file', 'original content\n')),
1501
builder.build_snapshot('a@cset-0-2a', ['a@cset-0-1'], [
1502
('modify', ('file-id', 'new-content\n')),
1504
builder.build_snapshot('a@cset-0-2b', ['a@cset-0-1'], [
1505
('add', ('other-file', 'file2-id', 'file', 'file2-content\n')),
1507
builder.build_snapshot('a@cset-0-3', ['a@cset-0-2a', 'a@cset-0-2b'], [
1508
('add', ('other-file', 'file2-id', 'file', 'file2-content\n')),
1510
builder.finish_series()
1511
self.b1 = builder.get_branch()
1513
self.addCleanup(self.b1.unlock)
1515
def make_bundle_just_inventories(self, base_revision_id,
1519
writer = v4.BundleWriteOperation(base_revision_id, target_revision_id,
1520
self.b1.repository, sio)
1521
writer.bundle.begin()
1522
writer._add_inventory_mpdiffs_from_serializer(revision_ids)
1527
def test_single_inventory_multiple_parents_as_xml(self):
1528
self.make_merged_branch()
1529
sio = self.make_bundle_just_inventories('a@cset-0-1', 'a@cset-0-3',
1531
reader = v4.BundleReader(sio, stream_input=False)
1532
records = list(reader.iter_records())
1533
self.assertEqual(1, len(records))
1534
(bytes, metadata, repo_kind, revision_id,
1535
file_id) = records[0]
1536
self.assertIs(None, file_id)
1537
self.assertEqual('a@cset-0-3', revision_id)
1538
self.assertEqual('inventory', repo_kind)
1539
self.assertEqual({'parents': ['a@cset-0-2a', 'a@cset-0-2b'],
1540
'sha1': '09c53b0c4de0895e11a2aacc34fef60a6e70865c',
1541
'storage_kind': 'mpdiff',
1543
# We should have an mpdiff that takes some lines from both parents.
1544
self.assertEqualDiff(
1546
'<inventory format="10" revision_id="a@cset-0-3">\n'
1549
'c 1 3 3 2\n', bytes)
1551
def test_single_inv_no_parents_as_xml(self):
1552
self.make_merged_branch()
1553
sio = self.make_bundle_just_inventories('null:', 'a@cset-0-1',
1555
reader = v4.BundleReader(sio, stream_input=False)
1556
records = list(reader.iter_records())
1557
self.assertEqual(1, len(records))
1558
(bytes, metadata, repo_kind, revision_id,
1559
file_id) = records[0]
1560
self.assertIs(None, file_id)
1561
self.assertEqual('a@cset-0-1', revision_id)
1562
self.assertEqual('inventory', repo_kind)
1563
self.assertEqual({'parents': [],
1564
'sha1': 'a13f42b142d544aac9b085c42595d304150e31a2',
1565
'storage_kind': 'mpdiff',
1567
# We should have an mpdiff that takes some lines from both parents.
1568
self.assertEqualDiff(
1570
'<inventory format="10" revision_id="a@cset-0-1">\n'
1571
'<directory file_id="root-id" name=""'
1572
' revision="a@cset-0-1" />\n'
1573
'<file file_id="file-id" name="file" parent_id="root-id"'
1574
' revision="a@cset-0-1"'
1575
' text_sha1="09c2f8647e14e49e922b955c194102070597c2d1"'
1576
' text_size="17" />\n'
1580
def test_multiple_inventories_as_xml(self):
1581
self.make_merged_branch()
1582
sio = self.make_bundle_just_inventories('a@cset-0-1', 'a@cset-0-3',
1583
['a@cset-0-2a', 'a@cset-0-2b', 'a@cset-0-3'])
1584
reader = v4.BundleReader(sio, stream_input=False)
1585
records = list(reader.iter_records())
1586
self.assertEqual(3, len(records))
1587
revision_ids = [rev_id for b, m, k, rev_id, f in records]
1588
self.assertEqual(['a@cset-0-2a', 'a@cset-0-2b', 'a@cset-0-3'],
1590
metadata_2a = records[0][1]
1591
self.assertEqual({'parents': ['a@cset-0-1'],
1592
'sha1': '1e105886d62d510763e22885eec733b66f5f09bf',
1593
'storage_kind': 'mpdiff',
1595
metadata_2b = records[1][1]
1596
self.assertEqual({'parents': ['a@cset-0-1'],
1597
'sha1': 'f03f12574bdb5ed2204c28636c98a8547544ccd8',
1598
'storage_kind': 'mpdiff',
1600
metadata_3 = records[2][1]
1601
self.assertEqual({'parents': ['a@cset-0-2a', 'a@cset-0-2b'],
1602
'sha1': '09c53b0c4de0895e11a2aacc34fef60a6e70865c',
1603
'storage_kind': 'mpdiff',
1605
bytes_2a = records[0][0]
1606
self.assertEqualDiff(
1608
'<inventory format="10" revision_id="a@cset-0-2a">\n'
1612
'<file file_id="file-id" name="file" parent_id="root-id"'
1613
' revision="a@cset-0-2a"'
1614
' text_sha1="50f545ff40e57b6924b1f3174b267ffc4576e9a9"'
1615
' text_size="12" />\n'
1617
'c 0 3 3 1\n', bytes_2a)
1618
bytes_2b = records[1][0]
1619
self.assertEqualDiff(
1621
'<inventory format="10" revision_id="a@cset-0-2b">\n'
1625
'<file file_id="file2-id" name="other-file" parent_id="root-id"'
1626
' revision="a@cset-0-2b"'
1627
' text_sha1="b46c0c8ea1e5ef8e46fc8894bfd4752a88ec939e"'
1628
' text_size="14" />\n'
1630
'c 0 3 4 1\n', bytes_2b)
1631
bytes_3 = records[2][0]
1632
self.assertEqualDiff(
1634
'<inventory format="10" revision_id="a@cset-0-3">\n'
1637
'c 1 3 3 2\n', bytes_3)
1639
def test_creating_bundle_preserves_chk_pages(self):
1640
self.make_merged_branch()
1641
target = self.b1.bzrdir.sprout('target',
1642
revision_id='a@cset-0-2a').open_branch()
1643
bundle_txt, rev_ids = self.create_bundle_text('a@cset-0-2a',
1645
self.assertEqual(['a@cset-0-2b', 'a@cset-0-3'], rev_ids)
1646
bundle = read_bundle(bundle_txt)
1648
self.addCleanup(target.unlock)
1649
install_bundle(target.repository, bundle)
1650
inv1 = self.b1.repository.inventories.get_record_stream([
1651
('a@cset-0-3',)], 'unordered',
1652
True).next().get_bytes_as('fulltext')
1653
inv2 = target.repository.inventories.get_record_stream([
1654
('a@cset-0-3',)], 'unordered',
1655
True).next().get_bytes_as('fulltext')
1656
self.assertEqualDiff(inv1, inv2)
1659
class MungedBundleTester(object):
1661
def build_test_bundle(self):
1662
wt = self.make_branch_and_tree('b1')
1664
self.build_tree(['b1/one'])
1666
wt.commit('add one', rev_id='a@cset-0-1')
1667
self.build_tree(['b1/two'])
1669
wt.commit('add two', rev_id='a@cset-0-2',
1670
revprops={'branch-nick':'test'})
1672
bundle_txt = BytesIO()
1673
rev_ids = write_bundle(wt.branch.repository, 'a@cset-0-2',
1674
'a@cset-0-1', bundle_txt, self.format)
1675
self.assertEqual({'a@cset-0-2'}, set(rev_ids))
1676
bundle_txt.seek(0, 0)
1679
def check_valid(self, bundle):
1680
"""Check that after whatever munging, the final object is valid."""
1681
self.assertEqual(['a@cset-0-2'],
1682
[r.revision_id for r in bundle.real_revisions])
1684
def test_extra_whitespace(self):
1685
bundle_txt = self.build_test_bundle()
1687
# Seek to the end of the file
1688
# Adding one extra newline used to give us
1689
# TypeError: float() argument must be a string or a number
1690
bundle_txt.seek(0, 2)
1691
bundle_txt.write('\n')
1694
bundle = read_bundle(bundle_txt)
1695
self.check_valid(bundle)
1697
def test_extra_whitespace_2(self):
1698
bundle_txt = self.build_test_bundle()
1700
# Seek to the end of the file
1701
# Adding two extra newlines used to give us
1702
# MalformedPatches: The first line of all patches should be ...
1703
bundle_txt.seek(0, 2)
1704
bundle_txt.write('\n\n')
1707
bundle = read_bundle(bundle_txt)
1708
self.check_valid(bundle)
1711
class MungedBundleTesterV09(tests.TestCaseWithTransport, MungedBundleTester):
1715
def test_missing_trailing_whitespace(self):
1716
bundle_txt = self.build_test_bundle()
1718
# Remove a trailing newline, it shouldn't kill the parser
1719
raw = bundle_txt.getvalue()
1720
# The contents of the bundle don't have to be this, but this
1721
# test is concerned with the exact case where the serializer
1722
# creates a blank line at the end, and fails if that
1724
self.assertEqual('\n\n', raw[-2:])
1725
bundle_txt = BytesIO(raw[:-1])
1727
bundle = read_bundle(bundle_txt)
1728
self.check_valid(bundle)
1730
def test_opening_text(self):
1731
bundle_txt = self.build_test_bundle()
1733
bundle_txt = BytesIO(
1734
b"Some random\nemail comments\n" + bundle_txt.getvalue())
1736
bundle = read_bundle(bundle_txt)
1737
self.check_valid(bundle)
1739
def test_trailing_text(self):
1740
bundle_txt = self.build_test_bundle()
1742
bundle_txt = BytesIO(
1743
bundle_txt.getvalue() + b"Some trailing\nrandom\ntext\n")
1745
bundle = read_bundle(bundle_txt)
1746
self.check_valid(bundle)
1749
class MungedBundleTesterV4(tests.TestCaseWithTransport, MungedBundleTester):
1754
class TestBundleWriterReader(tests.TestCase):
1756
def test_roundtrip_record(self):
1758
writer = v4.BundleWriter(fileobj)
1760
writer.add_info_record(foo='bar')
1761
writer._add_record("Record body", {'parents': ['1', '3'],
1762
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1765
reader = v4.BundleReader(fileobj, stream_input=True)
1766
record_iter = reader.iter_records()
1767
record = next(record_iter)
1768
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1769
'info', None, None), record)
1770
record = next(record_iter)
1771
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1772
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1775
def test_roundtrip_record_memory_hungry(self):
1777
writer = v4.BundleWriter(fileobj)
1779
writer.add_info_record(foo='bar')
1780
writer._add_record("Record body", {'parents': ['1', '3'],
1781
'storage_kind':'fulltext'}, 'file', 'revid', 'fileid')
1784
reader = v4.BundleReader(fileobj, stream_input=False)
1785
record_iter = reader.iter_records()
1786
record = next(record_iter)
1787
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1788
'info', None, None), record)
1789
record = next(record_iter)
1790
self.assertEqual(("Record body", {'storage_kind': 'fulltext',
1791
'parents': ['1', '3']}, 'file', 'revid', 'fileid'),
1794
def test_encode_name(self):
1795
self.assertEqual('revision/rev1',
1796
v4.BundleWriter.encode_name('revision', 'rev1'))
1797
self.assertEqual('file/rev//1/file-id-1',
1798
v4.BundleWriter.encode_name('file', 'rev/1', 'file-id-1'))
1799
self.assertEqual('info',
1800
v4.BundleWriter.encode_name('info', None, None))
1802
def test_decode_name(self):
1803
self.assertEqual(('revision', 'rev1', None),
1804
v4.BundleReader.decode_name('revision/rev1'))
1805
self.assertEqual(('file', 'rev/1', 'file-id-1'),
1806
v4.BundleReader.decode_name('file/rev//1/file-id-1'))
1807
self.assertEqual(('info', None, None),
1808
v4.BundleReader.decode_name('info'))
1810
def test_too_many_names(self):
1812
writer = v4.BundleWriter(fileobj)
1814
writer.add_info_record(foo='bar')
1815
writer._container.add_bytes_record('blah', ['two', 'names'])
1818
record_iter = v4.BundleReader(fileobj).iter_records()
1819
record = next(record_iter)
1820
self.assertEqual((None, {'foo': 'bar', 'storage_kind': 'header'},
1821
'info', None, None), record)
1822
self.assertRaises(errors.BadBundle, next, record_iter)
1825
class TestReadMergeableFromUrl(tests.TestCaseWithTransport):
1827
def test_read_mergeable_skips_local(self):
1828
"""A local bundle named like the URL should not be read.
1830
out, wt = test_read_bundle.create_bundle_file(self)
1831
class FooService(object):
1832
"""A directory service that always returns source"""
1834
def look_up(self, name, url):
1836
directories.register('foo:', FooService, 'Testing directory service')
1837
self.addCleanup(directories.remove, 'foo:')
1838
self.build_tree_contents([('./foo:bar', out.getvalue())])
1839
self.assertRaises(errors.NotABundle, read_mergeable_from_url,
1842
def test_infinite_redirects_are_not_a_bundle(self):
1843
"""If a URL causes TooManyRedirections then NotABundle is raised.
1845
from .blackbox.test_push import RedirectingMemoryServer
1846
server = RedirectingMemoryServer()
1847
self.start_server(server)
1848
url = server.get_url() + 'infinite-loop'
1849
self.assertRaises(errors.NotABundle, read_mergeable_from_url, url)
1851
def test_smart_server_connection_reset(self):
1852
"""If a smart server connection fails during the attempt to read a
1853
bundle, then the ConnectionReset error should be propagated.
1855
# Instantiate a server that will provoke a ConnectionReset
1856
sock_server = DisconnectingServer()
1857
self.start_server(sock_server)
1858
# We don't really care what the url is since the server will close the
1859
# connection without interpreting it
1860
url = sock_server.get_url()
1861
self.assertRaises(errors.ConnectionReset, read_mergeable_from_url, url)
1864
class DisconnectingHandler(socketserver.BaseRequestHandler):
1865
"""A request handler that immediately closes any connection made to it."""
1868
self.request.close()
1871
class DisconnectingServer(test_server.TestingTCPServerInAThread):
1874
super(DisconnectingServer, self).__init__(
1876
test_server.TestingTCPServer,
1877
DisconnectingHandler)
1880
"""Return the url of the server"""
1881
return "bzr://%s:%d/" % self.server.server_address