1
# Copyright (C) 2007-2010 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
17
from cStringIO import StringIO
28
revision as _mod_revision,
32
versionedfile as _mod_versionedfile,
34
from bzrlib.bundle import bundle_data, serializer as bundle_serializer
35
from bzrlib.i18n import ngettext
36
from bzrlib import bencode
39
class _MPDiffInventoryGenerator(_mod_versionedfile._MPDiffGenerator):
40
"""Generate Inventory diffs serialized inventories."""
42
def __init__(self, repo, inventory_keys):
43
super(_MPDiffInventoryGenerator, self).__init__(repo.inventories,
49
"""Compute the diffs one at a time."""
50
# This is instead of compute_diffs() since we guarantee our ordering of
51
# inventories, we don't have to do any buffering
52
self._find_needed_keys()
53
# We actually use a slightly different ordering. We grab all of the
54
# parents first, and then grab the ordered requests.
55
needed_ids = [k[-1] for k in self.present_parents]
56
needed_ids.extend([k[-1] for k in self.ordered_keys])
57
inv_to_str = self.repo._serializer.write_inventory_to_string
58
for inv in self.repo.iter_inventories(needed_ids):
59
revision_id = inv.revision_id
61
if key in self.present_parents:
62
# Not a key we will transmit, which is a shame, since because
63
# of that bundles don't work with stacked branches
66
parent_ids = [k[-1] for k in self.parent_map[key]]
67
as_bytes = inv_to_str(inv)
68
self._process_one_record(key, (as_bytes,))
69
if parent_ids is None:
71
diff = self.diffs.pop(key)
72
sha1 = osutils.sha_string(as_bytes)
73
yield revision_id, parent_ids, sha1, diff
76
class BundleWriter(object):
77
"""Writer for bundle-format files.
79
This serves roughly the same purpose as ContainerReader, but acts as a
82
Provides ways of writing the specific record types supported this bundle
86
def __init__(self, fileobj):
87
self._container = pack.ContainerWriter(self._write_encoded)
88
self._fileobj = fileobj
89
self._compressor = bz2.BZ2Compressor()
91
def _write_encoded(self, bytes):
92
"""Write bzip2-encoded bytes to the file"""
93
self._fileobj.write(self._compressor.compress(bytes))
96
"""Start writing the bundle"""
97
self._fileobj.write(bundle_serializer._get_bundle_header(
98
bundle_serializer.v4_string))
99
self._fileobj.write('#\n')
100
self._container.begin()
103
"""Finish writing the bundle"""
104
self._container.end()
105
self._fileobj.write(self._compressor.flush())
107
def add_multiparent_record(self, mp_bytes, sha1, parents, repo_kind,
108
revision_id, file_id):
109
"""Add a record for a multi-parent diff
111
:mp_bytes: A multi-parent diff, as a bytestring
112
:sha1: The sha1 hash of the fulltext
113
:parents: a list of revision-ids of the parents
114
:repo_kind: The kind of object in the repository. May be 'file' or
116
:revision_id: The revision id of the mpdiff being added.
117
:file_id: The file-id of the file, or None for inventories.
119
metadata = {'parents': parents,
120
'storage_kind': 'mpdiff',
122
self._add_record(mp_bytes, metadata, repo_kind, revision_id, file_id)
124
def add_fulltext_record(self, bytes, parents, repo_kind, revision_id):
125
"""Add a record for a fulltext
127
:bytes: The fulltext, as a bytestring
128
:parents: a list of revision-ids of the parents
129
:repo_kind: The kind of object in the repository. May be 'revision' or
131
:revision_id: The revision id of the fulltext being added.
133
metadata = {'parents': parents,
134
'storage_kind': 'mpdiff'}
135
self._add_record(bytes, {'parents': parents,
136
'storage_kind': 'fulltext'}, repo_kind, revision_id, None)
138
def add_info_record(self, **kwargs):
139
"""Add an info record to the bundle
141
Any parameters may be supplied, except 'self' and 'storage_kind'.
142
Values must be lists, strings, integers, dicts, or a combination.
144
kwargs['storage_kind'] = 'header'
145
self._add_record(None, kwargs, 'info', None, None)
148
def encode_name(content_kind, revision_id, file_id=None):
149
"""Encode semantic ids as a container name"""
150
if content_kind not in ('revision', 'file', 'inventory', 'signature',
152
raise ValueError(content_kind)
153
if content_kind == 'file':
155
raise AssertionError()
157
if file_id is not None:
158
raise AssertionError()
159
if content_kind == 'info':
160
if revision_id is not None:
161
raise AssertionError()
162
elif revision_id is None:
163
raise AssertionError()
164
names = [n.replace('/', '//') for n in
165
(content_kind, revision_id, file_id) if n is not None]
166
return '/'.join(names)
168
def _add_record(self, bytes, metadata, repo_kind, revision_id, file_id):
169
"""Add a bundle record to the container.
171
Most bundle records are recorded as header/body pairs, with the
172
body being nameless. Records with storage_kind 'header' have no
175
name = self.encode_name(repo_kind, revision_id, file_id)
176
encoded_metadata = bencode.bencode(metadata)
177
self._container.add_bytes_record(encoded_metadata, [(name, )])
178
if metadata['storage_kind'] != 'header':
179
self._container.add_bytes_record(bytes, [])
182
class BundleReader(object):
183
"""Reader for bundle-format files.
185
This serves roughly the same purpose as ContainerReader, but acts as a
186
layer on top of it, providing metadata, a semantic name, and a record
190
def __init__(self, fileobj, stream_input=True):
193
:param fileobj: a file containing a bzip-encoded container
194
:param stream_input: If True, the BundleReader stream input rather than
195
reading it all into memory at once. Reading it into memory all at
196
once is (currently) faster.
198
line = fileobj.readline()
201
self.patch_lines = []
203
source_file = iterablefile.IterableFile(self.iter_decode(fileobj))
205
source_file = StringIO(bz2.decompress(fileobj.read()))
206
self._container_file = source_file
209
def iter_decode(fileobj):
210
"""Iterate through decoded fragments of the file"""
211
decompressor = bz2.BZ2Decompressor()
214
yield decompressor.decompress(line)
219
def decode_name(name):
220
"""Decode a name from its container form into a semantic form
222
:retval: content_kind, revision_id, file_id
224
segments = re.split('(//?)', name)
226
for segment in segments:
233
content_kind = names[0]
237
revision_id = names[1]
240
return content_kind, revision_id, file_id
242
def iter_records(self):
243
"""Iterate through bundle records
245
:return: a generator of (bytes, metadata, content_kind, revision_id,
248
iterator = pack.iter_records_from_file(self._container_file)
249
for names, bytes in iterator:
251
raise errors.BadBundle('Record has %d names instead of 1'
253
metadata = bencode.bdecode(bytes)
254
if metadata['storage_kind'] == 'header':
257
_unused, bytes = iterator.next()
258
yield (bytes, metadata) + self.decode_name(names[0][0])
261
class BundleSerializerV4(bundle_serializer.BundleSerializer):
262
"""Implement the high-level bundle interface"""
264
def write(self, repository, revision_ids, forced_bases, fileobj):
265
"""Write a bundle to a file-like object
267
For backwards-compatibility only
269
write_op = BundleWriteOperation.from_old_args(repository, revision_ids,
270
forced_bases, fileobj)
271
return write_op.do_write()
273
def write_bundle(self, repository, target, base, fileobj):
274
"""Write a bundle to a file object
276
:param repository: The repository to retrieve revision data from
277
:param target: The head revision to include ancestors of
278
:param base: The ancestor of the target to stop including acestors
280
:param fileobj: The file-like object to write to
282
write_op = BundleWriteOperation(base, target, repository, fileobj)
283
return write_op.do_write()
285
def read(self, file):
286
"""return a reader object for a given file"""
287
bundle = BundleInfoV4(file, self)
291
def get_source_serializer(info):
292
"""Retrieve the serializer for a given info object"""
293
return serializer.format_registry.get(info['serializer'])
296
class BundleWriteOperation(object):
297
"""Perform the operation of writing revisions to a bundle"""
300
def from_old_args(cls, repository, revision_ids, forced_bases, fileobj):
301
"""Create a BundleWriteOperation from old-style arguments"""
302
base, target = cls.get_base_target(revision_ids, forced_bases,
304
return BundleWriteOperation(base, target, repository, fileobj,
307
def __init__(self, base, target, repository, fileobj, revision_ids=None):
310
self.repository = repository
311
bundle = BundleWriter(fileobj)
313
if revision_ids is not None:
314
self.revision_ids = revision_ids
316
graph = repository.get_graph()
317
revision_ids = graph.find_unique_ancestors(target, [base])
319
parents = graph.get_parent_map(revision_ids)
320
self.revision_ids = [r for r in revision_ids if r in parents]
321
self.revision_keys = set([(revid,) for revid in self.revision_ids])
324
"""Write all data to the bundle"""
325
trace.note(ngettext('Bundling %d revision.', 'Bundling %d revisions.',
326
len(self.revision_ids)), len(self.revision_ids))
327
self.repository.lock_read()
332
self.write_revisions()
335
self.repository.unlock()
336
return self.revision_ids
338
def write_info(self):
339
"""Write format info"""
340
serializer_format = self.repository.get_serializer_format()
341
supports_rich_root = {True: 1, False: 0}[
342
self.repository.supports_rich_root()]
343
self.bundle.add_info_record(serializer=serializer_format,
344
supports_rich_root=supports_rich_root)
346
def write_files(self):
347
"""Write bundle records for all revisions of all files"""
349
altered_fileids = self.repository.fileids_altered_by_revision_ids(
351
for file_id, revision_ids in altered_fileids.iteritems():
352
for revision_id in revision_ids:
353
text_keys.append((file_id, revision_id))
354
self._add_mp_records_keys('file', self.repository.texts, text_keys)
356
def write_revisions(self):
357
"""Write bundle records for all revisions and signatures"""
358
inv_vf = self.repository.inventories
359
topological_order = [key[-1] for key in multiparent.topo_iter_keys(
360
inv_vf, self.revision_keys)]
361
revision_order = topological_order
362
if self.target is not None and self.target in self.revision_ids:
363
# Make sure the target revision is always the last entry
364
revision_order = list(topological_order)
365
revision_order.remove(self.target)
366
revision_order.append(self.target)
367
if self.repository._serializer.support_altered_by_hack:
368
# Repositories that support_altered_by_hack means that
369
# inventories.make_mpdiffs() contains all the data about the tree
370
# shape. Formats without support_altered_by_hack require
371
# chk_bytes/etc, so we use a different code path.
372
self._add_mp_records_keys('inventory', inv_vf,
373
[(revid,) for revid in topological_order])
375
# Inventories should always be added in pure-topological order, so
376
# that we can apply the mpdiff for the child to the parent texts.
377
self._add_inventory_mpdiffs_from_serializer(topological_order)
378
self._add_revision_texts(revision_order)
380
def _add_inventory_mpdiffs_from_serializer(self, revision_order):
381
"""Generate mpdiffs by serializing inventories.
383
The current repository only has part of the tree shape information in
384
the 'inventories' vf. So we use serializer.write_inventory_to_string to
385
get a 'full' representation of the tree shape, and then generate
386
mpdiffs on that data stream. This stream can then be reconstructed on
389
inventory_key_order = [(r,) for r in revision_order]
390
generator = _MPDiffInventoryGenerator(self.repository,
392
for revision_id, parent_ids, sha1, diff in generator.iter_diffs():
393
text = ''.join(diff.to_patch())
394
self.bundle.add_multiparent_record(text, sha1, parent_ids,
395
'inventory', revision_id, None)
397
def _add_revision_texts(self, revision_order):
398
parent_map = self.repository.get_parent_map(revision_order)
399
revision_to_str = self.repository._serializer.write_revision_to_string
400
revisions = self.repository.get_revisions(revision_order)
401
for revision in revisions:
402
revision_id = revision.revision_id
403
parents = parent_map.get(revision_id, None)
404
revision_text = revision_to_str(revision)
405
self.bundle.add_fulltext_record(revision_text, parents,
406
'revision', revision_id)
408
self.bundle.add_fulltext_record(
409
self.repository.get_signature_text(
410
revision_id), parents, 'signature', revision_id)
411
except errors.NoSuchRevision:
415
def get_base_target(revision_ids, forced_bases, repository):
416
"""Determine the base and target from old-style revision ids"""
417
if len(revision_ids) == 0:
419
target = revision_ids[0]
420
base = forced_bases.get(target)
422
parents = repository.get_revision(target).parent_ids
423
if len(parents) == 0:
424
base = _mod_revision.NULL_REVISION
429
def _add_mp_records_keys(self, repo_kind, vf, keys):
430
"""Add multi-parent diff records to a bundle"""
431
ordered_keys = list(multiparent.topo_iter_keys(vf, keys))
432
mpdiffs = vf.make_mpdiffs(ordered_keys)
433
sha1s = vf.get_sha1s(ordered_keys)
434
parent_map = vf.get_parent_map(ordered_keys)
435
for mpdiff, item_key, in zip(mpdiffs, ordered_keys):
436
sha1 = sha1s[item_key]
437
parents = [key[-1] for key in parent_map[item_key]]
438
text = ''.join(mpdiff.to_patch())
439
# Infer file id records as appropriate.
440
if len(item_key) == 2:
441
file_id = item_key[0]
444
self.bundle.add_multiparent_record(text, sha1, parents, repo_kind,
445
item_key[-1], file_id)
448
class BundleInfoV4(object):
450
"""Provide (most of) the BundleInfo interface"""
451
def __init__(self, fileobj, serializer):
452
self._fileobj = fileobj
453
self._serializer = serializer
454
self.__real_revisions = None
455
self.__revisions = None
457
def install(self, repository):
458
return self.install_revisions(repository)
460
def install_revisions(self, repository, stream_input=True):
461
"""Install this bundle's revisions into the specified repository
463
:param target_repo: The repository to install into
464
:param stream_input: If True, will stream input rather than reading it
465
all into memory at once. Reading it into memory all at once is
468
repository.lock_write()
470
ri = RevisionInstaller(self.get_bundle_reader(stream_input),
471
self._serializer, repository)
476
def get_merge_request(self, target_repo):
477
"""Provide data for performing a merge
479
Returns suggested base, suggested target, and patch verification status
481
return None, self.target, 'inapplicable'
483
def get_bundle_reader(self, stream_input=True):
484
"""Return a new BundleReader for the associated bundle
486
:param stream_input: If True, the BundleReader stream input rather than
487
reading it all into memory at once. Reading it into memory all at
488
once is (currently) faster.
490
self._fileobj.seek(0)
491
return BundleReader(self._fileobj, stream_input)
493
def _get_real_revisions(self):
494
if self.__real_revisions is None:
495
self.__real_revisions = []
496
bundle_reader = self.get_bundle_reader()
497
for bytes, metadata, repo_kind, revision_id, file_id in \
498
bundle_reader.iter_records():
499
if repo_kind == 'info':
501
self._serializer.get_source_serializer(metadata)
502
if repo_kind == 'revision':
503
rev = serializer.read_revision_from_string(bytes)
504
self.__real_revisions.append(rev)
505
return self.__real_revisions
506
real_revisions = property(_get_real_revisions)
508
def _get_revisions(self):
509
if self.__revisions is None:
510
self.__revisions = []
511
for revision in self.real_revisions:
512
self.__revisions.append(
513
bundle_data.RevisionInfo.from_revision(revision))
514
return self.__revisions
516
revisions = property(_get_revisions)
518
def _get_target(self):
519
return self.revisions[-1].revision_id
521
target = property(_get_target)
524
class RevisionInstaller(object):
525
"""Installs revisions into a repository"""
527
def __init__(self, container, serializer, repository):
528
self._container = container
529
self._serializer = serializer
530
self._repository = repository
534
"""Perform the installation.
536
Must be called with the Repository locked.
538
self._repository.start_write_group()
540
result = self._install_in_write_group()
542
self._repository.abort_write_group()
544
self._repository.commit_write_group()
547
def _install_in_write_group(self):
549
current_versionedfile = None
550
pending_file_records = []
552
pending_inventory_records = []
554
target_revision = None
555
for bytes, metadata, repo_kind, revision_id, file_id in\
556
self._container.iter_records():
557
if repo_kind == 'info':
558
if self._info is not None:
559
raise AssertionError()
560
self._handle_info(metadata)
561
if (pending_file_records and
562
(repo_kind, file_id) != ('file', current_file)):
563
# Flush the data for a single file - prevents memory
564
# spiking due to buffering all files in memory.
565
self._install_mp_records_keys(self._repository.texts,
566
pending_file_records)
568
del pending_file_records[:]
569
if len(pending_inventory_records) > 0 and repo_kind != 'inventory':
570
self._install_inventory_records(pending_inventory_records)
571
pending_inventory_records = []
572
if repo_kind == 'inventory':
573
pending_inventory_records.append(((revision_id,), metadata, bytes))
574
if repo_kind == 'revision':
575
target_revision = revision_id
576
self._install_revision(revision_id, metadata, bytes)
577
if repo_kind == 'signature':
578
self._install_signature(revision_id, metadata, bytes)
579
if repo_kind == 'file':
580
current_file = file_id
581
pending_file_records.append(((file_id, revision_id), metadata, bytes))
582
self._install_mp_records_keys(self._repository.texts, pending_file_records)
583
return target_revision
585
def _handle_info(self, info):
586
"""Extract data from an info record"""
588
self._source_serializer = self._serializer.get_source_serializer(info)
589
if (info['supports_rich_root'] == 0 and
590
self._repository.supports_rich_root()):
591
self.update_root = True
593
self.update_root = False
595
def _install_mp_records(self, versionedfile, records):
596
if len(records) == 0:
598
d_func = multiparent.MultiParent.from_patch
599
vf_records = [(r, m['parents'], m['sha1'], d_func(t)) for r, m, t in
600
records if r not in versionedfile]
601
versionedfile.add_mpdiffs(vf_records)
603
def _install_mp_records_keys(self, versionedfile, records):
604
d_func = multiparent.MultiParent.from_patch
606
for key, meta, text in records:
607
# Adapt to tuple interface: A length two key is a file_id,
608
# revision_id pair, a length 1 key is a
609
# revision/signature/inventory. We need to do this because
610
# the metadata extraction from the bundle has not yet been updated
611
# to use the consistent tuple interface itself.
616
parents = [prefix + (parent,) for parent in meta['parents']]
617
vf_records.append((key, parents, meta['sha1'], d_func(text)))
618
versionedfile.add_mpdiffs(vf_records)
620
def _get_parent_inventory_texts(self, inventory_text_cache,
621
inventory_cache, parent_ids):
622
cached_parent_texts = {}
623
remaining_parent_ids = []
624
for parent_id in parent_ids:
625
p_text = inventory_text_cache.get(parent_id, None)
627
remaining_parent_ids.append(parent_id)
629
cached_parent_texts[parent_id] = p_text
631
# TODO: Use inventory_cache to grab inventories we already have in
633
if remaining_parent_ids:
634
# first determine what keys are actually present in the local
635
# inventories object (don't use revisions as they haven't been
637
parent_keys = [(r,) for r in remaining_parent_ids]
638
present_parent_map = self._repository.inventories.get_parent_map(
640
present_parent_ids = []
642
for p_id in remaining_parent_ids:
643
if (p_id,) in present_parent_map:
644
present_parent_ids.append(p_id)
647
to_string = self._source_serializer.write_inventory_to_string
648
for parent_inv in self._repository.iter_inventories(
650
p_text = to_string(parent_inv)
651
inventory_cache[parent_inv.revision_id] = parent_inv
652
cached_parent_texts[parent_inv.revision_id] = p_text
653
inventory_text_cache[parent_inv.revision_id] = p_text
655
parent_texts = [cached_parent_texts[parent_id]
656
for parent_id in parent_ids
657
if parent_id not in ghosts]
660
def _install_inventory_records(self, records):
661
if (self._info['serializer'] == self._repository._serializer.format_num
662
and self._repository._serializer.support_altered_by_hack):
663
return self._install_mp_records_keys(self._repository.inventories,
665
# Use a 10MB text cache, since these are string xml inventories. Note
666
# that 10MB is fairly small for large projects (a single inventory can
667
# be >5MB). Another possibility is to cache 10-20 inventory texts
669
inventory_text_cache = lru_cache.LRUSizeCache(10*1024*1024)
670
# Also cache the in-memory representation. This allows us to create
671
# inventory deltas to apply rather than calling add_inventory from
673
inventory_cache = lru_cache.LRUCache(10)
674
pb = ui.ui_factory.nested_progress_bar()
676
num_records = len(records)
677
for idx, (key, metadata, bytes) in enumerate(records):
678
pb.update('installing inventory', idx, num_records)
679
revision_id = key[-1]
680
parent_ids = metadata['parents']
681
# Note: This assumes the local ghosts are identical to the
682
# ghosts in the source, as the Bundle serialization
683
# format doesn't record ghosts.
684
p_texts = self._get_parent_inventory_texts(inventory_text_cache,
687
# Why does to_lines() take strings as the source, it seems that
688
# it would have to cast to a list of lines, which we get back
689
# as lines and then cast back to a string.
690
target_lines = multiparent.MultiParent.from_patch(bytes
692
inv_text = ''.join(target_lines)
694
sha1 = osutils.sha_string(inv_text)
695
if sha1 != metadata['sha1']:
696
raise errors.BadBundle("Can't convert to target format")
697
# Add this to the cache so we don't have to extract it again.
698
inventory_text_cache[revision_id] = inv_text
699
target_inv = self._source_serializer.read_inventory_from_string(
701
self._handle_root(target_inv, parent_ids)
704
parent_inv = inventory_cache.get(parent_ids[0], None)
706
if parent_inv is None:
707
self._repository.add_inventory(revision_id, target_inv,
710
delta = target_inv._make_delta(parent_inv)
711
self._repository.add_inventory_by_delta(parent_ids[0],
712
delta, revision_id, parent_ids)
713
except errors.UnsupportedInventoryKind:
714
raise errors.IncompatibleRevision(repr(self._repository))
715
inventory_cache[revision_id] = target_inv
719
def _handle_root(self, target_inv, parent_ids):
720
revision_id = target_inv.revision_id
722
text_key = (target_inv.root.file_id, revision_id)
723
parent_keys = [(target_inv.root.file_id, parent) for
724
parent in parent_ids]
725
self._repository.texts.add_lines(text_key, parent_keys, [])
726
elif not self._repository.supports_rich_root():
727
if target_inv.root.revision != revision_id:
728
raise errors.IncompatibleRevision(repr(self._repository))
730
def _install_revision(self, revision_id, metadata, text):
731
if self._repository.has_revision(revision_id):
733
revision = self._source_serializer.read_revision_from_string(text)
734
self._repository.add_revision(revision.revision_id, revision)
736
def _install_signature(self, revision_id, metadata, text):
737
transaction = self._repository.get_transaction()
738
if self._repository.has_signature_for_revision_id(revision_id):
740
self._repository.add_signature_text(revision_id, text)