1
# Copyright (C) 2005-2011 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
"""Repository formats built around versioned files."""
19
from __future__ import absolute_import
22
from ..lazy_import import lazy_import
23
lazy_import(globals(), """
27
config as _mod_config,
34
revision as _mod_revision,
39
from breezy.bzr import (
48
from breezy.bzr.bundle import serializer
50
from breezy.recordcounter import RecordCounter
51
from breezy.i18n import gettext
52
from breezy.bzr.testament import Testament
58
from ..decorators import (
61
from .inventory import (
67
from ..repository import (
74
from .repository import (
76
RepositoryFormatMetaDir,
79
from ..sixish import (
89
from ..tree import TreeChange
92
class VersionedFileRepositoryFormat(RepositoryFormat):
93
"""Base class for all repository formats that are VersionedFiles-based."""
95
supports_full_versioned_files = True
96
supports_versioned_directories = True
97
supports_unreferenced_revisions = True
99
# Should commit add an inventory, or an inventory delta to the repository.
100
_commit_inv_deltas = True
101
# What order should fetch operations request streams in?
102
# The default is unordered as that is the cheapest for an origin to
104
_fetch_order = 'unordered'
105
# Does this repository format use deltas that can be fetched as-deltas ?
106
# (E.g. knits, where the knit deltas can be transplanted intact.
107
# We default to False, which will ensure that enough data to get
108
# a full text out of any fetch stream will be grabbed.
109
_fetch_uses_deltas = False
112
class VersionedFileCommitBuilder(CommitBuilder):
113
"""Commit builder implementation for versioned files based repositories.
116
def __init__(self, repository, parents, config_stack, timestamp=None,
117
timezone=None, committer=None, revprops=None,
118
revision_id=None, lossy=False):
119
super(VersionedFileCommitBuilder, self).__init__(repository,
120
parents, config_stack, timestamp, timezone, committer, revprops,
123
basis_id = self.parents[0]
125
basis_id = _mod_revision.NULL_REVISION
126
self.basis_delta_revision = basis_id
127
self._new_inventory = None
128
self._basis_delta = []
129
self.__heads = graph.HeadsCache(repository.get_graph()).heads
130
# memo'd check for no-op commits.
131
self._any_changes = False
133
def any_changes(self):
134
"""Return True if any entries were changed.
136
This includes merge-only changes. It is the core for the --unchanged
139
:return: True if any changes have occured.
141
return self._any_changes
143
def _ensure_fallback_inventories(self):
144
"""Ensure that appropriate inventories are available.
146
This only applies to repositories that are stacked, and is about
147
enusring the stacking invariants. Namely, that for any revision that is
148
present, we either have all of the file content, or we have the parent
149
inventory and the delta file content.
151
if not self.repository._fallback_repositories:
153
if not self.repository._format.supports_chks:
154
raise errors.BzrError("Cannot commit directly to a stacked branch"
155
" in pre-2a formats. See "
156
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
157
# This is a stacked repo, we need to make sure we have the parent
158
# inventories for the parents.
159
parent_keys = [(p,) for p in self.parents]
160
parent_map = self.repository.inventories._index.get_parent_map(
162
missing_parent_keys = {pk for pk in parent_keys
163
if pk not in parent_map}
164
fallback_repos = list(reversed(self.repository._fallback_repositories))
165
missing_keys = [('inventories', pk[0])
166
for pk in missing_parent_keys]
168
while missing_keys and fallback_repos:
169
fallback_repo = fallback_repos.pop()
170
source = fallback_repo._get_source(self.repository._format)
171
sink = self.repository._get_sink()
172
missing_keys = sink.insert_missing_keys(source, missing_keys)
174
raise errors.BzrError('Unable to fill in parent inventories for a'
177
def commit(self, message):
178
"""Make the actual commit.
180
:return: The revision id of the recorded revision.
182
self._validate_unicode_text(message, 'commit message')
183
rev = _mod_revision.Revision(
184
timestamp=self._timestamp,
185
timezone=self._timezone,
186
committer=self._committer,
188
inventory_sha1=self.inv_sha1,
189
revision_id=self._new_revision_id,
190
properties=self._revprops)
191
rev.parent_ids = self.parents
192
if self._config_stack.get('create_signatures') == _mod_config.SIGN_ALWAYS:
193
testament = Testament(rev, self.revision_tree())
194
plaintext = testament.as_short_text()
195
self.repository.store_revision_signature(
196
gpg.GPGStrategy(self._config_stack), plaintext,
197
self._new_revision_id)
198
self.repository._add_revision(rev)
199
self._ensure_fallback_inventories()
200
self.repository.commit_write_group()
201
return self._new_revision_id
204
"""Abort the commit that is being built.
206
self.repository.abort_write_group()
208
def revision_tree(self):
209
"""Return the tree that was just committed.
211
After calling commit() this can be called to get a
212
RevisionTree representing the newly committed tree. This is
213
preferred to calling Repository.revision_tree() because that may
214
require deserializing the inventory, while we already have a copy in
217
if self._new_inventory is None:
218
self._new_inventory = self.repository.get_inventory(
219
self._new_revision_id)
220
return inventorytree.InventoryRevisionTree(self.repository,
221
self._new_inventory, self._new_revision_id)
223
def finish_inventory(self):
224
"""Tell the builder that the inventory is finished.
226
:return: The inventory id in the repository, which can be used with
227
repository.get_inventory.
229
# an inventory delta was accumulated without creating a new
231
basis_id = self.basis_delta_revision
232
self.inv_sha1, self._new_inventory = self.repository.add_inventory_by_delta(
233
basis_id, self._basis_delta, self._new_revision_id,
235
return self._new_revision_id
237
def _gen_revision_id(self):
238
"""Return new revision-id."""
239
return generate_ids.gen_revision_id(self._committer, self._timestamp)
241
def _require_root_change(self, tree):
242
"""Enforce an appropriate root object change.
244
This is called once when record_iter_changes is called, if and only if
245
the root was not in the delta calculated by record_iter_changes.
247
:param tree: The tree which is being committed.
249
if self.repository.supports_rich_root():
251
if len(self.parents) == 0:
252
raise errors.RootMissing()
253
entry = entry_factory['directory'](tree.path2id(''), '',
255
entry.revision = self._new_revision_id
256
self._basis_delta.append(('', '', entry.file_id, entry))
258
def _get_delta(self, ie, basis_inv, path):
259
"""Get a delta against the basis inventory for ie."""
260
if not basis_inv.has_id(ie.file_id):
262
result = (None, path, ie.file_id, ie)
263
self._basis_delta.append(result)
265
elif ie != basis_inv.get_entry(ie.file_id):
267
# TODO: avoid tis id2path call.
268
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
269
self._basis_delta.append(result)
275
def _heads(self, file_id, revision_ids):
276
"""Calculate the graph heads for revision_ids in the graph of file_id.
278
This can use either a per-file graph or a global revision graph as we
279
have an identity relationship between the two graphs.
281
return self.__heads(revision_ids)
283
def get_basis_delta(self):
284
"""Return the complete inventory delta versus the basis inventory.
286
:return: An inventory delta, suitable for use with apply_delta, or
287
Repository.add_inventory_by_delta, etc.
289
return self._basis_delta
291
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
292
_entry_factory=entry_factory):
293
"""Record a new tree via iter_changes.
295
:param tree: The tree to obtain text contents from for changed objects.
296
:param basis_revision_id: The revision id of the tree the iter_changes
297
has been generated against. Currently assumed to be the same
298
as self.parents[0] - if it is not, errors may occur.
299
:param iter_changes: An iter_changes iterator with the changes to apply
300
to basis_revision_id. The iterator must not include any items with
301
a current kind of None - missing items must be either filtered out
302
or errored-on before record_iter_changes sees the item.
303
:param _entry_factory: Private method to bind entry_factory locally for
305
:return: A generator of (relpath, fs_hash) tuples for use with
308
# Create an inventory delta based on deltas between all the parents and
309
# deltas between all the parent inventories. We use inventory delta's
310
# between the inventory objects because iter_changes masks
311
# last-changed-field only changes.
313
# file_id -> change map, change is fileid, paths, changed, versioneds,
314
# parents, names, kinds, executables
316
# {file_id -> revision_id -> inventory entry, for entries in parent
317
# trees that are not parents[0]
321
revtrees = list(self.repository.revision_trees(self.parents))
322
except errors.NoSuchRevision:
323
# one or more ghosts, slow path.
325
for revision_id in self.parents:
327
revtrees.append(self.repository.revision_tree(revision_id))
328
except errors.NoSuchRevision:
330
basis_revision_id = _mod_revision.NULL_REVISION
332
revtrees.append(self.repository.revision_tree(
333
_mod_revision.NULL_REVISION))
334
# The basis inventory from a repository
336
basis_tree = revtrees[0]
338
basis_tree = self.repository.revision_tree(
339
_mod_revision.NULL_REVISION)
340
basis_inv = basis_tree.root_inventory
341
if len(self.parents) > 0:
342
if basis_revision_id != self.parents[0] and not ghost_basis:
344
"arbitrary basis parents not yet supported with merges")
345
for revtree in revtrees[1:]:
346
for change in revtree.root_inventory._make_delta(basis_inv):
347
if change[1] is None:
348
# Not present in this parent.
350
if change[2] not in merged_ids:
351
if change[0] is not None:
352
basis_entry = basis_inv.get_entry(change[2])
353
merged_ids[change[2]] = [
355
basis_entry.revision,
358
parent_entries[change[2]] = {
360
basis_entry.revision: basis_entry,
362
change[3].revision: change[3],
365
merged_ids[change[2]] = [change[3].revision]
366
parent_entries[change[2]] = {
367
change[3].revision: change[3]}
369
merged_ids[change[2]].append(change[3].revision)
370
parent_entries[change[2]
371
][change[3].revision] = change[3]
374
# Setup the changes from the tree:
375
# changes maps file_id -> (change, [parent revision_ids])
377
for change in iter_changes:
378
# This probably looks up in basis_inv way to much.
379
if change.path[0] is not None:
380
head_candidate = [basis_inv.get_entry(change.file_id).revision]
383
changes[change.file_id] = change, merged_ids.get(
384
change.file_id, head_candidate)
385
unchanged_merged = set(merged_ids) - set(changes)
386
# Extend the changes dict with synthetic changes to record merges of
388
for file_id in unchanged_merged:
389
# Record a merged version of these items that did not change vs the
390
# basis. This can be either identical parallel changes, or a revert
391
# of a specific file after a merge. The recorded content will be
392
# that of the current tree (which is the same as the basis), but
393
# the per-file graph will reflect a merge.
394
# NB:XXX: We are reconstructing path information we had, this
395
# should be preserved instead.
396
# inv delta change: (file_id, (path_in_source, path_in_target),
397
# changed_content, versioned, parent, name, kind,
400
basis_entry = basis_inv.get_entry(file_id)
401
except errors.NoSuchId:
402
# a change from basis->some_parents but file_id isn't in basis
403
# so was new in the merge, which means it must have changed
404
# from basis -> current, and as it hasn't the add was reverted
405
# by the user. So we discard this change.
410
(basis_inv.id2path(file_id), tree.id2path(file_id)),
412
(basis_entry.parent_id, basis_entry.parent_id),
413
(basis_entry.name, basis_entry.name),
414
(basis_entry.kind, basis_entry.kind),
415
(basis_entry.executable, basis_entry.executable))
416
changes[file_id] = (change, merged_ids[file_id])
417
# changes contains tuples with the change and a set of inventory
418
# candidates for the file.
420
# old_path, new_path, file_id, new_inventory_entry
421
seen_root = False # Is the root in the basis delta?
422
inv_delta = self._basis_delta
423
modified_rev = self._new_revision_id
424
for change, head_candidates in viewvalues(changes):
425
if change.versioned[1]: # versioned in target.
426
# Several things may be happening here:
427
# We may have a fork in the per-file graph
428
# - record a change with the content from tree
429
# We may have a change against < all trees
430
# - carry over the tree that hasn't changed
431
# We may have a change against all trees
432
# - record the change with the content from tree
433
kind = change.kind[1]
434
file_id = change.file_id
435
entry = _entry_factory[kind](file_id, change.name[1],
437
head_set = self._heads(change.file_id, set(head_candidates))
440
for head_candidate in head_candidates:
441
if head_candidate in head_set:
442
heads.append(head_candidate)
443
head_set.remove(head_candidate)
446
# Could be a carry-over situation:
447
parent_entry_revs = parent_entries.get(file_id, None)
448
if parent_entry_revs:
449
parent_entry = parent_entry_revs.get(heads[0], None)
452
if parent_entry is None:
453
# The parent iter_changes was called against is the one
454
# that is the per-file head, so any change is relevant
455
# iter_changes is valid.
456
carry_over_possible = False
458
# could be a carry over situation
459
# A change against the basis may just indicate a merge,
460
# we need to check the content against the source of the
461
# merge to determine if it was changed after the merge
463
if (parent_entry.kind != entry.kind
464
or parent_entry.parent_id != entry.parent_id
465
or parent_entry.name != entry.name):
466
# Metadata common to all entries has changed
467
# against per-file parent
468
carry_over_possible = False
470
carry_over_possible = True
471
# per-type checks for changes against the parent_entry
474
# Cannot be a carry-over situation
475
carry_over_possible = False
476
# Populate the entry in the delta
478
# XXX: There is still a small race here: If someone reverts the content of a file
479
# after iter_changes examines and decides it has changed,
480
# we will unconditionally record a new version even if some
481
# other process reverts it while commit is running (with
482
# the revert happening after iter_changes did its
484
if change.executable[1]:
485
entry.executable = True
487
entry.executable = False
488
if (carry_over_possible
489
and parent_entry.executable == entry.executable):
490
# Check the file length, content hash after reading
492
nostore_sha = parent_entry.text_sha1
495
file_obj, stat_value = tree.get_file_with_stat(change.path[1])
497
entry.text_sha1, entry.text_size = self._add_file_to_weave(
498
file_id, file_obj, heads, nostore_sha)
499
yield change.path[1], (entry.text_sha1, stat_value)
500
except errors.ExistingContent:
501
# No content change against a carry_over parent
502
# Perhaps this should also yield a fs hash update?
504
entry.text_size = parent_entry.text_size
505
entry.text_sha1 = parent_entry.text_sha1
508
elif kind == 'symlink':
510
entry.symlink_target = tree.get_symlink_target(
512
if (carry_over_possible and
513
parent_entry.symlink_target ==
514
entry.symlink_target):
517
self._add_file_to_weave(
518
change.file_id, BytesIO(), heads, None)
519
elif kind == 'directory':
520
if carry_over_possible:
523
# Nothing to set on the entry.
524
# XXX: split into the Root and nonRoot versions.
525
if change.path[1] != '' or self.repository.supports_rich_root():
526
self._add_file_to_weave(
527
change.file_id, BytesIO(), heads, None)
528
elif kind == 'tree-reference':
529
if not self.repository._format.supports_tree_reference:
530
# This isn't quite sane as an error, but we shouldn't
531
# ever see this code path in practice: tree's don't
532
# permit references when the repo doesn't support tree
534
raise errors.UnsupportedOperation(
535
tree.add_reference, self.repository)
536
reference_revision = tree.get_reference_revision(
538
entry.reference_revision = reference_revision
539
if (carry_over_possible
540
and parent_entry.reference_revision ==
544
self._add_file_to_weave(
545
change.file_id, BytesIO(), heads, None)
547
raise AssertionError('unknown kind %r' % kind)
549
entry.revision = modified_rev
551
entry.revision = parent_entry.revision
554
new_path = change.path[1]
555
inv_delta.append((change.path[0], new_path, change.file_id, entry))
558
# The initial commit adds a root directory, but this in itself is not
559
# a worthwhile commit.
560
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION)
561
or (len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
562
# This should perhaps be guarded by a check that the basis we
563
# commit against is the basis for the commit and if not do a delta
565
self._any_changes = True
567
# housekeeping root entry changes do not affect no-change commits.
568
self._require_root_change(tree)
569
self.basis_delta_revision = basis_revision_id
571
def _add_file_to_weave(self, file_id, fileobj, parents, nostore_sha):
572
parent_keys = tuple([(file_id, parent) for parent in parents])
573
return self.repository.texts.add_chunks(
574
(file_id, self._new_revision_id), parent_keys,
575
osutils.file_iterator(fileobj),
576
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
579
class VersionedFileRepository(Repository):
580
"""Repository holding history for one or more branches.
582
The repository holds and retrieves historical information including
583
revisions and file history. It's normally accessed only by the Branch,
584
which views a particular line of development through that history.
586
The Repository builds on top of some byte storage facilies (the revisions,
587
signatures, inventories, texts and chk_bytes attributes) and a Transport,
588
which respectively provide byte storage and a means to access the (possibly
591
The byte storage facilities are addressed via tuples, which we refer to
592
as 'keys' throughout the code base. Revision_keys, inventory_keys and
593
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
594
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
595
byte string made up of a hash identifier and a hash value.
596
We use this interface because it allows low friction with the underlying
597
code that implements disk indices, network encoding and other parts of
600
:ivar revisions: A breezy.versionedfile.VersionedFiles instance containing
601
the serialised revisions for the repository. This can be used to obtain
602
revision graph information or to access raw serialised revisions.
603
The result of trying to insert data into the repository via this store
604
is undefined: it should be considered read-only except for implementors
606
:ivar signatures: A breezy.versionedfile.VersionedFiles instance containing
607
the serialised signatures for the repository. This can be used to
608
obtain access to raw serialised signatures. The result of trying to
609
insert data into the repository via this store is undefined: it should
610
be considered read-only except for implementors of repositories.
611
:ivar inventories: A breezy.versionedfile.VersionedFiles instance containing
612
the serialised inventories for the repository. This can be used to
613
obtain unserialised inventories. The result of trying to insert data
614
into the repository via this store is undefined: it should be
615
considered read-only except for implementors of repositories.
616
:ivar texts: A breezy.versionedfile.VersionedFiles instance containing the
617
texts of files and directories for the repository. This can be used to
618
obtain file texts or file graphs. Note that Repository.iter_file_bytes
619
is usually a better interface for accessing file texts.
620
The result of trying to insert data into the repository via this store
621
is undefined: it should be considered read-only except for implementors
623
:ivar chk_bytes: A breezy.versionedfile.VersionedFiles instance containing
624
any data the repository chooses to store or have indexed by its hash.
625
The result of trying to insert data into the repository via this store
626
is undefined: it should be considered read-only except for implementors
628
:ivar _transport: Transport for file access to repository, typically
629
pointing to .bzr/repository.
632
# What class to use for a CommitBuilder. Often it's simpler to change this
633
# in a Repository class subclass rather than to override
634
# get_commit_builder.
635
_commit_builder_class = VersionedFileCommitBuilder
637
def add_fallback_repository(self, repository):
638
"""Add a repository to use for looking up data not held locally.
640
:param repository: A repository.
642
if not self._format.supports_external_lookups:
643
raise errors.UnstackableRepositoryFormat(self._format, self.base)
644
# This can raise an exception, so should be done before we lock the
645
# fallback repository.
646
self._check_fallback_repository(repository)
648
# This repository will call fallback.unlock() when we transition to
649
# the unlocked state, so we make sure to increment the lock count
650
repository.lock_read()
651
self._fallback_repositories.append(repository)
652
self.texts.add_fallback_versioned_files(repository.texts)
653
self.inventories.add_fallback_versioned_files(repository.inventories)
654
self.revisions.add_fallback_versioned_files(repository.revisions)
655
self.signatures.add_fallback_versioned_files(repository.signatures)
656
if self.chk_bytes is not None:
657
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
659
def create_bundle(self, target, base, fileobj, format=None):
660
return serializer.write_bundle(self, target, base, fileobj, format)
662
@only_raises(errors.LockNotHeld, errors.LockBroken)
664
super(VersionedFileRepository, self).unlock()
665
if self.control_files._lock_count == 0:
666
self._inventory_entry_cache.clear()
668
def add_inventory(self, revision_id, inv, parents):
669
"""Add the inventory inv to the repository as revision_id.
671
:param parents: The revision ids of the parents that revision_id
672
is known to have and are in the repository already.
674
:returns: The validator(which is a sha1 digest, though what is sha'd is
675
repository format specific) of the serialized inventory.
677
if not self.is_in_write_group():
678
raise AssertionError("%r not in write group" % (self,))
679
_mod_revision.check_not_reserved_id(revision_id)
680
if not (inv.revision_id is None or inv.revision_id == revision_id):
681
raise AssertionError(
682
"Mismatch between inventory revision"
683
" id and insertion revid (%r, %r)"
684
% (inv.revision_id, revision_id))
686
raise errors.RootMissing()
687
return self._add_inventory_checked(revision_id, inv, parents)
689
def _add_inventory_checked(self, revision_id, inv, parents):
690
"""Add inv to the repository after checking the inputs.
692
This function can be overridden to allow different inventory styles.
694
:seealso: add_inventory, for the contract.
696
inv_lines = self._serializer.write_inventory_to_lines(inv)
697
return self._inventory_add_lines(revision_id, parents,
698
inv_lines, check_content=False)
700
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
701
parents, basis_inv=None, propagate_caches=False):
702
"""Add a new inventory expressed as a delta against another revision.
704
See the inventory developers documentation for the theory behind
707
:param basis_revision_id: The inventory id the delta was created
708
against. (This does not have to be a direct parent.)
709
:param delta: The inventory delta (see Inventory.apply_delta for
711
:param new_revision_id: The revision id that the inventory is being
713
:param parents: The revision ids of the parents that revision_id is
714
known to have and are in the repository already. These are supplied
715
for repositories that depend on the inventory graph for revision
716
graph access, as well as for those that pun ancestry with delta
718
:param basis_inv: The basis inventory if it is already known,
720
:param propagate_caches: If True, the caches for this inventory are
721
copied to and updated for the result if possible.
723
:returns: (validator, new_inv)
724
The validator(which is a sha1 digest, though what is sha'd is
725
repository format specific) of the serialized inventory, and the
728
if not self.is_in_write_group():
729
raise AssertionError("%r not in write group" % (self,))
730
_mod_revision.check_not_reserved_id(new_revision_id)
731
basis_tree = self.revision_tree(basis_revision_id)
732
with basis_tree.lock_read():
733
# Note that this mutates the inventory of basis_tree, which not all
734
# inventory implementations may support: A better idiom would be to
735
# return a new inventory, but as there is no revision tree cache in
736
# repository this is safe for now - RBC 20081013
737
if basis_inv is None:
738
basis_inv = basis_tree.root_inventory
739
basis_inv.apply_delta(delta)
740
basis_inv.revision_id = new_revision_id
741
return (self.add_inventory(new_revision_id, basis_inv, parents),
744
def _inventory_add_lines(self, revision_id, parents, lines,
746
"""Store lines in inv_vf and return the sha1 of the inventory."""
747
parents = [(parent,) for parent in parents]
748
result = self.inventories.add_lines((revision_id,), parents, lines,
749
check_content=check_content)[0]
750
self.inventories._access.flush()
753
def add_revision(self, revision_id, rev, inv=None):
754
"""Add rev to the revision store as revision_id.
756
:param revision_id: the revision id to use.
757
:param rev: The revision object.
758
:param inv: The inventory for the revision. if None, it will be looked
759
up in the inventory storer
761
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
763
_mod_revision.check_not_reserved_id(revision_id)
764
# check inventory present
765
if not self.inventories.get_parent_map([(revision_id,)]):
767
raise errors.WeaveRevisionNotPresent(revision_id,
770
# yes, this is not suitable for adding with ghosts.
771
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
775
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
776
self._add_revision(rev)
778
def _add_revision(self, revision):
779
text = self._serializer.write_revision_to_string(revision)
780
key = (revision.revision_id,)
781
parents = tuple((parent,) for parent in revision.parent_ids)
782
self.revisions.add_lines(key, parents, osutils.split_lines(text))
784
def _check_inventories(self, checker):
785
"""Check the inventories found from the revision scan.
787
This is responsible for verifying the sha1 of inventories and
788
creating a pending_keys set that covers data referenced by inventories.
790
with ui.ui_factory.nested_progress_bar() as bar:
791
self._do_check_inventories(checker, bar)
793
def _do_check_inventories(self, checker, bar):
794
"""Helper for _check_inventories."""
796
keys = {'chk_bytes': set(), 'inventories': set(), 'texts': set()}
797
kinds = ['chk_bytes', 'texts']
798
count = len(checker.pending_keys)
799
bar.update(gettext("inventories"), 0, 2)
800
current_keys = checker.pending_keys
801
checker.pending_keys = {}
802
# Accumulate current checks.
803
for key in current_keys:
804
if key[0] != 'inventories' and key[0] not in kinds:
805
checker._report_items.append('unknown key type %r' % (key,))
806
keys[key[0]].add(key[1:])
807
if keys['inventories']:
808
# NB: output order *should* be roughly sorted - topo or
809
# inverse topo depending on repository - either way decent
810
# to just delta against. However, pre-CHK formats didn't
811
# try to optimise inventory layout on disk. As such the
812
# pre-CHK code path does not use inventory deltas.
814
for record in self.inventories.check(keys=keys['inventories']):
815
if record.storage_kind == 'absent':
816
checker._report_items.append(
817
'Missing inventory {%s}' % (record.key,))
819
last_object = self._check_record('inventories', record,
820
checker, last_object,
821
current_keys[('inventories',) + record.key])
822
del keys['inventories']
825
bar.update(gettext("texts"), 1)
826
while (checker.pending_keys or keys['chk_bytes'] or
828
# Something to check.
829
current_keys = checker.pending_keys
830
checker.pending_keys = {}
831
# Accumulate current checks.
832
for key in current_keys:
833
if key[0] not in kinds:
834
checker._report_items.append(
835
'unknown key type %r' % (key,))
836
keys[key[0]].add(key[1:])
837
# Check the outermost kind only - inventories || chk_bytes || texts
841
for record in getattr(self, kind).check(keys=keys[kind]):
842
if record.storage_kind == 'absent':
843
checker._report_items.append(
844
'Missing %s {%s}' % (kind, record.key,))
846
last_object = self._check_record(kind, record,
847
checker, last_object, current_keys[(kind,) + record.key])
851
def _check_record(self, kind, record, checker, last_object, item_data):
852
"""Check a single text from this repository."""
853
if kind == 'inventories':
854
rev_id = record.key[0]
855
inv = self._deserialise_inventory(rev_id,
856
record.get_bytes_as('fulltext'))
857
if last_object is not None:
858
delta = inv._make_delta(last_object)
859
for old_path, path, file_id, ie in delta:
862
ie.check(checker, rev_id, inv)
864
for path, ie in inv.iter_entries():
865
ie.check(checker, rev_id, inv)
866
if self._format.fast_deltas:
868
elif kind == 'chk_bytes':
869
# No code written to check chk_bytes for this repo format.
870
checker._report_items.append(
871
'unsupported key type chk_bytes for %s' % (record.key,))
872
elif kind == 'texts':
873
self._check_text(record, checker, item_data)
875
checker._report_items.append(
876
'unknown key type %s for %s' % (kind, record.key))
878
def _check_text(self, record, checker, item_data):
879
"""Check a single text."""
880
# Check it is extractable.
881
# TODO: check length.
882
if record.storage_kind == 'chunked':
883
chunks = record.get_bytes_as(record.storage_kind)
884
sha1 = osutils.sha_strings(chunks)
885
length = sum(map(len, chunks))
887
content = record.get_bytes_as('fulltext')
888
sha1 = osutils.sha_string(content)
889
length = len(content)
890
if item_data and sha1 != item_data[1]:
891
checker._report_items.append(
892
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
893
(record.key, sha1, item_data[1], item_data[2]))
895
def _eliminate_revisions_not_present(self, revision_ids):
896
"""Check every revision id in revision_ids to see if we have it.
898
Returns a set of the present revisions.
900
with self.lock_read():
902
graph = self.get_graph()
903
parent_map = graph.get_parent_map(revision_ids)
904
# The old API returned a list, should this actually be a set?
905
return list(parent_map)
907
def __init__(self, _format, a_controldir, control_files):
908
"""Instantiate a VersionedFileRepository.
910
:param _format: The format of the repository on disk.
911
:param controldir: The ControlDir of the repository.
912
:param control_files: Control files to use for locking, etc.
914
# In the future we will have a single api for all stores for
915
# getting file texts, inventories and revisions, then
916
# this construct will accept instances of those things.
917
super(VersionedFileRepository, self).__init__(_format, a_controldir,
919
self._transport = control_files._transport
920
self.base = self._transport.base
922
self._reconcile_does_inventory_gc = True
923
self._reconcile_fixes_text_parents = False
924
self._reconcile_backsup_inventory = True
925
# An InventoryEntry cache, used during deserialization
926
self._inventory_entry_cache = fifo_cache.FIFOCache(10 * 1024)
927
# Is it safe to return inventory entries directly from the entry cache,
928
# rather copying them?
929
self._safe_to_return_from_cache = False
931
def fetch(self, source, revision_id=None, find_ghosts=False,
933
"""Fetch the content required to construct revision_id from source.
935
If revision_id is None and fetch_spec is None, then all content is
938
fetch() may not be used when the repository is in a write group -
939
either finish the current write group before using fetch, or use
940
fetch before starting the write group.
942
:param find_ghosts: Find and copy revisions in the source that are
943
ghosts in the target (and not reachable directly by walking out to
944
the first-present revision in target from revision_id).
945
:param revision_id: If specified, all the content needed for this
946
revision ID will be copied to the target. Fetch will determine for
947
itself which content needs to be copied.
948
:param fetch_spec: If specified, a SearchResult or
949
PendingAncestryResult that describes which revisions to copy. This
950
allows copying multiple heads at once. Mutually exclusive with
953
if fetch_spec is not None and revision_id is not None:
954
raise AssertionError(
955
"fetch_spec and revision_id are mutually exclusive.")
956
if self.is_in_write_group():
957
raise errors.InternalBzrError(
958
"May not fetch while in a write group.")
959
# fast path same-url fetch operations
960
# TODO: lift out to somewhere common with RemoteRepository
961
# <https://bugs.launchpad.net/bzr/+bug/401646>
962
if (self.has_same_location(source) and
963
fetch_spec is None and
964
self._has_same_fallbacks(source)):
965
# check that last_revision is in 'from' and then return a
967
if (revision_id is not None
968
and not _mod_revision.is_null(revision_id)):
969
self.get_revision(revision_id)
971
inter = InterRepository.get(source, self)
972
if (fetch_spec is not None
973
and not getattr(inter, "supports_fetch_spec", False)):
974
raise errors.UnsupportedOperation(
975
"fetch_spec not supported for %r" % inter)
976
return inter.fetch(revision_id=revision_id,
977
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
979
def gather_stats(self, revid=None, committers=None):
980
"""See Repository.gather_stats()."""
981
with self.lock_read():
982
result = super(VersionedFileRepository,
983
self).gather_stats(revid, committers)
984
# now gather global repository information
985
# XXX: This is available for many repos regardless of listability.
986
if self.user_transport.listable():
987
# XXX: do we want to __define len__() ?
988
# Maybe the versionedfiles object should provide a different
989
# method to get the number of keys.
990
result['revisions'] = len(self.revisions.keys())
994
def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
995
timezone=None, committer=None, revprops=None,
996
revision_id=None, lossy=False):
997
"""Obtain a CommitBuilder for this repository.
999
:param branch: Branch to commit to.
1000
:param parents: Revision ids of the parents of the new revision.
1001
:param config_stack: Configuration stack to use.
1002
:param timestamp: Optional timestamp recorded for commit.
1003
:param timezone: Optional timezone for timestamp.
1004
:param committer: Optional committer to set for commit.
1005
:param revprops: Optional dictionary of revision properties.
1006
:param revision_id: Optional revision id.
1007
:param lossy: Whether to discard data that can not be natively
1008
represented, when pushing to a foreign VCS
1010
if self._fallback_repositories and not self._format.supports_chks:
1011
raise errors.BzrError("Cannot commit directly to a stacked branch"
1012
" in pre-2a formats. See "
1013
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1014
result = self._commit_builder_class(self, parents, config_stack,
1015
timestamp, timezone, committer, revprops, revision_id,
1017
self.start_write_group()
1020
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1021
"""Return the keys of missing inventory parents for revisions added in
1024
A revision is not complete if the inventory delta for that revision
1025
cannot be calculated. Therefore if the parent inventories of a
1026
revision are not present, the revision is incomplete, and e.g. cannot
1027
be streamed by a smart server. This method finds missing inventory
1028
parents for revisions added in this write group.
1030
if not self._format.supports_external_lookups:
1031
# This is only an issue for stacked repositories
1033
if not self.is_in_write_group():
1034
raise AssertionError('not in a write group')
1036
# XXX: We assume that every added revision already has its
1037
# corresponding inventory, so we only check for parent inventories that
1038
# might be missing, rather than all inventories.
1039
parents = set(self.revisions._index.get_missing_parents())
1040
parents.discard(_mod_revision.NULL_REVISION)
1041
unstacked_inventories = self.inventories._index
1042
present_inventories = unstacked_inventories.get_parent_map(
1043
key[-1:] for key in parents)
1044
parents.difference_update(present_inventories)
1045
if len(parents) == 0:
1046
# No missing parent inventories.
1048
if not check_for_missing_texts:
1049
return set(('inventories', rev_id) for (rev_id,) in parents)
1050
# Ok, now we have a list of missing inventories. But these only matter
1051
# if the inventories that reference them are missing some texts they
1052
# appear to introduce.
1053
# XXX: Texts referenced by all added inventories need to be present,
1054
# but at the moment we're only checking for texts referenced by
1055
# inventories at the graph's edge.
1056
key_deps = self.revisions._index._key_dependencies
1057
key_deps.satisfy_refs_for_keys(present_inventories)
1058
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1059
file_ids = self.fileids_altered_by_revision_ids(referrers)
1060
missing_texts = set()
1061
for file_id, version_ids in viewitems(file_ids):
1062
missing_texts.update(
1063
(file_id, version_id) for version_id in version_ids)
1064
present_texts = self.texts.get_parent_map(missing_texts)
1065
missing_texts.difference_update(present_texts)
1066
if not missing_texts:
1067
# No texts are missing, so all revisions and their deltas are
1070
# Alternatively the text versions could be returned as the missing
1071
# keys, but this is likely to be less data.
1072
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1075
def has_revisions(self, revision_ids):
1076
"""Probe to find out the presence of multiple revisions.
1078
:param revision_ids: An iterable of revision_ids.
1079
:return: A set of the revision_ids that were present.
1081
with self.lock_read():
1082
parent_map = self.revisions.get_parent_map(
1083
[(rev_id,) for rev_id in revision_ids])
1085
if _mod_revision.NULL_REVISION in revision_ids:
1086
result.add(_mod_revision.NULL_REVISION)
1087
result.update([key[0] for key in parent_map])
1090
def get_revision_reconcile(self, revision_id):
1091
"""'reconcile' helper routine that allows access to a revision always.
1093
This variant of get_revision does not cross check the weave graph
1094
against the revision one as get_revision does: but it should only
1095
be used by reconcile, or reconcile-alike commands that are correcting
1096
or testing the revision graph.
1098
with self.lock_read():
1099
return self.get_revisions([revision_id])[0]
1101
def iter_revisions(self, revision_ids):
1102
"""Iterate over revision objects.
1104
:param revision_ids: An iterable of revisions to examine. None may be
1105
passed to request all revisions known to the repository. Note that
1106
not all repositories can find unreferenced revisions; for those
1107
repositories only referenced ones will be returned.
1108
:return: An iterator of (revid, revision) tuples. Absent revisions (
1109
those asked for but not available) are returned as (revid, None).
1111
with self.lock_read():
1112
for rev_id in revision_ids:
1113
if not rev_id or not isinstance(rev_id, bytes):
1114
raise errors.InvalidRevisionId(
1115
revision_id=rev_id, branch=self)
1116
keys = [(key,) for key in revision_ids]
1117
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1118
for record in stream:
1119
revid = record.key[0]
1120
if record.storage_kind == 'absent':
1123
text = record.get_bytes_as('fulltext')
1124
rev = self._serializer.read_revision_from_string(text)
1127
def add_signature_text(self, revision_id, signature):
1128
"""Store a signature text for a revision.
1130
:param revision_id: Revision id of the revision
1131
:param signature: Signature text.
1133
with self.lock_write():
1134
self.signatures.add_lines((revision_id,), (),
1135
osutils.split_lines(signature))
1137
def sign_revision(self, revision_id, gpg_strategy):
1138
with self.lock_write():
1139
testament = Testament.from_revision(
1141
plaintext = testament.as_short_text()
1142
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1144
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1145
with self.lock_write():
1146
signature = gpg_strategy.sign(plaintext, gpg.MODE_CLEAR)
1147
self.add_signature_text(revision_id, signature)
1149
def verify_revision_signature(self, revision_id, gpg_strategy):
1150
"""Verify the signature on a revision.
1152
:param revision_id: the revision to verify
1153
:gpg_strategy: the GPGStrategy object to used
1155
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
1157
with self.lock_read():
1158
if not self.has_signature_for_revision_id(revision_id):
1159
return gpg.SIGNATURE_NOT_SIGNED, None
1160
signature = self.get_signature_text(revision_id)
1162
testament = Testament.from_revision(
1165
(status, key, signed_plaintext) = gpg_strategy.verify(signature)
1166
if testament.as_short_text() != signed_plaintext:
1167
return gpg.SIGNATURE_NOT_VALID, None
1168
return (status, key)
1170
def find_text_key_references(self):
1171
"""Find the text key references within the repository.
1173
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1174
to whether they were referred to by the inventory of the
1175
revision_id that they contain. The inventory texts from all present
1176
revision ids are assessed to generate this report.
1178
revision_keys = self.revisions.keys()
1179
w = self.inventories
1180
with ui.ui_factory.nested_progress_bar() as pb:
1181
return self._serializer._find_text_key_references(
1182
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1184
def _inventory_xml_lines_for_keys(self, keys):
1185
"""Get a line iterator of the sort needed for findind references.
1187
Not relevant for non-xml inventory repositories.
1189
Ghosts in revision_keys are ignored.
1191
:param revision_keys: The revision keys for the inventories to inspect.
1192
:return: An iterator over (inventory line, revid) for the fulltexts of
1193
all of the xml inventories specified by revision_keys.
1195
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1196
for record in stream:
1197
if record.storage_kind != 'absent':
1198
chunks = record.get_bytes_as('chunked')
1199
revid = record.key[-1]
1200
lines = osutils.chunks_to_lines(chunks)
1204
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1206
"""Helper routine for fileids_altered_by_revision_ids.
1208
This performs the translation of xml lines to revision ids.
1210
:param line_iterator: An iterator of lines, origin_version_id
1211
:param revision_keys: The revision ids to filter for. This should be a
1212
set or other type which supports efficient __contains__ lookups, as
1213
the revision key from each parsed line will be looked up in the
1214
revision_keys filter.
1215
:return: a dictionary mapping altered file-ids to an iterable of
1216
revision_ids. Each altered file-ids has the exact revision_ids that
1217
altered it listed explicitly.
1219
seen = set(self._serializer._find_text_key_references(line_iterator))
1220
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1221
parent_seen = set(self._serializer._find_text_key_references(
1222
self._inventory_xml_lines_for_keys(parent_keys)))
1223
new_keys = seen - parent_seen
1225
setdefault = result.setdefault
1226
for key in new_keys:
1227
setdefault(key[0], set()).add(key[-1])
1230
def _find_parent_keys_of_revisions(self, revision_keys):
1231
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1233
:param revision_keys: An iterable of revision_keys.
1234
:return: The parents of all revision_keys that are not already in
1237
parent_map = self.revisions.get_parent_map(revision_keys)
1238
parent_keys = set(itertools.chain.from_iterable(
1239
viewvalues(parent_map)))
1240
parent_keys.difference_update(revision_keys)
1241
parent_keys.discard(_mod_revision.NULL_REVISION)
1244
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1245
"""Find the file ids and versions affected by revisions.
1247
:param revisions: an iterable containing revision ids.
1248
:param _inv_weave: The inventory weave from this repository or None.
1249
If None, the inventory weave will be opened automatically.
1250
:return: a dictionary mapping altered file-ids to an iterable of
1251
revision_ids. Each altered file-ids has the exact revision_ids that
1252
altered it listed explicitly.
1254
selected_keys = set((revid,) for revid in revision_ids)
1255
w = _inv_weave or self.inventories
1256
return self._find_file_ids_from_xml_inventory_lines(
1257
w.iter_lines_added_or_present_in_keys(
1258
selected_keys, pb=None),
1261
def iter_files_bytes(self, desired_files):
1262
"""Iterate through file versions.
1264
Files will not necessarily be returned in the order they occur in
1265
desired_files. No specific order is guaranteed.
1267
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1268
value supplied by the caller as part of desired_files. It should
1269
uniquely identify the file version in the caller's context. (Examples:
1270
an index number or a TreeTransform trans_id.)
1272
bytes_iterator is an iterable of bytestrings for the file. The
1273
kind of iterable and length of the bytestrings are unspecified, but for
1274
this implementation, it is a list of bytes produced by
1275
VersionedFile.get_record_stream().
1277
:param desired_files: a list of (file_id, revision_id, identifier)
1281
for file_id, revision_id, callable_data in desired_files:
1282
text_keys[(file_id, revision_id)] = callable_data
1283
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1284
if record.storage_kind == 'absent':
1285
raise errors.RevisionNotPresent(record.key[1], record.key[0])
1286
yield text_keys[record.key], record.get_bytes_as('chunked')
1288
def _generate_text_key_index(self, text_key_references=None,
1290
"""Generate a new text key index for the repository.
1292
This is an expensive function that will take considerable time to run.
1294
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1295
list of parents, also text keys. When a given key has no parents,
1296
the parents list will be [NULL_REVISION].
1298
# All revisions, to find inventory parents.
1299
if ancestors is None:
1300
graph = self.get_graph()
1301
ancestors = graph.get_parent_map(self.all_revision_ids())
1302
if text_key_references is None:
1303
text_key_references = self.find_text_key_references()
1304
with ui.ui_factory.nested_progress_bar() as pb:
1305
return self._do_generate_text_key_index(ancestors,
1306
text_key_references, pb)
1308
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1309
"""Helper for _generate_text_key_index to avoid deep nesting."""
1310
revision_order = tsort.topo_sort(ancestors)
1311
invalid_keys = set()
1313
for revision_id in revision_order:
1314
revision_keys[revision_id] = set()
1315
text_count = len(text_key_references)
1316
# a cache of the text keys to allow reuse; costs a dict of all the
1317
# keys, but saves a 2-tuple for every child of a given key.
1319
for text_key, valid in viewitems(text_key_references):
1321
invalid_keys.add(text_key)
1323
revision_keys[text_key[1]].add(text_key)
1324
text_key_cache[text_key] = text_key
1325
del text_key_references
1327
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1328
NULL_REVISION = _mod_revision.NULL_REVISION
1329
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1330
# too small for large or very branchy trees. However, for 55K path
1331
# trees, it would be easy to use too much memory trivially. Ideally we
1332
# could gauge this by looking at available real memory etc, but this is
1333
# always a tricky proposition.
1334
inventory_cache = lru_cache.LRUCache(10)
1335
batch_size = 10 # should be ~150MB on a 55K path tree
1336
batch_count = len(revision_order) // batch_size + 1
1338
pb.update(gettext("Calculating text parents"),
1339
processed_texts, text_count)
1340
for offset in range(batch_count):
1341
to_query = revision_order[offset * batch_size:(offset + 1)
1345
for revision_id in to_query:
1346
parent_ids = ancestors[revision_id]
1347
for text_key in revision_keys[revision_id]:
1348
pb.update(gettext("Calculating text parents"),
1350
processed_texts += 1
1351
candidate_parents = []
1352
for parent_id in parent_ids:
1353
parent_text_key = (text_key[0], parent_id)
1355
check_parent = parent_text_key not in \
1356
revision_keys[parent_id]
1358
# the parent parent_id is a ghost:
1359
check_parent = False
1360
# truncate the derived graph against this ghost.
1361
parent_text_key = None
1363
# look at the parent commit details inventories to
1364
# determine possible candidates in the per file graph.
1367
inv = inventory_cache[parent_id]
1369
inv = self.revision_tree(
1370
parent_id).root_inventory
1371
inventory_cache[parent_id] = inv
1373
parent_entry = inv.get_entry(text_key[0])
1374
except (KeyError, errors.NoSuchId):
1376
if parent_entry is not None:
1378
text_key[0], parent_entry.revision)
1380
parent_text_key = None
1381
if parent_text_key is not None:
1382
candidate_parents.append(
1383
text_key_cache[parent_text_key])
1384
parent_heads = text_graph.heads(candidate_parents)
1385
new_parents = list(parent_heads)
1386
new_parents.sort(key=lambda x: candidate_parents.index(x))
1387
if new_parents == []:
1388
new_parents = [NULL_REVISION]
1389
text_index[text_key] = new_parents
1391
for text_key in invalid_keys:
1392
text_index[text_key] = [NULL_REVISION]
1395
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1396
"""Get an iterable listing the keys of all the data introduced by a set
1399
The keys will be ordered so that the corresponding items can be safely
1400
fetched and inserted in that order.
1402
:returns: An iterable producing tuples of (knit-kind, file-id,
1403
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1404
'revisions'. file-id is None unless knit-kind is 'file'.
1406
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1409
for result in self._find_non_file_keys_to_fetch(revision_ids):
1412
def _find_file_keys_to_fetch(self, revision_ids, pb):
1413
# XXX: it's a bit weird to control the inventory weave caching in this
1414
# generator. Ideally the caching would be done in fetch.py I think. Or
1415
# maybe this generator should explicitly have the contract that it
1416
# should not be iterated until the previously yielded item has been
1418
inv_w = self.inventories
1420
# file ids that changed
1421
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1423
num_file_ids = len(file_ids)
1424
for file_id, altered_versions in viewitems(file_ids):
1426
pb.update(gettext("Fetch texts"), count, num_file_ids)
1428
yield ("file", file_id, altered_versions)
1430
def _find_non_file_keys_to_fetch(self, revision_ids):
1432
yield ("inventory", None, revision_ids)
1435
# XXX: Note ATM no callers actually pay attention to this return
1436
# instead they just use the list of revision ids and ignore
1437
# missing sigs. Consider removing this work entirely
1438
revisions_with_signatures = set(self.signatures.get_parent_map(
1439
[(r,) for r in revision_ids]))
1440
revisions_with_signatures = {r for (r,) in revisions_with_signatures}
1441
revisions_with_signatures.intersection_update(revision_ids)
1442
yield ("signatures", None, revisions_with_signatures)
1445
yield ("revisions", None, revision_ids)
1447
def get_inventory(self, revision_id):
1448
"""Get Inventory object by revision id."""
1449
with self.lock_read():
1450
return next(self.iter_inventories([revision_id]))
1452
def iter_inventories(self, revision_ids, ordering=None):
1453
"""Get many inventories by revision_ids.
1455
This will buffer some or all of the texts used in constructing the
1456
inventories in memory, but will only parse a single inventory at a
1459
:param revision_ids: The expected revision ids of the inventories.
1460
:param ordering: optional ordering, e.g. 'topological'. If not
1461
specified, the order of revision_ids will be preserved (by
1462
buffering if necessary).
1463
:return: An iterator of inventories.
1465
if ((None in revision_ids) or
1466
(_mod_revision.NULL_REVISION in revision_ids)):
1467
raise ValueError('cannot get null revision inventory')
1468
for inv, revid in self._iter_inventories(revision_ids, ordering):
1470
raise errors.NoSuchRevision(self, revid)
1473
def _iter_inventories(self, revision_ids, ordering):
1474
"""single-document based inventory iteration."""
1475
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1476
for text, revision_id in inv_xmls:
1478
yield None, revision_id
1480
yield self._deserialise_inventory(revision_id, text), revision_id
1482
def _iter_inventory_xmls(self, revision_ids, ordering):
1483
if ordering is None:
1484
order_as_requested = True
1485
ordering = 'unordered'
1487
order_as_requested = False
1488
keys = [(revision_id,) for revision_id in revision_ids]
1491
if order_as_requested:
1492
key_iter = iter(keys)
1493
next_key = next(key_iter)
1494
stream = self.inventories.get_record_stream(keys, ordering, True)
1496
for record in stream:
1497
if record.storage_kind != 'absent':
1498
chunks = record.get_bytes_as('chunked')
1499
if order_as_requested:
1500
text_chunks[record.key] = chunks
1502
yield b''.join(chunks), record.key[-1]
1504
yield None, record.key[-1]
1505
if order_as_requested:
1506
# Yield as many results as we can while preserving order.
1507
while next_key in text_chunks:
1508
chunks = text_chunks.pop(next_key)
1509
yield b''.join(chunks), next_key[-1]
1511
next_key = next(key_iter)
1512
except StopIteration:
1513
# We still want to fully consume the get_record_stream,
1514
# just in case it is not actually finished at this point
1518
def _deserialise_inventory(self, revision_id, xml):
1519
"""Transform the xml into an inventory object.
1521
:param revision_id: The expected revision id of the inventory.
1522
:param xml: A serialised inventory.
1524
result = self._serializer.read_inventory_from_string(xml, revision_id,
1525
entry_cache=self._inventory_entry_cache,
1526
return_from_cache=self._safe_to_return_from_cache)
1527
if result.revision_id != revision_id:
1528
raise AssertionError('revision id mismatch %s != %s' % (
1529
result.revision_id, revision_id))
1532
def get_serializer_format(self):
1533
return self._serializer.format_num
1535
def _get_inventory_xml(self, revision_id):
1536
"""Get serialized inventory as a string."""
1537
with self.lock_read():
1538
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1539
text, revision_id = next(texts)
1541
raise errors.NoSuchRevision(self, revision_id)
1544
def revision_tree(self, revision_id):
1545
"""Return Tree for a revision on this branch.
1547
`revision_id` may be NULL_REVISION for the empty tree revision.
1549
revision_id = _mod_revision.ensure_null(revision_id)
1550
# TODO: refactor this to use an existing revision object
1551
# so we don't need to read it in twice.
1552
if revision_id == _mod_revision.NULL_REVISION:
1553
return inventorytree.InventoryRevisionTree(self,
1554
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1556
with self.lock_read():
1557
inv = self.get_inventory(revision_id)
1558
return inventorytree.InventoryRevisionTree(self, inv, revision_id)
1560
def revision_trees(self, revision_ids):
1561
"""Return Trees for revisions in this repository.
1563
:param revision_ids: a sequence of revision-ids;
1564
a revision-id may not be None or b'null:'
1566
inventories = self.iter_inventories(revision_ids)
1567
for inv in inventories:
1568
yield inventorytree.InventoryRevisionTree(self, inv, inv.revision_id)
1570
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1571
"""Produce a generator of revision deltas.
1573
Note that the input is a sequence of REVISIONS, not revision_ids.
1574
Trees will be held in memory until the generator exits.
1575
Each delta is relative to the revision's lefthand predecessor.
1577
:param specific_fileids: if not None, the result is filtered
1578
so that only those file-ids, their parents and their
1579
children are included.
1581
# Get the revision-ids of interest
1582
required_trees = set()
1583
for revision in revisions:
1584
required_trees.add(revision.revision_id)
1585
required_trees.update(revision.parent_ids[:1])
1587
# Get the matching filtered trees. Note that it's more
1588
# efficient to pass filtered trees to changes_from() rather
1589
# than doing the filtering afterwards. changes_from() could
1590
# arguably do the filtering itself but it's path-based, not
1591
# file-id based, so filtering before or afterwards is
1593
if specific_fileids is None:
1594
trees = dict((t.get_revision_id(), t) for
1595
t in self.revision_trees(required_trees))
1597
trees = dict((t.get_revision_id(), t) for
1598
t in self._filtered_revision_trees(required_trees,
1601
# Calculate the deltas
1602
for revision in revisions:
1603
if not revision.parent_ids:
1604
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
1606
old_tree = trees[revision.parent_ids[0]]
1607
yield trees[revision.revision_id].changes_from(old_tree)
1609
def _filtered_revision_trees(self, revision_ids, file_ids):
1610
"""Return Tree for a revision on this branch with only some files.
1612
:param revision_ids: a sequence of revision-ids;
1613
a revision-id may not be None or b'null:'
1614
:param file_ids: if not None, the result is filtered
1615
so that only those file-ids, their parents and their
1616
children are included.
1618
inventories = self.iter_inventories(revision_ids)
1619
for inv in inventories:
1620
# Should we introduce a FilteredRevisionTree class rather
1621
# than pre-filter the inventory here?
1622
filtered_inv = inv.filter(file_ids)
1623
yield inventorytree.InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1625
def get_parent_map(self, revision_ids):
1626
"""See graph.StackedParentsProvider.get_parent_map"""
1627
# revisions index works in keys; this just works in revisions
1628
# therefore wrap and unwrap
1631
for revision_id in revision_ids:
1632
if revision_id == _mod_revision.NULL_REVISION:
1633
result[revision_id] = ()
1634
elif revision_id is None:
1635
raise ValueError('get_parent_map(None) is not valid')
1637
query_keys.append((revision_id,))
1638
for (revision_id,), parent_keys in viewitems(
1639
self.revisions.get_parent_map(query_keys)):
1641
result[revision_id] = tuple([parent_revid
1642
for (parent_revid,) in parent_keys])
1644
result[revision_id] = (_mod_revision.NULL_REVISION,)
1647
def get_known_graph_ancestry(self, revision_ids):
1648
"""Return the known graph for a set of revision ids and their ancestors.
1650
st = static_tuple.StaticTuple
1651
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1652
with self.lock_read():
1653
known_graph = self.revisions.get_known_graph_ancestry(
1655
return graph.GraphThunkIdsToKeys(known_graph)
1657
def get_file_graph(self):
1658
"""Return the graph walker for text revisions."""
1659
with self.lock_read():
1660
return graph.Graph(self.texts)
1662
def revision_ids_to_search_result(self, result_set):
1663
"""Convert a set of revision ids to a graph SearchResult."""
1664
result_parents = set(itertools.chain.from_iterable(viewvalues(
1665
self.get_graph().get_parent_map(result_set))))
1666
included_keys = result_set.intersection(result_parents)
1667
start_keys = result_set.difference(included_keys)
1668
exclude_keys = result_parents.difference(result_set)
1669
result = vf_search.SearchResult(start_keys, exclude_keys,
1670
len(result_set), result_set)
1673
def _get_versioned_file_checker(self, text_key_references=None,
1675
"""Return an object suitable for checking versioned files.
1677
:param text_key_references: if non-None, an already built
1678
dictionary mapping text keys ((fileid, revision_id) tuples)
1679
to whether they were referred to by the inventory of the
1680
revision_id that they contain. If None, this will be
1682
:param ancestors: Optional result from
1683
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1686
return _VersionedFileChecker(self,
1687
text_key_references=text_key_references, ancestors=ancestors)
1689
def has_signature_for_revision_id(self, revision_id):
1690
"""Query for a revision signature for revision_id in the repository."""
1691
with self.lock_read():
1692
if not self.has_revision(revision_id):
1693
raise errors.NoSuchRevision(self, revision_id)
1694
sig_present = (1 == len(
1695
self.signatures.get_parent_map([(revision_id,)])))
1698
def get_signature_text(self, revision_id):
1699
"""Return the text for a signature."""
1700
with self.lock_read():
1701
stream = self.signatures.get_record_stream([(revision_id,)],
1703
record = next(stream)
1704
if record.storage_kind == 'absent':
1705
raise errors.NoSuchRevision(self, revision_id)
1706
return record.get_bytes_as('fulltext')
1708
def _check(self, revision_ids, callback_refs, check_repo):
1709
with self.lock_read():
1710
result = check.VersionedFileCheck(self, check_repo=check_repo)
1711
result.check(callback_refs)
1714
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1715
"""Find revisions with different parent lists in the revision object
1716
and in the index graph.
1718
:param revisions_iterator: None, or an iterator of (revid,
1719
Revision-or-None). This iterator controls the revisions checked.
1720
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1721
parents-in-revision).
1723
if not self.is_locked():
1724
raise AssertionError()
1726
if revisions_iterator is None:
1727
revisions_iterator = self.iter_revisions(self.all_revision_ids())
1728
for revid, revision in revisions_iterator:
1729
if revision is None:
1731
parent_map = vf.get_parent_map([(revid,)])
1732
parents_according_to_index = tuple(parent[-1] for parent in
1733
parent_map[(revid,)])
1734
parents_according_to_revision = tuple(revision.parent_ids)
1735
if parents_according_to_index != parents_according_to_revision:
1736
yield (revid, parents_according_to_index,
1737
parents_according_to_revision)
1739
def _check_for_inconsistent_revision_parents(self):
1740
inconsistencies = list(self._find_inconsistent_revision_parents())
1742
raise errors.BzrCheckError(
1743
"Revision knit has inconsistent parents.")
1745
def _get_sink(self):
1746
"""Return a sink for streaming into this repository."""
1747
return StreamSink(self)
1749
def _get_source(self, to_format):
1750
"""Return a source for streaming from this repository."""
1751
return StreamSource(self, to_format)
1753
def reconcile(self, other=None, thorough=False):
1754
"""Reconcile this repository."""
1755
from .reconcile import VersionedFileRepoReconciler
1756
with self.lock_write():
1757
reconciler = VersionedFileRepoReconciler(self, thorough=thorough)
1758
return reconciler.reconcile()
1761
class MetaDirVersionedFileRepository(MetaDirRepository,
1762
VersionedFileRepository):
1763
"""Repositories in a meta-dir, that work via versioned file objects."""
1765
def __init__(self, _format, a_controldir, control_files):
1766
super(MetaDirVersionedFileRepository, self).__init__(_format, a_controldir,
1770
class MetaDirVersionedFileRepositoryFormat(RepositoryFormatMetaDir,
1771
VersionedFileRepositoryFormat):
1772
"""Base class for repository formats using versioned files in metadirs."""
1775
class StreamSink(object):
1776
"""An object that can insert a stream into a repository.
1778
This interface handles the complexity of reserialising inventories and
1779
revisions from different formats, and allows unidirectional insertion into
1780
stacked repositories without looking for the missing basis parents
1784
def __init__(self, target_repo):
1785
self.target_repo = target_repo
1787
def insert_missing_keys(self, source, missing_keys):
1788
"""Insert missing keys from another source.
1790
:param source: StreamSource to stream from
1791
:param missing_keys: Keys to insert
1792
:return: keys still missing
1794
stream = source.get_stream_for_missing_keys(missing_keys)
1795
return self.insert_stream_without_locking(stream,
1796
self.target_repo._format)
1798
def insert_stream(self, stream, src_format, resume_tokens):
1799
"""Insert a stream's content into the target repository.
1801
:param src_format: a bzr repository format.
1803
:return: a list of resume tokens and an iterable of keys additional
1804
items required before the insertion can be completed.
1806
with self.target_repo.lock_write():
1808
self.target_repo.resume_write_group(resume_tokens)
1811
self.target_repo.start_write_group()
1814
# locked_insert_stream performs a commit|suspend.
1815
missing_keys = self.insert_stream_without_locking(stream,
1816
src_format, is_resume)
1818
# suspend the write group and tell the caller what we is
1819
# missing. We know we can suspend or else we would not have
1820
# entered this code path. (All repositories that can handle
1821
# missing keys can handle suspending a write group).
1822
write_group_tokens = self.target_repo.suspend_write_group()
1823
return write_group_tokens, missing_keys
1824
hint = self.target_repo.commit_write_group()
1825
to_serializer = self.target_repo._format._serializer
1826
src_serializer = src_format._serializer
1827
if (to_serializer != src_serializer
1828
and self.target_repo._format.pack_compresses):
1829
self.target_repo.pack(hint=hint)
1832
self.target_repo.abort_write_group(suppress_errors=True)
1835
def insert_stream_without_locking(self, stream, src_format,
1837
"""Insert a stream's content into the target repository.
1839
This assumes that you already have a locked repository and an active
1842
:param src_format: a bzr repository format.
1843
:param is_resume: Passed down to get_missing_parent_inventories to
1844
indicate if we should be checking for missing texts at the same
1847
:return: A set of keys that are missing.
1849
if not self.target_repo.is_write_locked():
1850
raise errors.ObjectNotLocked(self)
1851
if not self.target_repo.is_in_write_group():
1852
raise errors.BzrError('you must already be in a write group')
1853
to_serializer = self.target_repo._format._serializer
1854
src_serializer = src_format._serializer
1856
if to_serializer == src_serializer:
1857
# If serializers match and the target is a pack repository, set the
1858
# write cache size on the new pack. This avoids poor performance
1859
# on transports where append is unbuffered (such as
1860
# RemoteTransport). This is safe to do because nothing should read
1861
# back from the target repository while a stream with matching
1862
# serialization is being inserted.
1863
# The exception is that a delta record from the source that should
1864
# be a fulltext may need to be expanded by the target (see
1865
# test_fetch_revisions_with_deltas_into_pack); but we take care to
1866
# explicitly flush any buffered writes first in that rare case.
1868
new_pack = self.target_repo._pack_collection._new_pack
1869
except AttributeError:
1870
# Not a pack repository
1873
new_pack.set_write_cache_size(1024 * 1024)
1874
for substream_type, substream in stream:
1875
if 'stream' in debug.debug_flags:
1876
mutter('inserting substream: %s', substream_type)
1877
if substream_type == 'texts':
1878
self.target_repo.texts.insert_record_stream(substream)
1879
elif substream_type == 'inventories':
1880
if src_serializer == to_serializer:
1881
self.target_repo.inventories.insert_record_stream(
1884
self._extract_and_insert_inventories(
1885
substream, src_serializer)
1886
elif substream_type == 'inventory-deltas':
1887
self._extract_and_insert_inventory_deltas(
1888
substream, src_serializer)
1889
elif substream_type == 'chk_bytes':
1890
# XXX: This doesn't support conversions, as it assumes the
1891
# conversion was done in the fetch code.
1892
self.target_repo.chk_bytes.insert_record_stream(substream)
1893
elif substream_type == 'revisions':
1894
# This may fallback to extract-and-insert more often than
1895
# required if the serializers are different only in terms of
1897
if src_serializer == to_serializer:
1898
self.target_repo.revisions.insert_record_stream(substream)
1900
self._extract_and_insert_revisions(substream,
1902
elif substream_type == 'signatures':
1903
self.target_repo.signatures.insert_record_stream(substream)
1905
raise AssertionError('kaboom! %s' % (substream_type,))
1906
# Done inserting data, and the missing_keys calculations will try to
1907
# read back from the inserted data, so flush the writes to the new pack
1908
# (if this is pack format).
1909
if new_pack is not None:
1910
new_pack._write_data(b'', flush=True)
1911
# Find all the new revisions (including ones from resume_tokens)
1912
missing_keys = self.target_repo.get_missing_parent_inventories(
1913
check_for_missing_texts=is_resume)
1915
for prefix, versioned_file in (
1916
('texts', self.target_repo.texts),
1917
('inventories', self.target_repo.inventories),
1918
('revisions', self.target_repo.revisions),
1919
('signatures', self.target_repo.signatures),
1920
('chk_bytes', self.target_repo.chk_bytes),
1922
if versioned_file is None:
1924
# TODO: key is often going to be a StaticTuple object
1925
# I don't believe we can define a method by which
1926
# (prefix,) + StaticTuple will work, though we could
1927
# define a StaticTuple.sq_concat that would allow you to
1928
# pass in either a tuple or a StaticTuple as the second
1929
# object, so instead we could have:
1930
# StaticTuple(prefix) + key here...
1931
missing_keys.update((prefix,) + key for key in
1932
versioned_file.get_missing_compression_parent_keys())
1933
except NotImplementedError:
1934
# cannot even attempt suspending, and missing would have failed
1935
# during stream insertion.
1936
missing_keys = set()
1939
def _extract_and_insert_inventory_deltas(self, substream, serializer):
1940
target_rich_root = self.target_repo._format.rich_root_data
1941
target_tree_refs = self.target_repo._format.supports_tree_reference
1942
for record in substream:
1943
# Insert the delta directly
1944
inventory_delta_bytes = record.get_bytes_as('fulltext')
1945
deserialiser = inventory_delta.InventoryDeltaDeserializer()
1947
parse_result = deserialiser.parse_text_bytes(
1948
inventory_delta_bytes)
1949
except inventory_delta.IncompatibleInventoryDelta as err:
1950
mutter("Incompatible delta: %s", err.msg)
1951
raise errors.IncompatibleRevision(self.target_repo._format)
1952
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
1953
revision_id = new_id
1954
parents = [key[0] for key in record.parents]
1955
self.target_repo.add_inventory_by_delta(
1956
basis_id, inv_delta, revision_id, parents)
1958
def _extract_and_insert_inventories(self, substream, serializer,
1960
"""Generate a new inventory versionedfile in target, converting data.
1962
The inventory is retrieved from the source, (deserializing it), and
1963
stored in the target (reserializing it in a different format).
1965
target_rich_root = self.target_repo._format.rich_root_data
1966
target_tree_refs = self.target_repo._format.supports_tree_reference
1967
for record in substream:
1968
# It's not a delta, so it must be a fulltext in the source
1969
# serializer's format.
1970
bytes = record.get_bytes_as('fulltext')
1971
revision_id = record.key[0]
1972
inv = serializer.read_inventory_from_string(bytes, revision_id)
1973
parents = [key[0] for key in record.parents]
1974
self.target_repo.add_inventory(revision_id, inv, parents)
1975
# No need to keep holding this full inv in memory when the rest of
1976
# the substream is likely to be all deltas.
1979
def _extract_and_insert_revisions(self, substream, serializer):
1980
for record in substream:
1981
bytes = record.get_bytes_as('fulltext')
1982
revision_id = record.key[0]
1983
rev = serializer.read_revision_from_string(bytes)
1984
if rev.revision_id != revision_id:
1985
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
1986
self.target_repo.add_revision(revision_id, rev)
1989
if self.target_repo._format._fetch_reconcile:
1990
self.target_repo.reconcile()
1993
class StreamSource(object):
1994
"""A source of a stream for fetching between repositories."""
1996
def __init__(self, from_repository, to_format):
1997
"""Create a StreamSource streaming from from_repository."""
1998
self.from_repository = from_repository
1999
self.to_format = to_format
2000
self._record_counter = RecordCounter()
2002
def delta_on_metadata(self):
2003
"""Return True if delta's are permitted on metadata streams.
2005
That is on revisions and signatures.
2007
src_serializer = self.from_repository._format._serializer
2008
target_serializer = self.to_format._serializer
2009
return (self.to_format._fetch_uses_deltas
2010
and src_serializer == target_serializer)
2012
def _fetch_revision_texts(self, revs):
2013
# fetch signatures first and then the revision texts
2014
# may need to be a InterRevisionStore call here.
2015
from_sf = self.from_repository.signatures
2016
# A missing signature is just skipped.
2017
keys = [(rev_id,) for rev_id in revs]
2018
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2020
self.to_format._fetch_order,
2021
not self.to_format._fetch_uses_deltas))
2022
# If a revision has a delta, this is actually expanded inside the
2023
# insert_record_stream code now, which is an alternate fix for
2025
from_rf = self.from_repository.revisions
2026
revisions = from_rf.get_record_stream(
2028
self.to_format._fetch_order,
2029
not self.delta_on_metadata())
2030
return [('signatures', signatures), ('revisions', revisions)]
2032
def _generate_root_texts(self, revs):
2033
"""This will be called by get_stream between fetching weave texts and
2034
fetching the inventory weave.
2036
if self._rich_root_upgrade():
2037
return _mod_fetch.Inter1and2Helper(
2038
self.from_repository).generate_root_texts(revs)
2042
def get_stream(self, search):
2044
revs = search.get_keys()
2045
graph = self.from_repository.get_graph()
2046
revs = tsort.topo_sort(graph.get_parent_map(revs))
2047
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2049
for knit_kind, file_id, revisions in data_to_fetch:
2050
if knit_kind != phase:
2052
# Make a new progress bar for this phase
2053
if knit_kind == "file":
2054
# Accumulate file texts
2055
text_keys.extend([(file_id, revision) for revision in
2057
elif knit_kind == "inventory":
2058
# Now copy the file texts.
2059
from_texts = self.from_repository.texts
2060
yield ('texts', from_texts.get_record_stream(
2061
text_keys, self.to_format._fetch_order,
2062
not self.to_format._fetch_uses_deltas))
2063
# Cause an error if a text occurs after we have done the
2066
# Before we process the inventory we generate the root
2067
# texts (if necessary) so that the inventories references
2069
for _ in self._generate_root_texts(revs):
2071
# we fetch only the referenced inventories because we do not
2072
# know for unselected inventories whether all their required
2073
# texts are present in the other repository - it could be
2075
for info in self._get_inventory_stream(revs):
2077
elif knit_kind == "signatures":
2078
# Nothing to do here; this will be taken care of when
2079
# _fetch_revision_texts happens.
2081
elif knit_kind == "revisions":
2082
for record in self._fetch_revision_texts(revs):
2085
raise AssertionError("Unknown knit kind %r" % knit_kind)
2087
def get_stream_for_missing_keys(self, missing_keys):
2088
# missing keys can only occur when we are byte copying and not
2089
# translating (because translation means we don't send
2090
# unreconstructable deltas ever).
2092
keys['texts'] = set()
2093
keys['revisions'] = set()
2094
keys['inventories'] = set()
2095
keys['chk_bytes'] = set()
2096
keys['signatures'] = set()
2097
for key in missing_keys:
2098
keys[key[0]].add(key[1:])
2099
if len(keys['revisions']):
2100
# If we allowed copying revisions at this point, we could end up
2101
# copying a revision without copying its required texts: a
2102
# violation of the requirements for repository integrity.
2103
raise AssertionError(
2104
'cannot copy revisions to fill in missing deltas %s' % (
2105
keys['revisions'],))
2106
for substream_kind, keys in viewitems(keys):
2107
vf = getattr(self.from_repository, substream_kind)
2108
if vf is None and keys:
2109
raise AssertionError(
2110
"cannot fill in keys for a versioned file we don't"
2111
" have: %s needs %s" % (substream_kind, keys))
2113
# No need to stream something we don't have
2115
if substream_kind == 'inventories':
2116
# Some missing keys are genuinely ghosts, filter those out.
2117
present = self.from_repository.inventories.get_parent_map(keys)
2118
revs = [key[0] for key in present]
2119
# Get the inventory stream more-or-less as we do for the
2120
# original stream; there's no reason to assume that records
2121
# direct from the source will be suitable for the sink. (Think
2122
# e.g. 2a -> 1.9-rich-root).
2123
for info in self._get_inventory_stream(revs, missing=True):
2127
# Ask for full texts always so that we don't need more round trips
2128
# after this stream.
2129
# Some of the missing keys are genuinely ghosts, so filter absent
2130
# records. The Sink is responsible for doing another check to
2131
# ensure that ghosts don't introduce missing data for future
2133
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2134
self.to_format._fetch_order, True))
2135
yield substream_kind, stream
2137
def inventory_fetch_order(self):
2138
if self._rich_root_upgrade():
2139
return 'topological'
2141
return self.to_format._fetch_order
2143
def _rich_root_upgrade(self):
2144
return (not self.from_repository._format.rich_root_data
2145
and self.to_format.rich_root_data)
2147
def _get_inventory_stream(self, revision_ids, missing=False):
2148
from_format = self.from_repository._format
2149
if (from_format.supports_chks and self.to_format.supports_chks
2150
and from_format.network_name() == self.to_format.network_name()):
2151
raise AssertionError(
2152
"this case should be handled by GroupCHKStreamSource")
2153
elif 'forceinvdeltas' in debug.debug_flags:
2154
return self._get_convertable_inventory_stream(revision_ids,
2155
delta_versus_null=missing)
2156
elif from_format.network_name() == self.to_format.network_name():
2158
return self._get_simple_inventory_stream(revision_ids,
2160
elif (not from_format.supports_chks and not self.to_format.supports_chks and
2161
from_format._serializer == self.to_format._serializer):
2162
# Essentially the same format.
2163
return self._get_simple_inventory_stream(revision_ids,
2166
# Any time we switch serializations, we want to use an
2167
# inventory-delta based approach.
2168
return self._get_convertable_inventory_stream(revision_ids,
2169
delta_versus_null=missing)
2171
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2172
# NB: This currently reopens the inventory weave in source;
2173
# using a single stream interface instead would avoid this.
2174
from_weave = self.from_repository.inventories
2176
delta_closure = True
2178
delta_closure = not self.delta_on_metadata()
2179
yield ('inventories', from_weave.get_record_stream(
2180
[(rev_id,) for rev_id in revision_ids],
2181
self.inventory_fetch_order(), delta_closure))
2183
def _get_convertable_inventory_stream(self, revision_ids,
2184
delta_versus_null=False):
2185
# The two formats are sufficiently different that there is no fast
2186
# path, so we need to send just inventorydeltas, which any
2187
# sufficiently modern client can insert into any repository.
2188
# The StreamSink code expects to be able to
2189
# convert on the target, so we need to put bytes-on-the-wire that can
2190
# be converted. That means inventory deltas (if the remote is <1.19,
2191
# RemoteStreamSink will fallback to VFS to insert the deltas).
2192
yield ('inventory-deltas',
2193
self._stream_invs_as_deltas(revision_ids,
2194
delta_versus_null=delta_versus_null))
2196
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2197
"""Return a stream of inventory-deltas for the given rev ids.
2199
:param revision_ids: The list of inventories to transmit
2200
:param delta_versus_null: Don't try to find a minimal delta for this
2201
entry, instead compute the delta versus the NULL_REVISION. This
2202
effectively streams a complete inventory. Used for stuff like
2203
filling in missing parents, etc.
2205
from_repo = self.from_repository
2206
revision_keys = [(rev_id,) for rev_id in revision_ids]
2207
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2208
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2210
inventories = self.from_repository.iter_inventories(
2211
revision_ids, 'topological')
2212
format = from_repo._format
2213
invs_sent_so_far = {_mod_revision.NULL_REVISION}
2214
inventory_cache = lru_cache.LRUCache(50)
2215
null_inventory = from_repo.revision_tree(
2216
_mod_revision.NULL_REVISION).root_inventory
2217
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2218
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2219
# repo back into a non-rich-root repo ought to be allowed)
2220
serializer = inventory_delta.InventoryDeltaSerializer(
2221
versioned_root=format.rich_root_data,
2222
tree_references=format.supports_tree_reference)
2223
for inv in inventories:
2224
key = (inv.revision_id,)
2225
parent_keys = parent_map.get(key, ())
2227
if not delta_versus_null and parent_keys:
2228
# The caller did not ask for complete inventories and we have
2229
# some parents that we can delta against. Make a delta against
2230
# each parent so that we can find the smallest.
2231
parent_ids = [parent_key[0] for parent_key in parent_keys]
2232
for parent_id in parent_ids:
2233
if parent_id not in invs_sent_so_far:
2234
# We don't know that the remote side has this basis, so
2237
if parent_id == _mod_revision.NULL_REVISION:
2238
parent_inv = null_inventory
2240
parent_inv = inventory_cache.get(parent_id, None)
2241
if parent_inv is None:
2242
parent_inv = from_repo.get_inventory(parent_id)
2243
candidate_delta = inv._make_delta(parent_inv)
2245
or len(delta) > len(candidate_delta)):
2246
delta = candidate_delta
2247
basis_id = parent_id
2249
# Either none of the parents ended up being suitable, or we
2250
# were asked to delta against NULL
2251
basis_id = _mod_revision.NULL_REVISION
2252
delta = inv._make_delta(null_inventory)
2253
invs_sent_so_far.add(inv.revision_id)
2254
inventory_cache[inv.revision_id] = inv
2255
delta_serialized = b''.join(
2256
serializer.delta_to_lines(basis_id, key[-1], delta))
2257
yield versionedfile.FulltextContentFactory(
2258
key, parent_keys, None, delta_serialized)
2261
class _VersionedFileChecker(object):
2263
def __init__(self, repository, text_key_references=None, ancestors=None):
2264
self.repository = repository
2265
self.text_index = self.repository._generate_text_key_index(
2266
text_key_references=text_key_references, ancestors=ancestors)
2268
def calculate_file_version_parents(self, text_key):
2269
"""Calculate the correct parents for a file version according to
2272
parent_keys = self.text_index[text_key]
2273
if parent_keys == [_mod_revision.NULL_REVISION]:
2275
return tuple(parent_keys)
2277
def check_file_version_parents(self, texts, progress_bar=None):
2278
"""Check the parents stored in a versioned file are correct.
2280
It also detects file versions that are not referenced by their
2281
corresponding revision's inventory.
2283
:returns: A tuple of (wrong_parents, dangling_file_versions).
2284
wrong_parents is a dict mapping {revision_id: (stored_parents,
2285
correct_parents)} for each revision_id where the stored parents
2286
are not correct. dangling_file_versions is a set of (file_id,
2287
revision_id) tuples for versions that are present in this versioned
2288
file, but not used by the corresponding inventory.
2290
local_progress = None
2291
if progress_bar is None:
2292
local_progress = ui.ui_factory.nested_progress_bar()
2293
progress_bar = local_progress
2295
return self._check_file_version_parents(texts, progress_bar)
2298
local_progress.finished()
2300
def _check_file_version_parents(self, texts, progress_bar):
2301
"""See check_file_version_parents."""
2303
self.file_ids = {file_id for file_id, _ in self.text_index}
2304
# text keys is now grouped by file_id
2305
n_versions = len(self.text_index)
2306
progress_bar.update(gettext('loading text store'), 0, n_versions)
2307
parent_map = self.repository.texts.get_parent_map(self.text_index)
2308
# On unlistable transports this could well be empty/error...
2309
text_keys = self.repository.texts.keys()
2310
unused_keys = frozenset(text_keys) - set(self.text_index)
2311
for num, key in enumerate(self.text_index):
2312
progress_bar.update(
2313
gettext('checking text graph'), num, n_versions)
2314
correct_parents = self.calculate_file_version_parents(key)
2316
knit_parents = parent_map[key]
2317
except errors.RevisionNotPresent:
2320
if correct_parents != knit_parents:
2321
wrong_parents[key] = (knit_parents, correct_parents)
2322
return wrong_parents, unused_keys
2325
class InterVersionedFileRepository(InterRepository):
2327
_walk_to_common_revisions_batch_size = 50
2329
supports_fetch_spec = True
2331
def fetch(self, revision_id=None, find_ghosts=False,
2333
"""Fetch the content required to construct revision_id.
2335
The content is copied from self.source to self.target.
2337
:param revision_id: if None all content is copied, if NULL_REVISION no
2341
if self.target._format.experimental:
2342
ui.ui_factory.show_user_warning(
2343
'experimental_format_fetch',
2344
from_format=self.source._format,
2345
to_format=self.target._format)
2346
from breezy.bzr.fetch import RepoFetcher
2347
# See <https://launchpad.net/bugs/456077> asking for a warning here
2348
if self.source._format.network_name() != self.target._format.network_name():
2349
ui.ui_factory.show_user_warning(
2350
'cross_format_fetch', from_format=self.source._format,
2351
to_format=self.target._format)
2352
with self.lock_write():
2353
f = RepoFetcher(to_repository=self.target,
2354
from_repository=self.source,
2355
last_revision=revision_id,
2356
fetch_spec=fetch_spec,
2357
find_ghosts=find_ghosts)
2359
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2360
"""Walk out from revision_ids in source to revisions target has.
2362
:param revision_ids: The start point for the search.
2363
:return: A set of revision ids.
2365
target_graph = self.target.get_graph()
2366
revision_ids = frozenset(revision_ids)
2368
all_wanted_revs = revision_ids.union(if_present_ids)
2370
all_wanted_revs = revision_ids
2371
missing_revs = set()
2372
source_graph = self.source.get_graph()
2373
# ensure we don't pay silly lookup costs.
2374
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2375
null_set = frozenset([_mod_revision.NULL_REVISION])
2376
searcher_exhausted = False
2380
# Iterate the searcher until we have enough next_revs
2381
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2383
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2384
next_revs.update(next_revs_part)
2385
ghosts.update(ghosts_part)
2386
except StopIteration:
2387
searcher_exhausted = True
2389
# If there are ghosts in the source graph, and the caller asked for
2390
# them, make sure that they are present in the target.
2391
# We don't care about other ghosts as we can't fetch them and
2392
# haven't been asked to.
2393
ghosts_to_check = set(revision_ids.intersection(ghosts))
2394
revs_to_get = set(next_revs).union(ghosts_to_check)
2396
have_revs = set(target_graph.get_parent_map(revs_to_get))
2397
# we always have NULL_REVISION present.
2398
have_revs = have_revs.union(null_set)
2399
# Check if the target is missing any ghosts we need.
2400
ghosts_to_check.difference_update(have_revs)
2402
# One of the caller's revision_ids is a ghost in both the
2403
# source and the target.
2404
raise errors.NoSuchRevision(
2405
self.source, ghosts_to_check.pop())
2406
missing_revs.update(next_revs - have_revs)
2407
# Because we may have walked past the original stop point, make
2408
# sure everything is stopped
2409
stop_revs = searcher.find_seen_ancestors(have_revs)
2410
searcher.stop_searching_any(stop_revs)
2411
if searcher_exhausted:
2413
(started_keys, excludes, included_keys) = searcher.get_state()
2414
return vf_search.SearchResult(started_keys, excludes,
2415
len(included_keys), included_keys)
2417
def search_missing_revision_ids(self,
2418
find_ghosts=True, revision_ids=None, if_present_ids=None,
2420
"""Return the revision ids that source has that target does not.
2422
:param revision_ids: return revision ids included by these
2423
revision_ids. NoSuchRevision will be raised if any of these
2424
revisions are not present.
2425
:param if_present_ids: like revision_ids, but will not cause
2426
NoSuchRevision if any of these are absent, instead they will simply
2427
not be in the result. This is useful for e.g. finding revisions
2428
to fetch for tags, which may reference absent revisions.
2429
:param find_ghosts: If True find missing revisions in deep history
2430
rather than just finding the surface difference.
2431
:return: A breezy.graph.SearchResult.
2433
with self.lock_read():
2434
# stop searching at found target revisions.
2435
if not find_ghosts and (revision_ids is not None or if_present_ids is
2437
result = self._walk_to_common_revisions(revision_ids,
2438
if_present_ids=if_present_ids)
2441
result_set = result.get_keys()
2443
# generic, possibly worst case, slow code path.
2444
target_ids = set(self.target.all_revision_ids())
2445
source_ids = self._present_source_revisions_for(
2446
revision_ids, if_present_ids)
2447
result_set = set(source_ids).difference(target_ids)
2448
if limit is not None:
2449
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2450
result_set = set(itertools.islice(topo_ordered, limit))
2451
return self.source.revision_ids_to_search_result(result_set)
2453
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2454
"""Returns set of all revisions in ancestry of revision_ids present in
2457
:param revision_ids: if None, all revisions in source are returned.
2458
:param if_present_ids: like revision_ids, but if any/all of these are
2459
absent no error is raised.
2461
if revision_ids is not None or if_present_ids is not None:
2462
# First, ensure all specified revisions exist. Callers expect
2463
# NoSuchRevision when they pass absent revision_ids here.
2464
if revision_ids is None:
2465
revision_ids = set()
2466
if if_present_ids is None:
2467
if_present_ids = set()
2468
revision_ids = set(revision_ids)
2469
if_present_ids = set(if_present_ids)
2470
all_wanted_ids = revision_ids.union(if_present_ids)
2471
graph = self.source.get_graph()
2472
present_revs = set(graph.get_parent_map(all_wanted_ids))
2473
missing = revision_ids.difference(present_revs)
2475
raise errors.NoSuchRevision(self.source, missing.pop())
2476
found_ids = all_wanted_ids.intersection(present_revs)
2477
source_ids = [rev_id for (rev_id, parents) in
2478
graph.iter_ancestry(found_ids)
2479
if rev_id != _mod_revision.NULL_REVISION and
2480
parents is not None]
2482
source_ids = self.source.all_revision_ids()
2483
return set(source_ids)
2486
def _get_repo_format_to_test(self):
2490
def is_compatible(cls, source, target):
2491
# The default implementation is compatible with everything
2492
return (source._format.supports_full_versioned_files
2493
and target._format.supports_full_versioned_files)
2496
class InterDifferingSerializer(InterVersionedFileRepository):
2499
def _get_repo_format_to_test(self):
2503
def is_compatible(source, target):
2504
if not source._format.supports_full_versioned_files:
2506
if not target._format.supports_full_versioned_files:
2508
# This is redundant with format.check_conversion_target(), however that
2509
# raises an exception, and we just want to say "False" as in we won't
2510
# support converting between these formats.
2511
if 'IDS_never' in debug.debug_flags:
2513
if source.supports_rich_root() and not target.supports_rich_root():
2515
if (source._format.supports_tree_reference and
2516
not target._format.supports_tree_reference):
2518
if target._fallback_repositories and target._format.supports_chks:
2519
# IDS doesn't know how to copy CHKs for the parent inventories it
2520
# adds to stacked repos.
2522
if 'IDS_always' in debug.debug_flags:
2524
# Only use this code path for local source and target. IDS does far
2525
# too much IO (both bandwidth and roundtrips) over a network.
2526
if not source.controldir.transport.base.startswith('file:///'):
2528
if not target.controldir.transport.base.startswith('file:///'):
2532
def _get_trees(self, revision_ids, cache):
2534
for rev_id in revision_ids:
2536
possible_trees.append((rev_id, cache[rev_id]))
2538
# Not cached, but inventory might be present anyway.
2540
tree = self.source.revision_tree(rev_id)
2541
except errors.NoSuchRevision:
2542
# Nope, parent is ghost.
2545
cache[rev_id] = tree
2546
possible_trees.append((rev_id, tree))
2547
return possible_trees
2549
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2550
"""Get the best delta and base for this revision.
2552
:return: (basis_id, delta)
2555
# Generate deltas against each tree, to find the shortest.
2556
# FIXME: Support nested trees
2557
texts_possibly_new_in_tree = set()
2558
for basis_id, basis_tree in possible_trees:
2559
delta = tree.root_inventory._make_delta(basis_tree.root_inventory)
2560
for old_path, new_path, file_id, new_entry in delta:
2561
if new_path is None:
2562
# This file_id isn't present in the new rev, so we don't
2566
# Rich roots are handled elsewhere...
2568
kind = new_entry.kind
2569
if kind != 'directory' and kind != 'file':
2570
# No text record associated with this inventory entry.
2572
# This is a directory or file that has changed somehow.
2573
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2574
deltas.append((len(delta), basis_id, delta))
2576
return deltas[0][1:]
2578
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2579
"""Find all parent revisions that are absent, but for which the
2580
inventory is present, and copy those inventories.
2582
This is necessary to preserve correctness when the source is stacked
2583
without fallbacks configured. (Note that in cases like upgrade the
2584
source may be not have _fallback_repositories even though it is
2587
parent_revs = set(itertools.chain.from_iterable(viewvalues(
2589
present_parents = self.source.get_parent_map(parent_revs)
2590
absent_parents = parent_revs.difference(present_parents)
2591
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2592
(rev_id,) for rev_id in absent_parents)
2593
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2594
for parent_tree in self.source.revision_trees(parent_inv_ids):
2595
current_revision_id = parent_tree.get_revision_id()
2596
parents_parents_keys = parent_invs_keys_for_stacking[
2597
(current_revision_id,)]
2598
parents_parents = [key[-1] for key in parents_parents_keys]
2599
basis_id = _mod_revision.NULL_REVISION
2600
basis_tree = self.source.revision_tree(basis_id)
2601
delta = parent_tree.root_inventory._make_delta(
2602
basis_tree.root_inventory)
2603
self.target.add_inventory_by_delta(
2604
basis_id, delta, current_revision_id, parents_parents)
2605
cache[current_revision_id] = parent_tree
2607
def _fetch_batch(self, revision_ids, basis_id, cache):
2608
"""Fetch across a few revisions.
2610
:param revision_ids: The revisions to copy
2611
:param basis_id: The revision_id of a tree that must be in cache, used
2612
as a basis for delta when no other base is available
2613
:param cache: A cache of RevisionTrees that we can use.
2614
:return: The revision_id of the last converted tree. The RevisionTree
2615
for it will be in cache
2617
# Walk though all revisions; get inventory deltas, copy referenced
2618
# texts that delta references, insert the delta, revision and
2620
root_keys_to_create = set()
2623
pending_revisions = []
2624
parent_map = self.source.get_parent_map(revision_ids)
2625
self._fetch_parent_invs_for_stacking(parent_map, cache)
2626
self.source._safe_to_return_from_cache = True
2627
for tree in self.source.revision_trees(revision_ids):
2628
# Find a inventory delta for this revision.
2629
# Find text entries that need to be copied, too.
2630
current_revision_id = tree.get_revision_id()
2631
parent_ids = parent_map.get(current_revision_id, ())
2632
parent_trees = self._get_trees(parent_ids, cache)
2633
possible_trees = list(parent_trees)
2634
if len(possible_trees) == 0:
2635
# There either aren't any parents, or the parents are ghosts,
2636
# so just use the last converted tree.
2637
possible_trees.append((basis_id, cache[basis_id]))
2638
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2640
revision = self.source.get_revision(current_revision_id)
2641
pending_deltas.append((basis_id, delta,
2642
current_revision_id, revision.parent_ids))
2643
if self._converting_to_rich_root:
2644
self._revision_id_to_root_id[current_revision_id] = \
2646
# Determine which texts are in present in this revision but not in
2647
# any of the available parents.
2648
texts_possibly_new_in_tree = set()
2649
for old_path, new_path, file_id, entry in delta:
2650
if new_path is None:
2651
# This file_id isn't present in the new rev
2655
if not self.target.supports_rich_root():
2656
# The target doesn't support rich root, so we don't
2659
if self._converting_to_rich_root:
2660
# This can't be copied normally, we have to insert
2662
root_keys_to_create.add((file_id, entry.revision))
2665
texts_possibly_new_in_tree.add((file_id, entry.revision))
2666
for basis_id, basis_tree in possible_trees:
2667
basis_inv = basis_tree.root_inventory
2668
for file_key in list(texts_possibly_new_in_tree):
2669
file_id, file_revision = file_key
2671
entry = basis_inv.get_entry(file_id)
2672
except errors.NoSuchId:
2674
if entry.revision == file_revision:
2675
texts_possibly_new_in_tree.remove(file_key)
2676
text_keys.update(texts_possibly_new_in_tree)
2677
pending_revisions.append(revision)
2678
cache[current_revision_id] = tree
2679
basis_id = current_revision_id
2680
self.source._safe_to_return_from_cache = False
2682
from_texts = self.source.texts
2683
to_texts = self.target.texts
2684
if root_keys_to_create:
2685
root_stream = _mod_fetch._new_root_data_stream(
2686
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2688
to_texts.insert_record_stream(root_stream)
2689
to_texts.insert_record_stream(from_texts.get_record_stream(
2690
text_keys, self.target._format._fetch_order,
2691
not self.target._format._fetch_uses_deltas))
2692
# insert inventory deltas
2693
for delta in pending_deltas:
2694
self.target.add_inventory_by_delta(*delta)
2695
if self.target._fallback_repositories:
2696
# Make sure this stacked repository has all the parent inventories
2697
# for the new revisions that we are about to insert. We do this
2698
# before adding the revisions so that no revision is added until
2699
# all the inventories it may depend on are added.
2700
# Note that this is overzealous, as we may have fetched these in an
2703
revision_ids = set()
2704
for revision in pending_revisions:
2705
revision_ids.add(revision.revision_id)
2706
parent_ids.update(revision.parent_ids)
2707
parent_ids.difference_update(revision_ids)
2708
parent_ids.discard(_mod_revision.NULL_REVISION)
2709
parent_map = self.source.get_parent_map(parent_ids)
2710
# we iterate over parent_map and not parent_ids because we don't
2711
# want to try copying any revision which is a ghost
2712
for parent_tree in self.source.revision_trees(parent_map):
2713
current_revision_id = parent_tree.get_revision_id()
2714
parents_parents = parent_map[current_revision_id]
2715
possible_trees = self._get_trees(parents_parents, cache)
2716
if len(possible_trees) == 0:
2717
# There either aren't any parents, or the parents are
2718
# ghosts, so just use the last converted tree.
2719
possible_trees.append((basis_id, cache[basis_id]))
2720
basis_id, delta = self._get_delta_for_revision(parent_tree,
2721
parents_parents, possible_trees)
2722
self.target.add_inventory_by_delta(
2723
basis_id, delta, current_revision_id, parents_parents)
2724
# insert signatures and revisions
2725
for revision in pending_revisions:
2727
signature = self.source.get_signature_text(
2728
revision.revision_id)
2729
self.target.add_signature_text(revision.revision_id,
2731
except errors.NoSuchRevision:
2733
self.target.add_revision(revision.revision_id, revision)
2736
def _fetch_all_revisions(self, revision_ids, pb):
2737
"""Fetch everything for the list of revisions.
2739
:param revision_ids: The list of revisions to fetch. Must be in
2741
:param pb: A ProgressTask
2744
basis_id, basis_tree = self._get_basis(revision_ids[0])
2746
cache = lru_cache.LRUCache(100)
2747
cache[basis_id] = basis_tree
2748
del basis_tree # We don't want to hang on to it here
2752
for offset in range(0, len(revision_ids), batch_size):
2753
self.target.start_write_group()
2755
pb.update(gettext('Transferring revisions'), offset,
2757
batch = revision_ids[offset:offset + batch_size]
2758
basis_id = self._fetch_batch(batch, basis_id, cache)
2760
self.source._safe_to_return_from_cache = False
2761
self.target.abort_write_group()
2764
hint = self.target.commit_write_group()
2767
if hints and self.target._format.pack_compresses:
2768
self.target.pack(hint=hints)
2769
pb.update(gettext('Transferring revisions'), len(revision_ids),
2772
def fetch(self, revision_id=None, find_ghosts=False,
2774
"""See InterRepository.fetch()."""
2775
if fetch_spec is not None:
2776
revision_ids = fetch_spec.get_keys()
2779
if self.source._format.experimental:
2780
ui.ui_factory.show_user_warning('experimental_format_fetch',
2781
from_format=self.source._format,
2782
to_format=self.target._format)
2783
if (not self.source.supports_rich_root() and
2784
self.target.supports_rich_root()):
2785
self._converting_to_rich_root = True
2786
self._revision_id_to_root_id = {}
2788
self._converting_to_rich_root = False
2789
# See <https://launchpad.net/bugs/456077> asking for a warning here
2790
if self.source._format.network_name() != self.target._format.network_name():
2791
ui.ui_factory.show_user_warning('cross_format_fetch',
2792
from_format=self.source._format,
2793
to_format=self.target._format)
2794
with self.lock_write():
2795
if revision_ids is None:
2797
search_revision_ids = [revision_id]
2799
search_revision_ids = None
2800
revision_ids = self.target.search_missing_revision_ids(self.source,
2801
revision_ids=search_revision_ids,
2802
find_ghosts=find_ghosts).get_keys()
2803
if not revision_ids:
2805
revision_ids = tsort.topo_sort(
2806
self.source.get_graph().get_parent_map(revision_ids))
2807
if not revision_ids:
2809
# Walk though all revisions; get inventory deltas, copy referenced
2810
# texts that delta references, insert the delta, revision and
2812
with ui.ui_factory.nested_progress_bar() as pb:
2813
self._fetch_all_revisions(revision_ids, pb)
2814
return len(revision_ids), 0
2816
def _get_basis(self, first_revision_id):
2817
"""Get a revision and tree which exists in the target.
2819
This assumes that first_revision_id is selected for transmission
2820
because all other ancestors are already present. If we can't find an
2821
ancestor we fall back to NULL_REVISION since we know that is safe.
2823
:return: (basis_id, basis_tree)
2825
first_rev = self.source.get_revision(first_revision_id)
2827
basis_id = first_rev.parent_ids[0]
2828
# only valid as a basis if the target has it
2829
self.target.get_revision(basis_id)
2830
# Try to get a basis tree - if it's a ghost it will hit the
2831
# NoSuchRevision case.
2832
basis_tree = self.source.revision_tree(basis_id)
2833
except (IndexError, errors.NoSuchRevision):
2834
basis_id = _mod_revision.NULL_REVISION
2835
basis_tree = self.source.revision_tree(basis_id)
2836
return basis_id, basis_tree
2839
class InterSameDataRepository(InterVersionedFileRepository):
2840
"""Code for converting between repositories that represent the same data.
2842
Data format and model must match for this to work.
2846
def _get_repo_format_to_test(self):
2847
"""Repository format for testing with.
2849
InterSameData can pull from subtree to subtree and from non-subtree to
2850
non-subtree, so we test this with the richest repository format.
2852
from breezy.bzr import knitrepo
2853
return knitrepo.RepositoryFormatKnit3()
2856
def is_compatible(source, target):
2858
InterRepository._same_model(source, target)
2859
and source._format.supports_full_versioned_files
2860
and target._format.supports_full_versioned_files)
2863
InterRepository.register_optimiser(InterVersionedFileRepository)
2864
InterRepository.register_optimiser(InterDifferingSerializer)
2865
InterRepository.register_optimiser(InterSameDataRepository)
2868
def install_revisions(repository, iterable, num_revisions=None, pb=None):
2869
"""Install all revision data into a repository.
2871
Accepts an iterable of revision, tree, signature tuples. The signature
2874
with WriteGroup(repository):
2875
inventory_cache = lru_cache.LRUCache(10)
2876
for n, (revision, revision_tree, signature) in enumerate(iterable):
2877
_install_revision(repository, revision, revision_tree, signature,
2880
pb.update(gettext('Transferring revisions'),
2881
n + 1, num_revisions)
2884
def _install_revision(repository, rev, revision_tree, signature,
2886
"""Install all revision data into a repository."""
2887
present_parents = []
2889
for p_id in rev.parent_ids:
2890
if repository.has_revision(p_id):
2891
present_parents.append(p_id)
2892
parent_trees[p_id] = repository.revision_tree(p_id)
2894
parent_trees[p_id] = repository.revision_tree(
2895
_mod_revision.NULL_REVISION)
2897
# FIXME: Support nested trees
2898
inv = revision_tree.root_inventory
2899
entries = inv.iter_entries()
2900
# backwards compatibility hack: skip the root id.
2901
if not repository.supports_rich_root():
2902
path, root = next(entries)
2903
if root.revision != rev.revision_id:
2904
raise errors.IncompatibleRevision(repr(repository))
2906
for path, ie in entries:
2907
text_keys[(ie.file_id, ie.revision)] = ie
2908
text_parent_map = repository.texts.get_parent_map(text_keys)
2909
missing_texts = set(text_keys) - set(text_parent_map)
2910
# Add the texts that are not already present
2911
for text_key in missing_texts:
2912
ie = text_keys[text_key]
2914
# FIXME: TODO: The following loop overlaps/duplicates that done by
2915
# commit to determine parents. There is a latent/real bug here where
2916
# the parents inserted are not those commit would do - in particular
2917
# they are not filtered by heads(). RBC, AB
2918
for revision, tree in viewitems(parent_trees):
2920
path = tree.id2path(ie.file_id)
2921
except errors.NoSuchId:
2923
parent_id = tree.get_file_revision(path)
2924
if parent_id in text_parents:
2926
text_parents.append((ie.file_id, parent_id))
2927
revision_tree_path = revision_tree.id2path(ie.file_id)
2928
with revision_tree.get_file(revision_tree_path) as f:
2929
lines = f.readlines()
2930
repository.texts.add_lines(text_key, text_parents, lines)
2932
# install the inventory
2933
if repository._format._commit_inv_deltas and len(rev.parent_ids):
2934
# Cache this inventory
2935
inventory_cache[rev.revision_id] = inv
2937
basis_inv = inventory_cache[rev.parent_ids[0]]
2939
repository.add_inventory(rev.revision_id, inv, present_parents)
2941
delta = inv._make_delta(basis_inv)
2942
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
2943
rev.revision_id, present_parents)
2945
repository.add_inventory(rev.revision_id, inv, present_parents)
2946
except errors.RevisionAlreadyPresent:
2948
if signature is not None:
2949
repository.add_signature_text(rev.revision_id, signature)
2950
repository.add_revision(rev.revision_id, rev, inv)
2953
def install_revision(repository, rev, revision_tree):
2954
"""Install all revision data into a repository."""
2955
install_revisions(repository, [(rev, revision_tree, None)])