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."""
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
34
revision as _mod_revision,
35
serializer as _mod_serializer,
43
from bzrlib.recordcounter import RecordCounter
44
from bzrlib.revisiontree import InventoryRevisionTree
45
from bzrlib.testament import Testament
46
from bzrlib.i18n import gettext
52
from bzrlib.decorators import (
57
from bzrlib.inventory import (
64
from bzrlib.repository import (
68
MetaDirRepositoryFormat,
73
from bzrlib.trace import (
78
class VersionedFileRepositoryFormat(RepositoryFormat):
79
"""Base class for all repository formats that are VersionedFiles-based."""
81
supports_full_versioned_files = True
82
supports_versioned_directories = True
83
supports_unreferenced_revisions = True
85
# Should commit add an inventory, or an inventory delta to the repository.
86
_commit_inv_deltas = True
87
# What order should fetch operations request streams in?
88
# The default is unordered as that is the cheapest for an origin to
90
_fetch_order = 'unordered'
91
# Does this repository format use deltas that can be fetched as-deltas ?
92
# (E.g. knits, where the knit deltas can be transplanted intact.
93
# We default to False, which will ensure that enough data to get
94
# a full text out of any fetch stream will be grabbed.
95
_fetch_uses_deltas = False
98
class VersionedFileCommitBuilder(CommitBuilder):
99
"""Commit builder implementation for versioned files based repositories.
102
# this commit builder supports the record_entry_contents interface
103
supports_record_entry_contents = True
105
# the default CommitBuilder does not manage trees whose root is versioned.
106
_versioned_root = False
108
def __init__(self, repository, parents, config, timestamp=None,
109
timezone=None, committer=None, revprops=None,
110
revision_id=None, lossy=False):
111
super(VersionedFileCommitBuilder, self).__init__(repository,
112
parents, config, timestamp, timezone, committer, revprops,
115
basis_id = self.parents[0]
117
basis_id = _mod_revision.NULL_REVISION
118
self.basis_delta_revision = basis_id
119
self.new_inventory = Inventory(None)
120
self._basis_delta = []
121
self.__heads = graph.HeadsCache(repository.get_graph()).heads
122
# memo'd check for no-op commits.
123
self._any_changes = False
124
# API compatibility, older code that used CommitBuilder did not call
125
# .record_delete(), which means the delta that is computed would not be
126
# valid. Callers that will call record_delete() should call
127
# .will_record_deletes() to indicate that.
128
self._recording_deletes = False
130
def will_record_deletes(self):
131
"""Tell the commit builder that deletes are being notified.
133
This enables the accumulation of an inventory delta; for the resulting
134
commit to be valid, deletes against the basis MUST be recorded via
135
builder.record_delete().
137
self._recording_deletes = True
139
def any_changes(self):
140
"""Return True if any entries were changed.
142
This includes merge-only changes. It is the core for the --unchanged
145
:return: True if any changes have occured.
147
return self._any_changes
149
def _ensure_fallback_inventories(self):
150
"""Ensure that appropriate inventories are available.
152
This only applies to repositories that are stacked, and is about
153
enusring the stacking invariants. Namely, that for any revision that is
154
present, we either have all of the file content, or we have the parent
155
inventory and the delta file content.
157
if not self.repository._fallback_repositories:
159
if not self.repository._format.supports_chks:
160
raise errors.BzrError("Cannot commit directly to a stacked branch"
161
" in pre-2a formats. See "
162
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
163
# This is a stacked repo, we need to make sure we have the parent
164
# inventories for the parents.
165
parent_keys = [(p,) for p in self.parents]
166
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
167
missing_parent_keys = set([pk for pk in parent_keys
168
if pk not in parent_map])
169
fallback_repos = list(reversed(self.repository._fallback_repositories))
170
missing_keys = [('inventories', pk[0])
171
for pk in missing_parent_keys]
173
while missing_keys and fallback_repos:
174
fallback_repo = fallback_repos.pop()
175
source = fallback_repo._get_source(self.repository._format)
176
sink = self.repository._get_sink()
177
stream = source.get_stream_for_missing_keys(missing_keys)
178
missing_keys = sink.insert_stream_without_locking(stream,
179
self.repository._format)
181
raise errors.BzrError('Unable to fill in parent inventories for a'
184
def commit(self, message):
185
"""Make the actual commit.
187
:return: The revision id of the recorded revision.
189
self._validate_unicode_text(message, 'commit message')
190
rev = _mod_revision.Revision(
191
timestamp=self._timestamp,
192
timezone=self._timezone,
193
committer=self._committer,
195
inventory_sha1=self.inv_sha1,
196
revision_id=self._new_revision_id,
197
properties=self._revprops)
198
rev.parent_ids = self.parents
199
self.repository.add_revision(self._new_revision_id, rev,
200
self.new_inventory, self._config)
201
self._ensure_fallback_inventories()
202
self.repository.commit_write_group()
203
return self._new_revision_id
206
"""Abort the commit that is being built.
208
self.repository.abort_write_group()
210
def revision_tree(self):
211
"""Return the tree that was just committed.
213
After calling commit() this can be called to get a
214
RevisionTree representing the newly committed tree. This is
215
preferred to calling Repository.revision_tree() because that may
216
require deserializing the inventory, while we already have a copy in
219
if self.new_inventory is None:
220
self.new_inventory = self.repository.get_inventory(
221
self._new_revision_id)
222
return InventoryRevisionTree(self.repository, self.new_inventory,
223
self._new_revision_id)
225
def finish_inventory(self):
226
"""Tell the builder that the inventory is finished.
228
:return: The inventory id in the repository, which can be used with
229
repository.get_inventory.
231
if self.new_inventory is None:
232
# an inventory delta was accumulated without creating a new
234
basis_id = self.basis_delta_revision
235
# We ignore the 'inventory' returned by add_inventory_by_delta
236
# because self.new_inventory is used to hint to the rest of the
237
# system what code path was taken
238
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
239
basis_id, self._basis_delta, self._new_revision_id,
242
if self.new_inventory.root is None:
243
raise AssertionError('Root entry should be supplied to'
244
' record_entry_contents, as of bzr 0.10.')
245
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
246
self.new_inventory.revision_id = self._new_revision_id
247
self.inv_sha1 = self.repository.add_inventory(
248
self._new_revision_id,
252
return self._new_revision_id
254
def _check_root(self, ie, parent_invs, tree):
255
"""Helper for record_entry_contents.
257
:param ie: An entry being added.
258
:param parent_invs: The inventories of the parent revisions of the
260
:param tree: The tree that is being committed.
262
# In this revision format, root entries have no knit or weave When
263
# serializing out to disk and back in root.revision is always
265
ie.revision = self._new_revision_id
267
def _require_root_change(self, tree):
268
"""Enforce an appropriate root object change.
270
This is called once when record_iter_changes is called, if and only if
271
the root was not in the delta calculated by record_iter_changes.
273
:param tree: The tree which is being committed.
275
if len(self.parents) == 0:
276
raise errors.RootMissing()
277
entry = entry_factory['directory'](tree.path2id(''), '',
279
entry.revision = self._new_revision_id
280
self._basis_delta.append(('', '', entry.file_id, entry))
282
def _get_delta(self, ie, basis_inv, path):
283
"""Get a delta against the basis inventory for ie."""
284
if not basis_inv.has_id(ie.file_id):
286
result = (None, path, ie.file_id, ie)
287
self._basis_delta.append(result)
289
elif ie != basis_inv[ie.file_id]:
291
# TODO: avoid tis id2path call.
292
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
293
self._basis_delta.append(result)
299
def _heads(self, file_id, revision_ids):
300
"""Calculate the graph heads for revision_ids in the graph of file_id.
302
This can use either a per-file graph or a global revision graph as we
303
have an identity relationship between the two graphs.
305
return self.__heads(revision_ids)
307
def get_basis_delta(self):
308
"""Return the complete inventory delta versus the basis inventory.
310
This has been built up with the calls to record_delete and
311
record_entry_contents. The client must have already called
312
will_record_deletes() to indicate that they will be generating a
315
:return: An inventory delta, suitable for use with apply_delta, or
316
Repository.add_inventory_by_delta, etc.
318
if not self._recording_deletes:
319
raise AssertionError("recording deletes not activated.")
320
return self._basis_delta
322
def record_delete(self, path, file_id):
323
"""Record that a delete occured against a basis tree.
325
This is an optional API - when used it adds items to the basis_delta
326
being accumulated by the commit builder. It cannot be called unless the
327
method will_record_deletes() has been called to inform the builder that
328
a delta is being supplied.
330
:param path: The path of the thing deleted.
331
:param file_id: The file id that was deleted.
333
if not self._recording_deletes:
334
raise AssertionError("recording deletes not activated.")
335
delta = (path, None, file_id, None)
336
self._basis_delta.append(delta)
337
self._any_changes = True
340
def record_entry_contents(self, ie, parent_invs, path, tree,
342
"""Record the content of ie from tree into the commit if needed.
344
Side effect: sets ie.revision when unchanged
346
:param ie: An inventory entry present in the commit.
347
:param parent_invs: The inventories of the parent revisions of the
349
:param path: The path the entry is at in the tree.
350
:param tree: The tree which contains this entry and should be used to
352
:param content_summary: Summary data from the tree about the paths
353
content - stat, length, exec, sha/link target. This is only
354
accessed when the entry has a revision of None - that is when it is
355
a candidate to commit.
356
:return: A tuple (change_delta, version_recorded, fs_hash).
357
change_delta is an inventory_delta change for this entry against
358
the basis tree of the commit, or None if no change occured against
360
version_recorded is True if a new version of the entry has been
361
recorded. For instance, committing a merge where a file was only
362
changed on the other side will return (delta, False).
363
fs_hash is either None, or the hash details for the path (currently
364
a tuple of the contents sha1 and the statvalue returned by
365
tree.get_file_with_stat()).
367
if self.new_inventory.root is None:
368
if ie.parent_id is not None:
369
raise errors.RootMissing()
370
self._check_root(ie, parent_invs, tree)
371
if ie.revision is None:
372
kind = content_summary[0]
374
# ie is carried over from a prior commit
376
# XXX: repository specific check for nested tree support goes here - if
377
# the repo doesn't want nested trees we skip it ?
378
if (kind == 'tree-reference' and
379
not self.repository._format.supports_tree_reference):
380
# mismatch between commit builder logic and repository:
381
# this needs the entry creation pushed down into the builder.
382
raise NotImplementedError('Missing repository subtree support.')
383
self.new_inventory.add(ie)
385
# TODO: slow, take it out of the inner loop.
387
basis_inv = parent_invs[0]
389
basis_inv = Inventory(root_id=None)
391
# ie.revision is always None if the InventoryEntry is considered
392
# for committing. We may record the previous parents revision if the
393
# content is actually unchanged against a sole head.
394
if ie.revision is not None:
395
if not self._versioned_root and path == '':
396
# repositories that do not version the root set the root's
397
# revision to the new commit even when no change occurs (more
398
# specifically, they do not record a revision on the root; and
399
# the rev id is assigned to the root during deserialisation -
400
# this masks when a change may have occurred against the basis.
401
# To match this we always issue a delta, because the revision
402
# of the root will always be changing.
403
if basis_inv.has_id(ie.file_id):
404
delta = (basis_inv.id2path(ie.file_id), path,
408
delta = (None, path, ie.file_id, ie)
409
self._basis_delta.append(delta)
410
return delta, False, None
412
# we don't need to commit this, because the caller already
413
# determined that an existing revision of this file is
414
# appropriate. If it's not being considered for committing then
415
# it and all its parents to the root must be unaltered so
416
# no-change against the basis.
417
if ie.revision == self._new_revision_id:
418
raise AssertionError("Impossible situation, a skipped "
419
"inventory entry (%r) claims to be modified in this "
420
"commit (%r).", (ie, self._new_revision_id))
421
return None, False, None
422
# XXX: Friction: parent_candidates should return a list not a dict
423
# so that we don't have to walk the inventories again.
424
parent_candidate_entries = ie.parent_candidates(parent_invs)
425
head_set = self._heads(ie.file_id, parent_candidate_entries.keys())
427
for inv in parent_invs:
428
if inv.has_id(ie.file_id):
429
old_rev = inv[ie.file_id].revision
430
if old_rev in head_set:
431
heads.append(inv[ie.file_id].revision)
432
head_set.remove(inv[ie.file_id].revision)
435
# now we check to see if we need to write a new record to the
437
# We write a new entry unless there is one head to the ancestors, and
438
# the kind-derived content is unchanged.
440
# Cheapest check first: no ancestors, or more the one head in the
441
# ancestors, we write a new node.
445
# There is a single head, look it up for comparison
446
parent_entry = parent_candidate_entries[heads[0]]
447
# if the non-content specific data has changed, we'll be writing a
449
if (parent_entry.parent_id != ie.parent_id or
450
parent_entry.name != ie.name):
452
# now we need to do content specific checks:
454
# if the kind changed the content obviously has
455
if kind != parent_entry.kind:
457
# Stat cache fingerprint feedback for the caller - None as we usually
458
# don't generate one.
461
if content_summary[2] is None:
462
raise ValueError("Files must not have executable = None")
464
# We can't trust a check of the file length because of content
466
if (# if the exec bit has changed we have to store:
467
parent_entry.executable != content_summary[2]):
469
elif parent_entry.text_sha1 == content_summary[3]:
470
# all meta and content is unchanged (using a hash cache
471
# hit to check the sha)
472
ie.revision = parent_entry.revision
473
ie.text_size = parent_entry.text_size
474
ie.text_sha1 = parent_entry.text_sha1
475
ie.executable = parent_entry.executable
476
return self._get_delta(ie, basis_inv, path), False, None
478
# Either there is only a hash change(no hash cache entry,
479
# or same size content change), or there is no change on
481
# Provide the parent's hash to the store layer, so that the
482
# content is unchanged we will not store a new node.
483
nostore_sha = parent_entry.text_sha1
485
# We want to record a new node regardless of the presence or
486
# absence of a content change in the file.
488
ie.executable = content_summary[2]
489
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
491
text = file_obj.read()
495
ie.text_sha1, ie.text_size = self._add_text_to_weave(
496
ie.file_id, text, heads, nostore_sha)
497
# Let the caller know we generated a stat fingerprint.
498
fingerprint = (ie.text_sha1, stat_value)
499
except errors.ExistingContent:
500
# Turns out that the file content was unchanged, and we were
501
# only going to store a new node if it was changed. Carry over
503
ie.revision = parent_entry.revision
504
ie.text_size = parent_entry.text_size
505
ie.text_sha1 = parent_entry.text_sha1
506
ie.executable = parent_entry.executable
507
return self._get_delta(ie, basis_inv, path), False, None
508
elif kind == 'directory':
510
# all data is meta here, nothing specific to directory, so
512
ie.revision = parent_entry.revision
513
return self._get_delta(ie, basis_inv, path), False, None
514
self._add_text_to_weave(ie.file_id, '', heads, None)
515
elif kind == 'symlink':
516
current_link_target = content_summary[3]
518
# symlink target is not generic metadata, check if it has
520
if current_link_target != parent_entry.symlink_target:
523
# unchanged, carry over.
524
ie.revision = parent_entry.revision
525
ie.symlink_target = parent_entry.symlink_target
526
return self._get_delta(ie, basis_inv, path), False, None
527
ie.symlink_target = current_link_target
528
self._add_text_to_weave(ie.file_id, '', heads, None)
529
elif kind == 'tree-reference':
531
if content_summary[3] != parent_entry.reference_revision:
534
# unchanged, carry over.
535
ie.reference_revision = parent_entry.reference_revision
536
ie.revision = parent_entry.revision
537
return self._get_delta(ie, basis_inv, path), False, None
538
ie.reference_revision = content_summary[3]
539
if ie.reference_revision is None:
540
raise AssertionError("invalid content_summary for nested tree: %r"
541
% (content_summary,))
542
self._add_text_to_weave(ie.file_id, '', heads, None)
544
raise NotImplementedError('unknown kind')
545
ie.revision = self._new_revision_id
546
# The initial commit adds a root directory, but this in itself is not
547
# a worthwhile commit.
548
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
550
self._any_changes = True
551
return self._get_delta(ie, basis_inv, path), True, fingerprint
553
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
554
_entry_factory=entry_factory):
555
"""Record a new tree via iter_changes.
557
:param tree: The tree to obtain text contents from for changed objects.
558
:param basis_revision_id: The revision id of the tree the iter_changes
559
has been generated against. Currently assumed to be the same
560
as self.parents[0] - if it is not, errors may occur.
561
:param iter_changes: An iter_changes iterator with the changes to apply
562
to basis_revision_id. The iterator must not include any items with
563
a current kind of None - missing items must be either filtered out
564
or errored-on before record_iter_changes sees the item.
565
:param _entry_factory: Private method to bind entry_factory locally for
567
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
570
# Create an inventory delta based on deltas between all the parents and
571
# deltas between all the parent inventories. We use inventory delta's
572
# between the inventory objects because iter_changes masks
573
# last-changed-field only changes.
575
# file_id -> change map, change is fileid, paths, changed, versioneds,
576
# parents, names, kinds, executables
578
# {file_id -> revision_id -> inventory entry, for entries in parent
579
# trees that are not parents[0]
583
revtrees = list(self.repository.revision_trees(self.parents))
584
except errors.NoSuchRevision:
585
# one or more ghosts, slow path.
587
for revision_id in self.parents:
589
revtrees.append(self.repository.revision_tree(revision_id))
590
except errors.NoSuchRevision:
592
basis_revision_id = _mod_revision.NULL_REVISION
594
revtrees.append(self.repository.revision_tree(
595
_mod_revision.NULL_REVISION))
596
# The basis inventory from a repository
598
basis_inv = revtrees[0].inventory
600
basis_inv = self.repository.revision_tree(
601
_mod_revision.NULL_REVISION).inventory
602
if len(self.parents) > 0:
603
if basis_revision_id != self.parents[0] and not ghost_basis:
605
"arbitrary basis parents not yet supported with merges")
606
for revtree in revtrees[1:]:
607
for change in revtree.inventory._make_delta(basis_inv):
608
if change[1] is None:
609
# Not present in this parent.
611
if change[2] not in merged_ids:
612
if change[0] is not None:
613
basis_entry = basis_inv[change[2]]
614
merged_ids[change[2]] = [
616
basis_entry.revision,
619
parent_entries[change[2]] = {
621
basis_entry.revision:basis_entry,
623
change[3].revision:change[3],
626
merged_ids[change[2]] = [change[3].revision]
627
parent_entries[change[2]] = {change[3].revision:change[3]}
629
merged_ids[change[2]].append(change[3].revision)
630
parent_entries[change[2]][change[3].revision] = change[3]
633
# Setup the changes from the tree:
634
# changes maps file_id -> (change, [parent revision_ids])
636
for change in iter_changes:
637
# This probably looks up in basis_inv way to much.
638
if change[1][0] is not None:
639
head_candidate = [basis_inv[change[0]].revision]
642
changes[change[0]] = change, merged_ids.get(change[0],
644
unchanged_merged = set(merged_ids) - set(changes)
645
# Extend the changes dict with synthetic changes to record merges of
647
for file_id in unchanged_merged:
648
# Record a merged version of these items that did not change vs the
649
# basis. This can be either identical parallel changes, or a revert
650
# of a specific file after a merge. The recorded content will be
651
# that of the current tree (which is the same as the basis), but
652
# the per-file graph will reflect a merge.
653
# NB:XXX: We are reconstructing path information we had, this
654
# should be preserved instead.
655
# inv delta change: (file_id, (path_in_source, path_in_target),
656
# changed_content, versioned, parent, name, kind,
659
basis_entry = basis_inv[file_id]
660
except errors.NoSuchId:
661
# a change from basis->some_parents but file_id isn't in basis
662
# so was new in the merge, which means it must have changed
663
# from basis -> current, and as it hasn't the add was reverted
664
# by the user. So we discard this change.
668
(basis_inv.id2path(file_id), tree.id2path(file_id)),
670
(basis_entry.parent_id, basis_entry.parent_id),
671
(basis_entry.name, basis_entry.name),
672
(basis_entry.kind, basis_entry.kind),
673
(basis_entry.executable, basis_entry.executable))
674
changes[file_id] = (change, merged_ids[file_id])
675
# changes contains tuples with the change and a set of inventory
676
# candidates for the file.
678
# old_path, new_path, file_id, new_inventory_entry
679
seen_root = False # Is the root in the basis delta?
680
inv_delta = self._basis_delta
681
modified_rev = self._new_revision_id
682
for change, head_candidates in changes.values():
683
if change[3][1]: # versioned in target.
684
# Several things may be happening here:
685
# We may have a fork in the per-file graph
686
# - record a change with the content from tree
687
# We may have a change against < all trees
688
# - carry over the tree that hasn't changed
689
# We may have a change against all trees
690
# - record the change with the content from tree
693
entry = _entry_factory[kind](file_id, change[5][1],
695
head_set = self._heads(change[0], set(head_candidates))
698
for head_candidate in head_candidates:
699
if head_candidate in head_set:
700
heads.append(head_candidate)
701
head_set.remove(head_candidate)
704
# Could be a carry-over situation:
705
parent_entry_revs = parent_entries.get(file_id, None)
706
if parent_entry_revs:
707
parent_entry = parent_entry_revs.get(heads[0], None)
710
if parent_entry is None:
711
# The parent iter_changes was called against is the one
712
# that is the per-file head, so any change is relevant
713
# iter_changes is valid.
714
carry_over_possible = False
716
# could be a carry over situation
717
# A change against the basis may just indicate a merge,
718
# we need to check the content against the source of the
719
# merge to determine if it was changed after the merge
721
if (parent_entry.kind != entry.kind or
722
parent_entry.parent_id != entry.parent_id or
723
parent_entry.name != entry.name):
724
# Metadata common to all entries has changed
725
# against per-file parent
726
carry_over_possible = False
728
carry_over_possible = True
729
# per-type checks for changes against the parent_entry
732
# Cannot be a carry-over situation
733
carry_over_possible = False
734
# Populate the entry in the delta
736
# XXX: There is still a small race here: If someone reverts the content of a file
737
# after iter_changes examines and decides it has changed,
738
# we will unconditionally record a new version even if some
739
# other process reverts it while commit is running (with
740
# the revert happening after iter_changes did its
743
entry.executable = True
745
entry.executable = False
746
if (carry_over_possible and
747
parent_entry.executable == entry.executable):
748
# Check the file length, content hash after reading
750
nostore_sha = parent_entry.text_sha1
753
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
755
text = file_obj.read()
759
entry.text_sha1, entry.text_size = self._add_text_to_weave(
760
file_id, text, heads, nostore_sha)
761
yield file_id, change[1][1], (entry.text_sha1, stat_value)
762
except errors.ExistingContent:
763
# No content change against a carry_over parent
764
# Perhaps this should also yield a fs hash update?
766
entry.text_size = parent_entry.text_size
767
entry.text_sha1 = parent_entry.text_sha1
768
elif kind == 'symlink':
770
entry.symlink_target = tree.get_symlink_target(file_id)
771
if (carry_over_possible and
772
parent_entry.symlink_target == entry.symlink_target):
775
self._add_text_to_weave(change[0], '', heads, None)
776
elif kind == 'directory':
777
if carry_over_possible:
780
# Nothing to set on the entry.
781
# XXX: split into the Root and nonRoot versions.
782
if change[1][1] != '' or self.repository.supports_rich_root():
783
self._add_text_to_weave(change[0], '', heads, None)
784
elif kind == 'tree-reference':
785
if not self.repository._format.supports_tree_reference:
786
# This isn't quite sane as an error, but we shouldn't
787
# ever see this code path in practice: tree's don't
788
# permit references when the repo doesn't support tree
790
raise errors.UnsupportedOperation(tree.add_reference,
792
reference_revision = tree.get_reference_revision(change[0])
793
entry.reference_revision = reference_revision
794
if (carry_over_possible and
795
parent_entry.reference_revision == reference_revision):
798
self._add_text_to_weave(change[0], '', heads, None)
800
raise AssertionError('unknown kind %r' % kind)
802
entry.revision = modified_rev
804
entry.revision = parent_entry.revision
807
new_path = change[1][1]
808
inv_delta.append((change[1][0], new_path, change[0], entry))
811
self.new_inventory = None
812
# The initial commit adds a root directory, but this in itself is not
813
# a worthwhile commit.
814
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
815
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
816
# This should perhaps be guarded by a check that the basis we
817
# commit against is the basis for the commit and if not do a delta
819
self._any_changes = True
821
# housekeeping root entry changes do not affect no-change commits.
822
self._require_root_change(tree)
823
self.basis_delta_revision = basis_revision_id
825
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
826
parent_keys = tuple([(file_id, parent) for parent in parents])
827
return self.repository.texts._add_text(
828
(file_id, self._new_revision_id), parent_keys, new_text,
829
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
832
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
833
"""This commitbuilder actually records the root id"""
835
# the root entry gets versioned properly by this builder.
836
_versioned_root = True
838
def _check_root(self, ie, parent_invs, tree):
839
"""Helper for record_entry_contents.
841
:param ie: An entry being added.
842
:param parent_invs: The inventories of the parent revisions of the
844
:param tree: The tree that is being committed.
847
def _require_root_change(self, tree):
848
"""Enforce an appropriate root object change.
850
This is called once when record_iter_changes is called, if and only if
851
the root was not in the delta calculated by record_iter_changes.
853
:param tree: The tree which is being committed.
855
# versioned roots do not change unless the tree found a change.
858
class VersionedFileRepository(Repository):
859
"""Repository holding history for one or more branches.
861
The repository holds and retrieves historical information including
862
revisions and file history. It's normally accessed only by the Branch,
863
which views a particular line of development through that history.
865
The Repository builds on top of some byte storage facilies (the revisions,
866
signatures, inventories, texts and chk_bytes attributes) and a Transport,
867
which respectively provide byte storage and a means to access the (possibly
870
The byte storage facilities are addressed via tuples, which we refer to
871
as 'keys' throughout the code base. Revision_keys, inventory_keys and
872
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
873
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
874
byte string made up of a hash identifier and a hash value.
875
We use this interface because it allows low friction with the underlying
876
code that implements disk indices, network encoding and other parts of
879
:ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
880
the serialised revisions for the repository. This can be used to obtain
881
revision graph information or to access raw serialised revisions.
882
The result of trying to insert data into the repository via this store
883
is undefined: it should be considered read-only except for implementors
885
:ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
886
the serialised signatures for the repository. This can be used to
887
obtain access to raw serialised signatures. The result of trying to
888
insert data into the repository via this store is undefined: it should
889
be considered read-only except for implementors of repositories.
890
:ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
891
the serialised inventories for the repository. This can be used to
892
obtain unserialised inventories. The result of trying to insert data
893
into the repository via this store is undefined: it should be
894
considered read-only except for implementors of repositories.
895
:ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
896
texts of files and directories for the repository. This can be used to
897
obtain file texts or file graphs. Note that Repository.iter_file_bytes
898
is usually a better interface for accessing file texts.
899
The result of trying to insert data into the repository via this store
900
is undefined: it should be considered read-only except for implementors
902
:ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
903
any data the repository chooses to store or have indexed by its hash.
904
The result of trying to insert data into the repository via this store
905
is undefined: it should be considered read-only except for implementors
907
:ivar _transport: Transport for file access to repository, typically
908
pointing to .bzr/repository.
911
# What class to use for a CommitBuilder. Often it's simpler to change this
912
# in a Repository class subclass rather than to override
913
# get_commit_builder.
914
_commit_builder_class = VersionedFileCommitBuilder
916
def add_fallback_repository(self, repository):
917
"""Add a repository to use for looking up data not held locally.
919
:param repository: A repository.
921
if not self._format.supports_external_lookups:
922
raise errors.UnstackableRepositoryFormat(self._format, self.base)
923
# This can raise an exception, so should be done before we lock the
924
# fallback repository.
925
self._check_fallback_repository(repository)
927
# This repository will call fallback.unlock() when we transition to
928
# the unlocked state, so we make sure to increment the lock count
929
repository.lock_read()
930
self._fallback_repositories.append(repository)
931
self.texts.add_fallback_versioned_files(repository.texts)
932
self.inventories.add_fallback_versioned_files(repository.inventories)
933
self.revisions.add_fallback_versioned_files(repository.revisions)
934
self.signatures.add_fallback_versioned_files(repository.signatures)
935
if self.chk_bytes is not None:
936
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
938
@only_raises(errors.LockNotHeld, errors.LockBroken)
940
super(VersionedFileRepository, self).unlock()
941
if self.control_files._lock_count == 0:
942
self._inventory_entry_cache.clear()
944
def add_inventory(self, revision_id, inv, parents):
945
"""Add the inventory inv to the repository as revision_id.
947
:param parents: The revision ids of the parents that revision_id
948
is known to have and are in the repository already.
950
:returns: The validator(which is a sha1 digest, though what is sha'd is
951
repository format specific) of the serialized inventory.
953
if not self.is_in_write_group():
954
raise AssertionError("%r not in write group" % (self,))
955
_mod_revision.check_not_reserved_id(revision_id)
956
if not (inv.revision_id is None or inv.revision_id == revision_id):
957
raise AssertionError(
958
"Mismatch between inventory revision"
959
" id and insertion revid (%r, %r)"
960
% (inv.revision_id, revision_id))
962
raise errors.RootMissing()
963
return self._add_inventory_checked(revision_id, inv, parents)
965
def _add_inventory_checked(self, revision_id, inv, parents):
966
"""Add inv to the repository after checking the inputs.
968
This function can be overridden to allow different inventory styles.
970
:seealso: add_inventory, for the contract.
972
inv_lines = self._serializer.write_inventory_to_lines(inv)
973
return self._inventory_add_lines(revision_id, parents,
974
inv_lines, check_content=False)
976
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
977
parents, basis_inv=None, propagate_caches=False):
978
"""Add a new inventory expressed as a delta against another revision.
980
See the inventory developers documentation for the theory behind
983
:param basis_revision_id: The inventory id the delta was created
984
against. (This does not have to be a direct parent.)
985
:param delta: The inventory delta (see Inventory.apply_delta for
987
:param new_revision_id: The revision id that the inventory is being
989
:param parents: The revision ids of the parents that revision_id is
990
known to have and are in the repository already. These are supplied
991
for repositories that depend on the inventory graph for revision
992
graph access, as well as for those that pun ancestry with delta
994
:param basis_inv: The basis inventory if it is already known,
996
:param propagate_caches: If True, the caches for this inventory are
997
copied to and updated for the result if possible.
999
:returns: (validator, new_inv)
1000
The validator(which is a sha1 digest, though what is sha'd is
1001
repository format specific) of the serialized inventory, and the
1002
resulting inventory.
1004
if not self.is_in_write_group():
1005
raise AssertionError("%r not in write group" % (self,))
1006
_mod_revision.check_not_reserved_id(new_revision_id)
1007
basis_tree = self.revision_tree(basis_revision_id)
1008
basis_tree.lock_read()
1010
# Note that this mutates the inventory of basis_tree, which not all
1011
# inventory implementations may support: A better idiom would be to
1012
# return a new inventory, but as there is no revision tree cache in
1013
# repository this is safe for now - RBC 20081013
1014
if basis_inv is None:
1015
basis_inv = basis_tree.inventory
1016
basis_inv.apply_delta(delta)
1017
basis_inv.revision_id = new_revision_id
1018
return (self.add_inventory(new_revision_id, basis_inv, parents),
1023
def _inventory_add_lines(self, revision_id, parents, lines,
1024
check_content=True):
1025
"""Store lines in inv_vf and return the sha1 of the inventory."""
1026
parents = [(parent,) for parent in parents]
1027
result = self.inventories.add_lines((revision_id,), parents, lines,
1028
check_content=check_content)[0]
1029
self.inventories._access.flush()
1032
def add_revision(self, revision_id, rev, inv=None, config=None):
1033
"""Add rev to the revision store as revision_id.
1035
:param revision_id: the revision id to use.
1036
:param rev: The revision object.
1037
:param inv: The inventory for the revision. if None, it will be looked
1038
up in the inventory storer
1039
:param config: If None no digital signature will be created.
1040
If supplied its signature_needed method will be used
1041
to determine if a signature should be made.
1043
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1045
_mod_revision.check_not_reserved_id(revision_id)
1046
if config is not None and config.signature_needed():
1048
inv = self.get_inventory(revision_id)
1049
tree = InventoryRevisionTree(self, inv, revision_id)
1050
testament = Testament(rev, tree)
1051
plaintext = testament.as_short_text()
1052
self.store_revision_signature(
1053
gpg.GPGStrategy(config), plaintext, revision_id)
1054
# check inventory present
1055
if not self.inventories.get_parent_map([(revision_id,)]):
1057
raise errors.WeaveRevisionNotPresent(revision_id,
1060
# yes, this is not suitable for adding with ghosts.
1061
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1064
key = (revision_id,)
1065
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1066
self._add_revision(rev)
1068
def _add_revision(self, revision):
1069
text = self._serializer.write_revision_to_string(revision)
1070
key = (revision.revision_id,)
1071
parents = tuple((parent,) for parent in revision.parent_ids)
1072
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1074
def _check_inventories(self, checker):
1075
"""Check the inventories found from the revision scan.
1077
This is responsible for verifying the sha1 of inventories and
1078
creating a pending_keys set that covers data referenced by inventories.
1080
bar = ui.ui_factory.nested_progress_bar()
1082
self._do_check_inventories(checker, bar)
1086
def _do_check_inventories(self, checker, bar):
1087
"""Helper for _check_inventories."""
1089
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1090
kinds = ['chk_bytes', 'texts']
1091
count = len(checker.pending_keys)
1092
bar.update(gettext("inventories"), 0, 2)
1093
current_keys = checker.pending_keys
1094
checker.pending_keys = {}
1095
# Accumulate current checks.
1096
for key in current_keys:
1097
if key[0] != 'inventories' and key[0] not in kinds:
1098
checker._report_items.append('unknown key type %r' % (key,))
1099
keys[key[0]].add(key[1:])
1100
if keys['inventories']:
1101
# NB: output order *should* be roughly sorted - topo or
1102
# inverse topo depending on repository - either way decent
1103
# to just delta against. However, pre-CHK formats didn't
1104
# try to optimise inventory layout on disk. As such the
1105
# pre-CHK code path does not use inventory deltas.
1107
for record in self.inventories.check(keys=keys['inventories']):
1108
if record.storage_kind == 'absent':
1109
checker._report_items.append(
1110
'Missing inventory {%s}' % (record.key,))
1112
last_object = self._check_record('inventories', record,
1113
checker, last_object,
1114
current_keys[('inventories',) + record.key])
1115
del keys['inventories']
1118
bar.update(gettext("texts"), 1)
1119
while (checker.pending_keys or keys['chk_bytes']
1121
# Something to check.
1122
current_keys = checker.pending_keys
1123
checker.pending_keys = {}
1124
# Accumulate current checks.
1125
for key in current_keys:
1126
if key[0] not in kinds:
1127
checker._report_items.append('unknown key type %r' % (key,))
1128
keys[key[0]].add(key[1:])
1129
# Check the outermost kind only - inventories || chk_bytes || texts
1133
for record in getattr(self, kind).check(keys=keys[kind]):
1134
if record.storage_kind == 'absent':
1135
checker._report_items.append(
1136
'Missing %s {%s}' % (kind, record.key,))
1138
last_object = self._check_record(kind, record,
1139
checker, last_object, current_keys[(kind,) + record.key])
1143
def _check_record(self, kind, record, checker, last_object, item_data):
1144
"""Check a single text from this repository."""
1145
if kind == 'inventories':
1146
rev_id = record.key[0]
1147
inv = self._deserialise_inventory(rev_id,
1148
record.get_bytes_as('fulltext'))
1149
if last_object is not None:
1150
delta = inv._make_delta(last_object)
1151
for old_path, path, file_id, ie in delta:
1154
ie.check(checker, rev_id, inv)
1156
for path, ie in inv.iter_entries():
1157
ie.check(checker, rev_id, inv)
1158
if self._format.fast_deltas:
1160
elif kind == 'chk_bytes':
1161
# No code written to check chk_bytes for this repo format.
1162
checker._report_items.append(
1163
'unsupported key type chk_bytes for %s' % (record.key,))
1164
elif kind == 'texts':
1165
self._check_text(record, checker, item_data)
1167
checker._report_items.append(
1168
'unknown key type %s for %s' % (kind, record.key))
1170
def _check_text(self, record, checker, item_data):
1171
"""Check a single text."""
1172
# Check it is extractable.
1173
# TODO: check length.
1174
if record.storage_kind == 'chunked':
1175
chunks = record.get_bytes_as(record.storage_kind)
1176
sha1 = osutils.sha_strings(chunks)
1177
length = sum(map(len, chunks))
1179
content = record.get_bytes_as('fulltext')
1180
sha1 = osutils.sha_string(content)
1181
length = len(content)
1182
if item_data and sha1 != item_data[1]:
1183
checker._report_items.append(
1184
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1185
(record.key, sha1, item_data[1], item_data[2]))
1188
def _eliminate_revisions_not_present(self, revision_ids):
1189
"""Check every revision id in revision_ids to see if we have it.
1191
Returns a set of the present revisions.
1194
graph = self.get_graph()
1195
parent_map = graph.get_parent_map(revision_ids)
1196
# The old API returned a list, should this actually be a set?
1197
return parent_map.keys()
1199
def __init__(self, _format, a_bzrdir, control_files):
1200
"""Instantiate a VersionedFileRepository.
1202
:param _format: The format of the repository on disk.
1203
:param controldir: The ControlDir of the repository.
1204
:param control_files: Control files to use for locking, etc.
1206
# In the future we will have a single api for all stores for
1207
# getting file texts, inventories and revisions, then
1208
# this construct will accept instances of those things.
1209
super(VersionedFileRepository, self).__init__(_format, a_bzrdir,
1211
self._transport = control_files._transport
1212
self.base = self._transport.base
1214
self._reconcile_does_inventory_gc = True
1215
self._reconcile_fixes_text_parents = False
1216
self._reconcile_backsup_inventory = True
1217
# An InventoryEntry cache, used during deserialization
1218
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1219
# Is it safe to return inventory entries directly from the entry cache,
1220
# rather copying them?
1221
self._safe_to_return_from_cache = False
1224
def gather_stats(self, revid=None, committers=None):
1225
"""See Repository.gather_stats()."""
1226
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1227
# now gather global repository information
1228
# XXX: This is available for many repos regardless of listability.
1229
if self.user_transport.listable():
1230
# XXX: do we want to __define len__() ?
1231
# Maybe the versionedfiles object should provide a different
1232
# method to get the number of keys.
1233
result['revisions'] = len(self.revisions.keys())
1234
# result['size'] = t
1237
def get_commit_builder(self, branch, parents, config, timestamp=None,
1238
timezone=None, committer=None, revprops=None,
1239
revision_id=None, lossy=False):
1240
"""Obtain a CommitBuilder for this repository.
1242
:param branch: Branch to commit to.
1243
:param parents: Revision ids of the parents of the new revision.
1244
:param config: Configuration to use.
1245
:param timestamp: Optional timestamp recorded for commit.
1246
:param timezone: Optional timezone for timestamp.
1247
:param committer: Optional committer to set for commit.
1248
:param revprops: Optional dictionary of revision properties.
1249
:param revision_id: Optional revision id.
1250
:param lossy: Whether to discard data that can not be natively
1251
represented, when pushing to a foreign VCS
1253
if self._fallback_repositories and not self._format.supports_chks:
1254
raise errors.BzrError("Cannot commit directly to a stacked branch"
1255
" in pre-2a formats. See "
1256
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1257
result = self._commit_builder_class(self, parents, config,
1258
timestamp, timezone, committer, revprops, revision_id,
1260
self.start_write_group()
1263
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1264
"""Return the keys of missing inventory parents for revisions added in
1267
A revision is not complete if the inventory delta for that revision
1268
cannot be calculated. Therefore if the parent inventories of a
1269
revision are not present, the revision is incomplete, and e.g. cannot
1270
be streamed by a smart server. This method finds missing inventory
1271
parents for revisions added in this write group.
1273
if not self._format.supports_external_lookups:
1274
# This is only an issue for stacked repositories
1276
if not self.is_in_write_group():
1277
raise AssertionError('not in a write group')
1279
# XXX: We assume that every added revision already has its
1280
# corresponding inventory, so we only check for parent inventories that
1281
# might be missing, rather than all inventories.
1282
parents = set(self.revisions._index.get_missing_parents())
1283
parents.discard(_mod_revision.NULL_REVISION)
1284
unstacked_inventories = self.inventories._index
1285
present_inventories = unstacked_inventories.get_parent_map(
1286
key[-1:] for key in parents)
1287
parents.difference_update(present_inventories)
1288
if len(parents) == 0:
1289
# No missing parent inventories.
1291
if not check_for_missing_texts:
1292
return set(('inventories', rev_id) for (rev_id,) in parents)
1293
# Ok, now we have a list of missing inventories. But these only matter
1294
# if the inventories that reference them are missing some texts they
1295
# appear to introduce.
1296
# XXX: Texts referenced by all added inventories need to be present,
1297
# but at the moment we're only checking for texts referenced by
1298
# inventories at the graph's edge.
1299
key_deps = self.revisions._index._key_dependencies
1300
key_deps.satisfy_refs_for_keys(present_inventories)
1301
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1302
file_ids = self.fileids_altered_by_revision_ids(referrers)
1303
missing_texts = set()
1304
for file_id, version_ids in file_ids.iteritems():
1305
missing_texts.update(
1306
(file_id, version_id) for version_id in version_ids)
1307
present_texts = self.texts.get_parent_map(missing_texts)
1308
missing_texts.difference_update(present_texts)
1309
if not missing_texts:
1310
# No texts are missing, so all revisions and their deltas are
1313
# Alternatively the text versions could be returned as the missing
1314
# keys, but this is likely to be less data.
1315
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1319
def has_revisions(self, revision_ids):
1320
"""Probe to find out the presence of multiple revisions.
1322
:param revision_ids: An iterable of revision_ids.
1323
:return: A set of the revision_ids that were present.
1325
parent_map = self.revisions.get_parent_map(
1326
[(rev_id,) for rev_id in revision_ids])
1328
if _mod_revision.NULL_REVISION in revision_ids:
1329
result.add(_mod_revision.NULL_REVISION)
1330
result.update([key[0] for key in parent_map])
1334
def get_revision_reconcile(self, revision_id):
1335
"""'reconcile' helper routine that allows access to a revision always.
1337
This variant of get_revision does not cross check the weave graph
1338
against the revision one as get_revision does: but it should only
1339
be used by reconcile, or reconcile-alike commands that are correcting
1340
or testing the revision graph.
1342
return self._get_revisions([revision_id])[0]
1345
def get_revisions(self, revision_ids):
1346
"""Get many revisions at once.
1348
Repositories that need to check data on every revision read should
1349
subclass this method.
1351
return self._get_revisions(revision_ids)
1354
def _get_revisions(self, revision_ids):
1355
"""Core work logic to get many revisions without sanity checks."""
1357
for revid, rev in self._iter_revisions(revision_ids):
1359
raise errors.NoSuchRevision(self, revid)
1361
return [revs[revid] for revid in revision_ids]
1363
def _iter_revisions(self, revision_ids):
1364
"""Iterate over revision objects.
1366
:param revision_ids: An iterable of revisions to examine. None may be
1367
passed to request all revisions known to the repository. Note that
1368
not all repositories can find unreferenced revisions; for those
1369
repositories only referenced ones will be returned.
1370
:return: An iterator of (revid, revision) tuples. Absent revisions (
1371
those asked for but not available) are returned as (revid, None).
1373
if revision_ids is None:
1374
revision_ids = self.all_revision_ids()
1376
for rev_id in revision_ids:
1377
if not rev_id or not isinstance(rev_id, basestring):
1378
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1379
keys = [(key,) for key in revision_ids]
1380
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1381
for record in stream:
1382
revid = record.key[0]
1383
if record.storage_kind == 'absent':
1386
text = record.get_bytes_as('fulltext')
1387
rev = self._serializer.read_revision_from_string(text)
1391
def add_signature_text(self, revision_id, signature):
1392
"""Store a signature text for a revision.
1394
:param revision_id: Revision id of the revision
1395
:param signature: Signature text.
1397
self.signatures.add_lines((revision_id,), (),
1398
osutils.split_lines(signature))
1400
def find_text_key_references(self):
1401
"""Find the text key references within the repository.
1403
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1404
to whether they were referred to by the inventory of the
1405
revision_id that they contain. The inventory texts from all present
1406
revision ids are assessed to generate this report.
1408
revision_keys = self.revisions.keys()
1409
w = self.inventories
1410
pb = ui.ui_factory.nested_progress_bar()
1412
return self._serializer._find_text_key_references(
1413
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1417
def _inventory_xml_lines_for_keys(self, keys):
1418
"""Get a line iterator of the sort needed for findind references.
1420
Not relevant for non-xml inventory repositories.
1422
Ghosts in revision_keys are ignored.
1424
:param revision_keys: The revision keys for the inventories to inspect.
1425
:return: An iterator over (inventory line, revid) for the fulltexts of
1426
all of the xml inventories specified by revision_keys.
1428
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1429
for record in stream:
1430
if record.storage_kind != 'absent':
1431
chunks = record.get_bytes_as('chunked')
1432
revid = record.key[-1]
1433
lines = osutils.chunks_to_lines(chunks)
1437
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1439
"""Helper routine for fileids_altered_by_revision_ids.
1441
This performs the translation of xml lines to revision ids.
1443
:param line_iterator: An iterator of lines, origin_version_id
1444
:param revision_keys: The revision ids to filter for. This should be a
1445
set or other type which supports efficient __contains__ lookups, as
1446
the revision key from each parsed line will be looked up in the
1447
revision_keys filter.
1448
:return: a dictionary mapping altered file-ids to an iterable of
1449
revision_ids. Each altered file-ids has the exact revision_ids that
1450
altered it listed explicitly.
1452
seen = set(self._serializer._find_text_key_references(
1453
line_iterator).iterkeys())
1454
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1455
parent_seen = set(self._serializer._find_text_key_references(
1456
self._inventory_xml_lines_for_keys(parent_keys)))
1457
new_keys = seen - parent_seen
1459
setdefault = result.setdefault
1460
for key in new_keys:
1461
setdefault(key[0], set()).add(key[-1])
1464
def _find_parent_keys_of_revisions(self, revision_keys):
1465
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1467
:param revision_keys: An iterable of revision_keys.
1468
:return: The parents of all revision_keys that are not already in
1471
parent_map = self.revisions.get_parent_map(revision_keys)
1473
map(parent_keys.update, parent_map.itervalues())
1474
parent_keys.difference_update(revision_keys)
1475
parent_keys.discard(_mod_revision.NULL_REVISION)
1478
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1479
"""Find the file ids and versions affected by revisions.
1481
:param revisions: an iterable containing revision ids.
1482
:param _inv_weave: The inventory weave from this repository or None.
1483
If None, the inventory weave will be opened automatically.
1484
:return: a dictionary mapping altered file-ids to an iterable of
1485
revision_ids. Each altered file-ids has the exact revision_ids that
1486
altered it listed explicitly.
1488
selected_keys = set((revid,) for revid in revision_ids)
1489
w = _inv_weave or self.inventories
1490
return self._find_file_ids_from_xml_inventory_lines(
1491
w.iter_lines_added_or_present_in_keys(
1492
selected_keys, pb=None),
1495
def iter_files_bytes(self, desired_files):
1496
"""Iterate through file versions.
1498
Files will not necessarily be returned in the order they occur in
1499
desired_files. No specific order is guaranteed.
1501
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1502
value supplied by the caller as part of desired_files. It should
1503
uniquely identify the file version in the caller's context. (Examples:
1504
an index number or a TreeTransform trans_id.)
1506
bytes_iterator is an iterable of bytestrings for the file. The
1507
kind of iterable and length of the bytestrings are unspecified, but for
1508
this implementation, it is a list of bytes produced by
1509
VersionedFile.get_record_stream().
1511
:param desired_files: a list of (file_id, revision_id, identifier)
1515
for file_id, revision_id, callable_data in desired_files:
1516
text_keys[(file_id, revision_id)] = callable_data
1517
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1518
if record.storage_kind == 'absent':
1519
raise errors.RevisionNotPresent(record.key, self)
1520
yield text_keys[record.key], record.get_bytes_as('chunked')
1522
def _generate_text_key_index(self, text_key_references=None,
1524
"""Generate a new text key index for the repository.
1526
This is an expensive function that will take considerable time to run.
1528
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1529
list of parents, also text keys. When a given key has no parents,
1530
the parents list will be [NULL_REVISION].
1532
# All revisions, to find inventory parents.
1533
if ancestors is None:
1534
graph = self.get_graph()
1535
ancestors = graph.get_parent_map(self.all_revision_ids())
1536
if text_key_references is None:
1537
text_key_references = self.find_text_key_references()
1538
pb = ui.ui_factory.nested_progress_bar()
1540
return self._do_generate_text_key_index(ancestors,
1541
text_key_references, pb)
1545
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1546
"""Helper for _generate_text_key_index to avoid deep nesting."""
1547
revision_order = tsort.topo_sort(ancestors)
1548
invalid_keys = set()
1550
for revision_id in revision_order:
1551
revision_keys[revision_id] = set()
1552
text_count = len(text_key_references)
1553
# a cache of the text keys to allow reuse; costs a dict of all the
1554
# keys, but saves a 2-tuple for every child of a given key.
1556
for text_key, valid in text_key_references.iteritems():
1558
invalid_keys.add(text_key)
1560
revision_keys[text_key[1]].add(text_key)
1561
text_key_cache[text_key] = text_key
1562
del text_key_references
1564
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1565
NULL_REVISION = _mod_revision.NULL_REVISION
1566
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1567
# too small for large or very branchy trees. However, for 55K path
1568
# trees, it would be easy to use too much memory trivially. Ideally we
1569
# could gauge this by looking at available real memory etc, but this is
1570
# always a tricky proposition.
1571
inventory_cache = lru_cache.LRUCache(10)
1572
batch_size = 10 # should be ~150MB on a 55K path tree
1573
batch_count = len(revision_order) / batch_size + 1
1575
pb.update(gettext("Calculating text parents"), processed_texts, text_count)
1576
for offset in xrange(batch_count):
1577
to_query = revision_order[offset * batch_size:(offset + 1) *
1581
for revision_id in to_query:
1582
parent_ids = ancestors[revision_id]
1583
for text_key in revision_keys[revision_id]:
1584
pb.update(gettext("Calculating text parents"), processed_texts)
1585
processed_texts += 1
1586
candidate_parents = []
1587
for parent_id in parent_ids:
1588
parent_text_key = (text_key[0], parent_id)
1590
check_parent = parent_text_key not in \
1591
revision_keys[parent_id]
1593
# the parent parent_id is a ghost:
1594
check_parent = False
1595
# truncate the derived graph against this ghost.
1596
parent_text_key = None
1598
# look at the parent commit details inventories to
1599
# determine possible candidates in the per file graph.
1602
inv = inventory_cache[parent_id]
1604
inv = self.revision_tree(parent_id).inventory
1605
inventory_cache[parent_id] = inv
1607
parent_entry = inv[text_key[0]]
1608
except (KeyError, errors.NoSuchId):
1610
if parent_entry is not None:
1612
text_key[0], parent_entry.revision)
1614
parent_text_key = None
1615
if parent_text_key is not None:
1616
candidate_parents.append(
1617
text_key_cache[parent_text_key])
1618
parent_heads = text_graph.heads(candidate_parents)
1619
new_parents = list(parent_heads)
1620
new_parents.sort(key=lambda x:candidate_parents.index(x))
1621
if new_parents == []:
1622
new_parents = [NULL_REVISION]
1623
text_index[text_key] = new_parents
1625
for text_key in invalid_keys:
1626
text_index[text_key] = [NULL_REVISION]
1629
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1630
"""Get an iterable listing the keys of all the data introduced by a set
1633
The keys will be ordered so that the corresponding items can be safely
1634
fetched and inserted in that order.
1636
:returns: An iterable producing tuples of (knit-kind, file-id,
1637
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1638
'revisions'. file-id is None unless knit-kind is 'file'.
1640
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1643
for result in self._find_non_file_keys_to_fetch(revision_ids):
1646
def _find_file_keys_to_fetch(self, revision_ids, pb):
1647
# XXX: it's a bit weird to control the inventory weave caching in this
1648
# generator. Ideally the caching would be done in fetch.py I think. Or
1649
# maybe this generator should explicitly have the contract that it
1650
# should not be iterated until the previously yielded item has been
1652
inv_w = self.inventories
1654
# file ids that changed
1655
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1657
num_file_ids = len(file_ids)
1658
for file_id, altered_versions in file_ids.iteritems():
1660
pb.update(gettext("Fetch texts"), count, num_file_ids)
1662
yield ("file", file_id, altered_versions)
1664
def _find_non_file_keys_to_fetch(self, revision_ids):
1666
yield ("inventory", None, revision_ids)
1669
# XXX: Note ATM no callers actually pay attention to this return
1670
# instead they just use the list of revision ids and ignore
1671
# missing sigs. Consider removing this work entirely
1672
revisions_with_signatures = set(self.signatures.get_parent_map(
1673
[(r,) for r in revision_ids]))
1674
revisions_with_signatures = set(
1675
[r for (r,) in revisions_with_signatures])
1676
revisions_with_signatures.intersection_update(revision_ids)
1677
yield ("signatures", None, revisions_with_signatures)
1680
yield ("revisions", None, revision_ids)
1683
def get_inventory(self, revision_id):
1684
"""Get Inventory object by revision id."""
1685
return self.iter_inventories([revision_id]).next()
1687
def iter_inventories(self, revision_ids, ordering=None):
1688
"""Get many inventories by revision_ids.
1690
This will buffer some or all of the texts used in constructing the
1691
inventories in memory, but will only parse a single inventory at a
1694
:param revision_ids: The expected revision ids of the inventories.
1695
:param ordering: optional ordering, e.g. 'topological'. If not
1696
specified, the order of revision_ids will be preserved (by
1697
buffering if necessary).
1698
:return: An iterator of inventories.
1700
if ((None in revision_ids)
1701
or (_mod_revision.NULL_REVISION in revision_ids)):
1702
raise ValueError('cannot get null revision inventory')
1703
return self._iter_inventories(revision_ids, ordering)
1705
def _iter_inventories(self, revision_ids, ordering):
1706
"""single-document based inventory iteration."""
1707
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1708
for text, revision_id in inv_xmls:
1709
yield self._deserialise_inventory(revision_id, text)
1711
def _iter_inventory_xmls(self, revision_ids, ordering):
1712
if ordering is None:
1713
order_as_requested = True
1714
ordering = 'unordered'
1716
order_as_requested = False
1717
keys = [(revision_id,) for revision_id in revision_ids]
1720
if order_as_requested:
1721
key_iter = iter(keys)
1722
next_key = key_iter.next()
1723
stream = self.inventories.get_record_stream(keys, ordering, True)
1725
for record in stream:
1726
if record.storage_kind != 'absent':
1727
chunks = record.get_bytes_as('chunked')
1728
if order_as_requested:
1729
text_chunks[record.key] = chunks
1731
yield ''.join(chunks), record.key[-1]
1733
raise errors.NoSuchRevision(self, record.key)
1734
if order_as_requested:
1735
# Yield as many results as we can while preserving order.
1736
while next_key in text_chunks:
1737
chunks = text_chunks.pop(next_key)
1738
yield ''.join(chunks), next_key[-1]
1740
next_key = key_iter.next()
1741
except StopIteration:
1742
# We still want to fully consume the get_record_stream,
1743
# just in case it is not actually finished at this point
1747
def _deserialise_inventory(self, revision_id, xml):
1748
"""Transform the xml into an inventory object.
1750
:param revision_id: The expected revision id of the inventory.
1751
:param xml: A serialised inventory.
1753
result = self._serializer.read_inventory_from_string(xml, revision_id,
1754
entry_cache=self._inventory_entry_cache,
1755
return_from_cache=self._safe_to_return_from_cache)
1756
if result.revision_id != revision_id:
1757
raise AssertionError('revision id mismatch %s != %s' % (
1758
result.revision_id, revision_id))
1761
def get_serializer_format(self):
1762
return self._serializer.format_num
1765
def _get_inventory_xml(self, revision_id):
1766
"""Get serialized inventory as a string."""
1767
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1769
text, revision_id = texts.next()
1770
except StopIteration:
1771
raise errors.HistoryMissing(self, 'inventory', revision_id)
1775
def revision_tree(self, revision_id):
1776
"""Return Tree for a revision on this branch.
1778
`revision_id` may be NULL_REVISION for the empty tree revision.
1780
revision_id = _mod_revision.ensure_null(revision_id)
1781
# TODO: refactor this to use an existing revision object
1782
# so we don't need to read it in twice.
1783
if revision_id == _mod_revision.NULL_REVISION:
1784
return InventoryRevisionTree(self,
1785
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1787
inv = self.get_inventory(revision_id)
1788
return InventoryRevisionTree(self, inv, revision_id)
1790
def revision_trees(self, revision_ids):
1791
"""Return Trees for revisions in this repository.
1793
:param revision_ids: a sequence of revision-ids;
1794
a revision-id may not be None or 'null:'
1796
inventories = self.iter_inventories(revision_ids)
1797
for inv in inventories:
1798
yield InventoryRevisionTree(self, inv, inv.revision_id)
1800
def _filtered_revision_trees(self, revision_ids, file_ids):
1801
"""Return Tree for a revision on this branch with only some files.
1803
:param revision_ids: a sequence of revision-ids;
1804
a revision-id may not be None or 'null:'
1805
:param file_ids: if not None, the result is filtered
1806
so that only those file-ids, their parents and their
1807
children are included.
1809
inventories = self.iter_inventories(revision_ids)
1810
for inv in inventories:
1811
# Should we introduce a FilteredRevisionTree class rather
1812
# than pre-filter the inventory here?
1813
filtered_inv = inv.filter(file_ids)
1814
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1816
def get_parent_map(self, revision_ids):
1817
"""See graph.StackedParentsProvider.get_parent_map"""
1818
# revisions index works in keys; this just works in revisions
1819
# therefore wrap and unwrap
1822
for revision_id in revision_ids:
1823
if revision_id == _mod_revision.NULL_REVISION:
1824
result[revision_id] = ()
1825
elif revision_id is None:
1826
raise ValueError('get_parent_map(None) is not valid')
1828
query_keys.append((revision_id ,))
1829
for ((revision_id,), parent_keys) in \
1830
self.revisions.get_parent_map(query_keys).iteritems():
1832
result[revision_id] = tuple([parent_revid
1833
for (parent_revid,) in parent_keys])
1835
result[revision_id] = (_mod_revision.NULL_REVISION,)
1839
def get_known_graph_ancestry(self, revision_ids):
1840
"""Return the known graph for a set of revision ids and their ancestors.
1842
st = static_tuple.StaticTuple
1843
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1844
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1845
return graph.GraphThunkIdsToKeys(known_graph)
1848
def get_file_graph(self):
1849
"""Return the graph walker for text revisions."""
1850
return graph.Graph(self.texts)
1852
def _get_versioned_file_checker(self, text_key_references=None,
1854
"""Return an object suitable for checking versioned files.
1856
:param text_key_references: if non-None, an already built
1857
dictionary mapping text keys ((fileid, revision_id) tuples)
1858
to whether they were referred to by the inventory of the
1859
revision_id that they contain. If None, this will be
1861
:param ancestors: Optional result from
1862
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1865
return _VersionedFileChecker(self,
1866
text_key_references=text_key_references, ancestors=ancestors)
1869
def has_signature_for_revision_id(self, revision_id):
1870
"""Query for a revision signature for revision_id in the repository."""
1871
if not self.has_revision(revision_id):
1872
raise errors.NoSuchRevision(self, revision_id)
1873
sig_present = (1 == len(
1874
self.signatures.get_parent_map([(revision_id,)])))
1878
def get_signature_text(self, revision_id):
1879
"""Return the text for a signature."""
1880
stream = self.signatures.get_record_stream([(revision_id,)],
1882
record = stream.next()
1883
if record.storage_kind == 'absent':
1884
raise errors.NoSuchRevision(self, revision_id)
1885
return record.get_bytes_as('fulltext')
1888
def _check(self, revision_ids, callback_refs, check_repo):
1889
result = check.VersionedFileCheck(self, check_repo=check_repo)
1890
result.check(callback_refs)
1893
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1894
"""Find revisions with different parent lists in the revision object
1895
and in the index graph.
1897
:param revisions_iterator: None, or an iterator of (revid,
1898
Revision-or-None). This iterator controls the revisions checked.
1899
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1900
parents-in-revision).
1902
if not self.is_locked():
1903
raise AssertionError()
1905
if revisions_iterator is None:
1906
revisions_iterator = self._iter_revisions(None)
1907
for revid, revision in revisions_iterator:
1908
if revision is None:
1910
parent_map = vf.get_parent_map([(revid,)])
1911
parents_according_to_index = tuple(parent[-1] for parent in
1912
parent_map[(revid,)])
1913
parents_according_to_revision = tuple(revision.parent_ids)
1914
if parents_according_to_index != parents_according_to_revision:
1915
yield (revid, parents_according_to_index,
1916
parents_according_to_revision)
1918
def _check_for_inconsistent_revision_parents(self):
1919
inconsistencies = list(self._find_inconsistent_revision_parents())
1921
raise errors.BzrCheckError(
1922
"Revision knit has inconsistent parents.")
1924
def _get_sink(self):
1925
"""Return a sink for streaming into this repository."""
1926
return StreamSink(self)
1928
def _get_source(self, to_format):
1929
"""Return a source for streaming from this repository."""
1930
return StreamSource(self, to_format)
1933
class MetaDirVersionedFileRepository(MetaDirRepository,
1934
VersionedFileRepository):
1935
"""Repositories in a meta-dir, that work via versioned file objects."""
1937
def __init__(self, _format, a_bzrdir, control_files):
1938
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
1942
class MetaDirVersionedFileRepositoryFormat(MetaDirRepositoryFormat,
1943
VersionedFileRepositoryFormat):
1944
"""Base class for repository formats using versioned files in metadirs."""
1947
class StreamSink(object):
1948
"""An object that can insert a stream into a repository.
1950
This interface handles the complexity of reserialising inventories and
1951
revisions from different formats, and allows unidirectional insertion into
1952
stacked repositories without looking for the missing basis parents
1956
def __init__(self, target_repo):
1957
self.target_repo = target_repo
1959
def insert_stream(self, stream, src_format, resume_tokens):
1960
"""Insert a stream's content into the target repository.
1962
:param src_format: a bzr repository format.
1964
:return: a list of resume tokens and an iterable of keys additional
1965
items required before the insertion can be completed.
1967
self.target_repo.lock_write()
1970
self.target_repo.resume_write_group(resume_tokens)
1973
self.target_repo.start_write_group()
1976
# locked_insert_stream performs a commit|suspend.
1977
missing_keys = self.insert_stream_without_locking(stream,
1978
src_format, is_resume)
1980
# suspend the write group and tell the caller what we is
1981
# missing. We know we can suspend or else we would not have
1982
# entered this code path. (All repositories that can handle
1983
# missing keys can handle suspending a write group).
1984
write_group_tokens = self.target_repo.suspend_write_group()
1985
return write_group_tokens, missing_keys
1986
hint = self.target_repo.commit_write_group()
1987
to_serializer = self.target_repo._format._serializer
1988
src_serializer = src_format._serializer
1989
if (to_serializer != src_serializer and
1990
self.target_repo._format.pack_compresses):
1991
self.target_repo.pack(hint=hint)
1994
self.target_repo.abort_write_group(suppress_errors=True)
1997
self.target_repo.unlock()
1999
def insert_stream_without_locking(self, stream, src_format,
2001
"""Insert a stream's content into the target repository.
2003
This assumes that you already have a locked repository and an active
2006
:param src_format: a bzr repository format.
2007
:param is_resume: Passed down to get_missing_parent_inventories to
2008
indicate if we should be checking for missing texts at the same
2011
:return: A set of keys that are missing.
2013
if not self.target_repo.is_write_locked():
2014
raise errors.ObjectNotLocked(self)
2015
if not self.target_repo.is_in_write_group():
2016
raise errors.BzrError('you must already be in a write group')
2017
to_serializer = self.target_repo._format._serializer
2018
src_serializer = src_format._serializer
2020
if to_serializer == src_serializer:
2021
# If serializers match and the target is a pack repository, set the
2022
# write cache size on the new pack. This avoids poor performance
2023
# on transports where append is unbuffered (such as
2024
# RemoteTransport). This is safe to do because nothing should read
2025
# back from the target repository while a stream with matching
2026
# serialization is being inserted.
2027
# The exception is that a delta record from the source that should
2028
# be a fulltext may need to be expanded by the target (see
2029
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2030
# explicitly flush any buffered writes first in that rare case.
2032
new_pack = self.target_repo._pack_collection._new_pack
2033
except AttributeError:
2034
# Not a pack repository
2037
new_pack.set_write_cache_size(1024*1024)
2038
for substream_type, substream in stream:
2039
if 'stream' in debug.debug_flags:
2040
mutter('inserting substream: %s', substream_type)
2041
if substream_type == 'texts':
2042
self.target_repo.texts.insert_record_stream(substream)
2043
elif substream_type == 'inventories':
2044
if src_serializer == to_serializer:
2045
self.target_repo.inventories.insert_record_stream(
2048
self._extract_and_insert_inventories(
2049
substream, src_serializer)
2050
elif substream_type == 'inventory-deltas':
2051
self._extract_and_insert_inventory_deltas(
2052
substream, src_serializer)
2053
elif substream_type == 'chk_bytes':
2054
# XXX: This doesn't support conversions, as it assumes the
2055
# conversion was done in the fetch code.
2056
self.target_repo.chk_bytes.insert_record_stream(substream)
2057
elif substream_type == 'revisions':
2058
# This may fallback to extract-and-insert more often than
2059
# required if the serializers are different only in terms of
2061
if src_serializer == to_serializer:
2062
self.target_repo.revisions.insert_record_stream(substream)
2064
self._extract_and_insert_revisions(substream,
2066
elif substream_type == 'signatures':
2067
self.target_repo.signatures.insert_record_stream(substream)
2069
raise AssertionError('kaboom! %s' % (substream_type,))
2070
# Done inserting data, and the missing_keys calculations will try to
2071
# read back from the inserted data, so flush the writes to the new pack
2072
# (if this is pack format).
2073
if new_pack is not None:
2074
new_pack._write_data('', flush=True)
2075
# Find all the new revisions (including ones from resume_tokens)
2076
missing_keys = self.target_repo.get_missing_parent_inventories(
2077
check_for_missing_texts=is_resume)
2079
for prefix, versioned_file in (
2080
('texts', self.target_repo.texts),
2081
('inventories', self.target_repo.inventories),
2082
('revisions', self.target_repo.revisions),
2083
('signatures', self.target_repo.signatures),
2084
('chk_bytes', self.target_repo.chk_bytes),
2086
if versioned_file is None:
2088
# TODO: key is often going to be a StaticTuple object
2089
# I don't believe we can define a method by which
2090
# (prefix,) + StaticTuple will work, though we could
2091
# define a StaticTuple.sq_concat that would allow you to
2092
# pass in either a tuple or a StaticTuple as the second
2093
# object, so instead we could have:
2094
# StaticTuple(prefix) + key here...
2095
missing_keys.update((prefix,) + key for key in
2096
versioned_file.get_missing_compression_parent_keys())
2097
except NotImplementedError:
2098
# cannot even attempt suspending, and missing would have failed
2099
# during stream insertion.
2100
missing_keys = set()
2103
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2104
target_rich_root = self.target_repo._format.rich_root_data
2105
target_tree_refs = self.target_repo._format.supports_tree_reference
2106
for record in substream:
2107
# Insert the delta directly
2108
inventory_delta_bytes = record.get_bytes_as('fulltext')
2109
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2111
parse_result = deserialiser.parse_text_bytes(
2112
inventory_delta_bytes)
2113
except inventory_delta.IncompatibleInventoryDelta, err:
2114
mutter("Incompatible delta: %s", err.msg)
2115
raise errors.IncompatibleRevision(self.target_repo._format)
2116
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2117
revision_id = new_id
2118
parents = [key[0] for key in record.parents]
2119
self.target_repo.add_inventory_by_delta(
2120
basis_id, inv_delta, revision_id, parents)
2122
def _extract_and_insert_inventories(self, substream, serializer,
2124
"""Generate a new inventory versionedfile in target, converting data.
2126
The inventory is retrieved from the source, (deserializing it), and
2127
stored in the target (reserializing it in a different format).
2129
target_rich_root = self.target_repo._format.rich_root_data
2130
target_tree_refs = self.target_repo._format.supports_tree_reference
2131
for record in substream:
2132
# It's not a delta, so it must be a fulltext in the source
2133
# serializer's format.
2134
bytes = record.get_bytes_as('fulltext')
2135
revision_id = record.key[0]
2136
inv = serializer.read_inventory_from_string(bytes, revision_id)
2137
parents = [key[0] for key in record.parents]
2138
self.target_repo.add_inventory(revision_id, inv, parents)
2139
# No need to keep holding this full inv in memory when the rest of
2140
# the substream is likely to be all deltas.
2143
def _extract_and_insert_revisions(self, substream, serializer):
2144
for record in substream:
2145
bytes = record.get_bytes_as('fulltext')
2146
revision_id = record.key[0]
2147
rev = serializer.read_revision_from_string(bytes)
2148
if rev.revision_id != revision_id:
2149
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2150
self.target_repo.add_revision(revision_id, rev)
2153
if self.target_repo._format._fetch_reconcile:
2154
self.target_repo.reconcile()
2157
class StreamSource(object):
2158
"""A source of a stream for fetching between repositories."""
2160
def __init__(self, from_repository, to_format):
2161
"""Create a StreamSource streaming from from_repository."""
2162
self.from_repository = from_repository
2163
self.to_format = to_format
2164
self._record_counter = RecordCounter()
2166
def delta_on_metadata(self):
2167
"""Return True if delta's are permitted on metadata streams.
2169
That is on revisions and signatures.
2171
src_serializer = self.from_repository._format._serializer
2172
target_serializer = self.to_format._serializer
2173
return (self.to_format._fetch_uses_deltas and
2174
src_serializer == target_serializer)
2176
def _fetch_revision_texts(self, revs):
2177
# fetch signatures first and then the revision texts
2178
# may need to be a InterRevisionStore call here.
2179
from_sf = self.from_repository.signatures
2180
# A missing signature is just skipped.
2181
keys = [(rev_id,) for rev_id in revs]
2182
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2184
self.to_format._fetch_order,
2185
not self.to_format._fetch_uses_deltas))
2186
# If a revision has a delta, this is actually expanded inside the
2187
# insert_record_stream code now, which is an alternate fix for
2189
from_rf = self.from_repository.revisions
2190
revisions = from_rf.get_record_stream(
2192
self.to_format._fetch_order,
2193
not self.delta_on_metadata())
2194
return [('signatures', signatures), ('revisions', revisions)]
2196
def _generate_root_texts(self, revs):
2197
"""This will be called by get_stream between fetching weave texts and
2198
fetching the inventory weave.
2200
if self._rich_root_upgrade():
2201
return _mod_fetch.Inter1and2Helper(
2202
self.from_repository).generate_root_texts(revs)
2206
def get_stream(self, search):
2208
revs = search.get_keys()
2209
graph = self.from_repository.get_graph()
2210
revs = tsort.topo_sort(graph.get_parent_map(revs))
2211
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2213
for knit_kind, file_id, revisions in data_to_fetch:
2214
if knit_kind != phase:
2216
# Make a new progress bar for this phase
2217
if knit_kind == "file":
2218
# Accumulate file texts
2219
text_keys.extend([(file_id, revision) for revision in
2221
elif knit_kind == "inventory":
2222
# Now copy the file texts.
2223
from_texts = self.from_repository.texts
2224
yield ('texts', from_texts.get_record_stream(
2225
text_keys, self.to_format._fetch_order,
2226
not self.to_format._fetch_uses_deltas))
2227
# Cause an error if a text occurs after we have done the
2230
# Before we process the inventory we generate the root
2231
# texts (if necessary) so that the inventories references
2233
for _ in self._generate_root_texts(revs):
2235
# we fetch only the referenced inventories because we do not
2236
# know for unselected inventories whether all their required
2237
# texts are present in the other repository - it could be
2239
for info in self._get_inventory_stream(revs):
2241
elif knit_kind == "signatures":
2242
# Nothing to do here; this will be taken care of when
2243
# _fetch_revision_texts happens.
2245
elif knit_kind == "revisions":
2246
for record in self._fetch_revision_texts(revs):
2249
raise AssertionError("Unknown knit kind %r" % knit_kind)
2251
def get_stream_for_missing_keys(self, missing_keys):
2252
# missing keys can only occur when we are byte copying and not
2253
# translating (because translation means we don't send
2254
# unreconstructable deltas ever).
2256
keys['texts'] = set()
2257
keys['revisions'] = set()
2258
keys['inventories'] = set()
2259
keys['chk_bytes'] = set()
2260
keys['signatures'] = set()
2261
for key in missing_keys:
2262
keys[key[0]].add(key[1:])
2263
if len(keys['revisions']):
2264
# If we allowed copying revisions at this point, we could end up
2265
# copying a revision without copying its required texts: a
2266
# violation of the requirements for repository integrity.
2267
raise AssertionError(
2268
'cannot copy revisions to fill in missing deltas %s' % (
2269
keys['revisions'],))
2270
for substream_kind, keys in keys.iteritems():
2271
vf = getattr(self.from_repository, substream_kind)
2272
if vf is None and keys:
2273
raise AssertionError(
2274
"cannot fill in keys for a versioned file we don't"
2275
" have: %s needs %s" % (substream_kind, keys))
2277
# No need to stream something we don't have
2279
if substream_kind == 'inventories':
2280
# Some missing keys are genuinely ghosts, filter those out.
2281
present = self.from_repository.inventories.get_parent_map(keys)
2282
revs = [key[0] for key in present]
2283
# Get the inventory stream more-or-less as we do for the
2284
# original stream; there's no reason to assume that records
2285
# direct from the source will be suitable for the sink. (Think
2286
# e.g. 2a -> 1.9-rich-root).
2287
for info in self._get_inventory_stream(revs, missing=True):
2291
# Ask for full texts always so that we don't need more round trips
2292
# after this stream.
2293
# Some of the missing keys are genuinely ghosts, so filter absent
2294
# records. The Sink is responsible for doing another check to
2295
# ensure that ghosts don't introduce missing data for future
2297
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2298
self.to_format._fetch_order, True))
2299
yield substream_kind, stream
2301
def inventory_fetch_order(self):
2302
if self._rich_root_upgrade():
2303
return 'topological'
2305
return self.to_format._fetch_order
2307
def _rich_root_upgrade(self):
2308
return (not self.from_repository._format.rich_root_data and
2309
self.to_format.rich_root_data)
2311
def _get_inventory_stream(self, revision_ids, missing=False):
2312
from_format = self.from_repository._format
2313
if (from_format.supports_chks and self.to_format.supports_chks and
2314
from_format.network_name() == self.to_format.network_name()):
2315
raise AssertionError(
2316
"this case should be handled by GroupCHKStreamSource")
2317
elif 'forceinvdeltas' in debug.debug_flags:
2318
return self._get_convertable_inventory_stream(revision_ids,
2319
delta_versus_null=missing)
2320
elif from_format.network_name() == self.to_format.network_name():
2322
return self._get_simple_inventory_stream(revision_ids,
2324
elif (not from_format.supports_chks and not self.to_format.supports_chks
2325
and from_format._serializer == self.to_format._serializer):
2326
# Essentially the same format.
2327
return self._get_simple_inventory_stream(revision_ids,
2330
# Any time we switch serializations, we want to use an
2331
# inventory-delta based approach.
2332
return self._get_convertable_inventory_stream(revision_ids,
2333
delta_versus_null=missing)
2335
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2336
# NB: This currently reopens the inventory weave in source;
2337
# using a single stream interface instead would avoid this.
2338
from_weave = self.from_repository.inventories
2340
delta_closure = True
2342
delta_closure = not self.delta_on_metadata()
2343
yield ('inventories', from_weave.get_record_stream(
2344
[(rev_id,) for rev_id in revision_ids],
2345
self.inventory_fetch_order(), delta_closure))
2347
def _get_convertable_inventory_stream(self, revision_ids,
2348
delta_versus_null=False):
2349
# The two formats are sufficiently different that there is no fast
2350
# path, so we need to send just inventorydeltas, which any
2351
# sufficiently modern client can insert into any repository.
2352
# The StreamSink code expects to be able to
2353
# convert on the target, so we need to put bytes-on-the-wire that can
2354
# be converted. That means inventory deltas (if the remote is <1.19,
2355
# RemoteStreamSink will fallback to VFS to insert the deltas).
2356
yield ('inventory-deltas',
2357
self._stream_invs_as_deltas(revision_ids,
2358
delta_versus_null=delta_versus_null))
2360
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2361
"""Return a stream of inventory-deltas for the given rev ids.
2363
:param revision_ids: The list of inventories to transmit
2364
:param delta_versus_null: Don't try to find a minimal delta for this
2365
entry, instead compute the delta versus the NULL_REVISION. This
2366
effectively streams a complete inventory. Used for stuff like
2367
filling in missing parents, etc.
2369
from_repo = self.from_repository
2370
revision_keys = [(rev_id,) for rev_id in revision_ids]
2371
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2372
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2374
inventories = self.from_repository.iter_inventories(
2375
revision_ids, 'topological')
2376
format = from_repo._format
2377
invs_sent_so_far = set([_mod_revision.NULL_REVISION])
2378
inventory_cache = lru_cache.LRUCache(50)
2379
null_inventory = from_repo.revision_tree(
2380
_mod_revision.NULL_REVISION).inventory
2381
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2382
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2383
# repo back into a non-rich-root repo ought to be allowed)
2384
serializer = inventory_delta.InventoryDeltaSerializer(
2385
versioned_root=format.rich_root_data,
2386
tree_references=format.supports_tree_reference)
2387
for inv in inventories:
2388
key = (inv.revision_id,)
2389
parent_keys = parent_map.get(key, ())
2391
if not delta_versus_null and parent_keys:
2392
# The caller did not ask for complete inventories and we have
2393
# some parents that we can delta against. Make a delta against
2394
# each parent so that we can find the smallest.
2395
parent_ids = [parent_key[0] for parent_key in parent_keys]
2396
for parent_id in parent_ids:
2397
if parent_id not in invs_sent_so_far:
2398
# We don't know that the remote side has this basis, so
2401
if parent_id == _mod_revision.NULL_REVISION:
2402
parent_inv = null_inventory
2404
parent_inv = inventory_cache.get(parent_id, None)
2405
if parent_inv is None:
2406
parent_inv = from_repo.get_inventory(parent_id)
2407
candidate_delta = inv._make_delta(parent_inv)
2408
if (delta is None or
2409
len(delta) > len(candidate_delta)):
2410
delta = candidate_delta
2411
basis_id = parent_id
2413
# Either none of the parents ended up being suitable, or we
2414
# were asked to delta against NULL
2415
basis_id = _mod_revision.NULL_REVISION
2416
delta = inv._make_delta(null_inventory)
2417
invs_sent_so_far.add(inv.revision_id)
2418
inventory_cache[inv.revision_id] = inv
2419
delta_serialized = ''.join(
2420
serializer.delta_to_lines(basis_id, key[-1], delta))
2421
yield versionedfile.FulltextContentFactory(
2422
key, parent_keys, None, delta_serialized)
2425
class _VersionedFileChecker(object):
2427
def __init__(self, repository, text_key_references=None, ancestors=None):
2428
self.repository = repository
2429
self.text_index = self.repository._generate_text_key_index(
2430
text_key_references=text_key_references, ancestors=ancestors)
2432
def calculate_file_version_parents(self, text_key):
2433
"""Calculate the correct parents for a file version according to
2436
parent_keys = self.text_index[text_key]
2437
if parent_keys == [_mod_revision.NULL_REVISION]:
2439
return tuple(parent_keys)
2441
def check_file_version_parents(self, texts, progress_bar=None):
2442
"""Check the parents stored in a versioned file are correct.
2444
It also detects file versions that are not referenced by their
2445
corresponding revision's inventory.
2447
:returns: A tuple of (wrong_parents, dangling_file_versions).
2448
wrong_parents is a dict mapping {revision_id: (stored_parents,
2449
correct_parents)} for each revision_id where the stored parents
2450
are not correct. dangling_file_versions is a set of (file_id,
2451
revision_id) tuples for versions that are present in this versioned
2452
file, but not used by the corresponding inventory.
2454
local_progress = None
2455
if progress_bar is None:
2456
local_progress = ui.ui_factory.nested_progress_bar()
2457
progress_bar = local_progress
2459
return self._check_file_version_parents(texts, progress_bar)
2462
local_progress.finished()
2464
def _check_file_version_parents(self, texts, progress_bar):
2465
"""See check_file_version_parents."""
2467
self.file_ids = set([file_id for file_id, _ in
2468
self.text_index.iterkeys()])
2469
# text keys is now grouped by file_id
2470
n_versions = len(self.text_index)
2471
progress_bar.update(gettext('loading text store'), 0, n_versions)
2472
parent_map = self.repository.texts.get_parent_map(self.text_index)
2473
# On unlistable transports this could well be empty/error...
2474
text_keys = self.repository.texts.keys()
2475
unused_keys = frozenset(text_keys) - set(self.text_index)
2476
for num, key in enumerate(self.text_index.iterkeys()):
2477
progress_bar.update(gettext('checking text graph'), num, n_versions)
2478
correct_parents = self.calculate_file_version_parents(key)
2480
knit_parents = parent_map[key]
2481
except errors.RevisionNotPresent:
2484
if correct_parents != knit_parents:
2485
wrong_parents[key] = (knit_parents, correct_parents)
2486
return wrong_parents, unused_keys
2489
class InterVersionedFileRepository(InterRepository):
2491
_walk_to_common_revisions_batch_size = 50
2494
def fetch(self, revision_id=None, find_ghosts=False,
2496
"""Fetch the content required to construct revision_id.
2498
The content is copied from self.source to self.target.
2500
:param revision_id: if None all content is copied, if NULL_REVISION no
2504
if self.target._format.experimental:
2505
ui.ui_factory.show_user_warning('experimental_format_fetch',
2506
from_format=self.source._format,
2507
to_format=self.target._format)
2508
from bzrlib.fetch import RepoFetcher
2509
# See <https://launchpad.net/bugs/456077> asking for a warning here
2510
if self.source._format.network_name() != self.target._format.network_name():
2511
ui.ui_factory.show_user_warning('cross_format_fetch',
2512
from_format=self.source._format,
2513
to_format=self.target._format)
2514
f = RepoFetcher(to_repository=self.target,
2515
from_repository=self.source,
2516
last_revision=revision_id,
2517
fetch_spec=fetch_spec,
2518
find_ghosts=find_ghosts)
2520
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2521
"""Walk out from revision_ids in source to revisions target has.
2523
:param revision_ids: The start point for the search.
2524
:return: A set of revision ids.
2526
target_graph = self.target.get_graph()
2527
revision_ids = frozenset(revision_ids)
2529
all_wanted_revs = revision_ids.union(if_present_ids)
2531
all_wanted_revs = revision_ids
2532
missing_revs = set()
2533
source_graph = self.source.get_graph()
2534
# ensure we don't pay silly lookup costs.
2535
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2536
null_set = frozenset([_mod_revision.NULL_REVISION])
2537
searcher_exhausted = False
2541
# Iterate the searcher until we have enough next_revs
2542
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2544
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2545
next_revs.update(next_revs_part)
2546
ghosts.update(ghosts_part)
2547
except StopIteration:
2548
searcher_exhausted = True
2550
# If there are ghosts in the source graph, and the caller asked for
2551
# them, make sure that they are present in the target.
2552
# We don't care about other ghosts as we can't fetch them and
2553
# haven't been asked to.
2554
ghosts_to_check = set(revision_ids.intersection(ghosts))
2555
revs_to_get = set(next_revs).union(ghosts_to_check)
2557
have_revs = set(target_graph.get_parent_map(revs_to_get))
2558
# we always have NULL_REVISION present.
2559
have_revs = have_revs.union(null_set)
2560
# Check if the target is missing any ghosts we need.
2561
ghosts_to_check.difference_update(have_revs)
2563
# One of the caller's revision_ids is a ghost in both the
2564
# source and the target.
2565
raise errors.NoSuchRevision(
2566
self.source, ghosts_to_check.pop())
2567
missing_revs.update(next_revs - have_revs)
2568
# Because we may have walked past the original stop point, make
2569
# sure everything is stopped
2570
stop_revs = searcher.find_seen_ancestors(have_revs)
2571
searcher.stop_searching_any(stop_revs)
2572
if searcher_exhausted:
2574
return searcher.get_result()
2577
def search_missing_revision_ids(self,
2578
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
2579
find_ghosts=True, revision_ids=None, if_present_ids=None,
2581
"""Return the revision ids that source has that target does not.
2583
:param revision_id: only return revision ids included by this
2585
:param revision_ids: return revision ids included by these
2586
revision_ids. NoSuchRevision will be raised if any of these
2587
revisions are not present.
2588
:param if_present_ids: like revision_ids, but will not cause
2589
NoSuchRevision if any of these are absent, instead they will simply
2590
not be in the result. This is useful for e.g. finding revisions
2591
to fetch for tags, which may reference absent revisions.
2592
:param find_ghosts: If True find missing revisions in deep history
2593
rather than just finding the surface difference.
2594
:return: A bzrlib.graph.SearchResult.
2596
if symbol_versioning.deprecated_passed(revision_id):
2597
symbol_versioning.warn(
2598
'search_missing_revision_ids(revision_id=...) was '
2599
'deprecated in 2.4. Use revision_ids=[...] instead.',
2600
DeprecationWarning, stacklevel=2)
2601
if revision_ids is not None:
2602
raise AssertionError(
2603
'revision_ids is mutually exclusive with revision_id')
2604
if revision_id is not None:
2605
revision_ids = [revision_id]
2607
# stop searching at found target revisions.
2608
if not find_ghosts and (revision_ids is not None or if_present_ids is
2610
result = self._walk_to_common_revisions(revision_ids,
2611
if_present_ids=if_present_ids)
2614
result_set = result.get_keys()
2616
# generic, possibly worst case, slow code path.
2617
target_ids = set(self.target.all_revision_ids())
2618
source_ids = self._present_source_revisions_for(
2619
revision_ids, if_present_ids)
2620
result_set = set(source_ids).difference(target_ids)
2621
if limit is not None:
2622
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2623
result_set = set(itertools.islice(topo_ordered, limit))
2624
return self.source.revision_ids_to_search_result(result_set)
2626
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2627
"""Returns set of all revisions in ancestry of revision_ids present in
2630
:param revision_ids: if None, all revisions in source are returned.
2631
:param if_present_ids: like revision_ids, but if any/all of these are
2632
absent no error is raised.
2634
if revision_ids is not None or if_present_ids is not None:
2635
# First, ensure all specified revisions exist. Callers expect
2636
# NoSuchRevision when they pass absent revision_ids here.
2637
if revision_ids is None:
2638
revision_ids = set()
2639
if if_present_ids is None:
2640
if_present_ids = set()
2641
revision_ids = set(revision_ids)
2642
if_present_ids = set(if_present_ids)
2643
all_wanted_ids = revision_ids.union(if_present_ids)
2644
graph = self.source.get_graph()
2645
present_revs = set(graph.get_parent_map(all_wanted_ids))
2646
missing = revision_ids.difference(present_revs)
2648
raise errors.NoSuchRevision(self.source, missing.pop())
2649
found_ids = all_wanted_ids.intersection(present_revs)
2650
source_ids = [rev_id for (rev_id, parents) in
2651
graph.iter_ancestry(found_ids)
2652
if rev_id != _mod_revision.NULL_REVISION
2653
and parents is not None]
2655
source_ids = self.source.all_revision_ids()
2656
return set(source_ids)
2659
def _get_repo_format_to_test(self):
2663
def is_compatible(cls, source, target):
2664
# The default implementation is compatible with everything
2665
return (source._format.supports_full_versioned_files and
2666
target._format.supports_full_versioned_files)
2669
class InterDifferingSerializer(InterVersionedFileRepository):
2672
def _get_repo_format_to_test(self):
2676
def is_compatible(source, target):
2677
if not source._format.supports_full_versioned_files:
2679
if not target._format.supports_full_versioned_files:
2681
# This is redundant with format.check_conversion_target(), however that
2682
# raises an exception, and we just want to say "False" as in we won't
2683
# support converting between these formats.
2684
if 'IDS_never' in debug.debug_flags:
2686
if source.supports_rich_root() and not target.supports_rich_root():
2688
if (source._format.supports_tree_reference
2689
and not target._format.supports_tree_reference):
2691
if target._fallback_repositories and target._format.supports_chks:
2692
# IDS doesn't know how to copy CHKs for the parent inventories it
2693
# adds to stacked repos.
2695
if 'IDS_always' in debug.debug_flags:
2697
# Only use this code path for local source and target. IDS does far
2698
# too much IO (both bandwidth and roundtrips) over a network.
2699
if not source.bzrdir.transport.base.startswith('file:///'):
2701
if not target.bzrdir.transport.base.startswith('file:///'):
2705
def _get_trees(self, revision_ids, cache):
2707
for rev_id in revision_ids:
2709
possible_trees.append((rev_id, cache[rev_id]))
2711
# Not cached, but inventory might be present anyway.
2713
tree = self.source.revision_tree(rev_id)
2714
except errors.NoSuchRevision:
2715
# Nope, parent is ghost.
2718
cache[rev_id] = tree
2719
possible_trees.append((rev_id, tree))
2720
return possible_trees
2722
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2723
"""Get the best delta and base for this revision.
2725
:return: (basis_id, delta)
2728
# Generate deltas against each tree, to find the shortest.
2729
texts_possibly_new_in_tree = set()
2730
for basis_id, basis_tree in possible_trees:
2731
delta = tree.inventory._make_delta(basis_tree.inventory)
2732
for old_path, new_path, file_id, new_entry in delta:
2733
if new_path is None:
2734
# This file_id isn't present in the new rev, so we don't
2738
# Rich roots are handled elsewhere...
2740
kind = new_entry.kind
2741
if kind != 'directory' and kind != 'file':
2742
# No text record associated with this inventory entry.
2744
# This is a directory or file that has changed somehow.
2745
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2746
deltas.append((len(delta), basis_id, delta))
2748
return deltas[0][1:]
2750
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2751
"""Find all parent revisions that are absent, but for which the
2752
inventory is present, and copy those inventories.
2754
This is necessary to preserve correctness when the source is stacked
2755
without fallbacks configured. (Note that in cases like upgrade the
2756
source may be not have _fallback_repositories even though it is
2760
for parents in parent_map.values():
2761
parent_revs.update(parents)
2762
present_parents = self.source.get_parent_map(parent_revs)
2763
absent_parents = set(parent_revs).difference(present_parents)
2764
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2765
(rev_id,) for rev_id in absent_parents)
2766
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2767
for parent_tree in self.source.revision_trees(parent_inv_ids):
2768
current_revision_id = parent_tree.get_revision_id()
2769
parents_parents_keys = parent_invs_keys_for_stacking[
2770
(current_revision_id,)]
2771
parents_parents = [key[-1] for key in parents_parents_keys]
2772
basis_id = _mod_revision.NULL_REVISION
2773
basis_tree = self.source.revision_tree(basis_id)
2774
delta = parent_tree.inventory._make_delta(basis_tree.inventory)
2775
self.target.add_inventory_by_delta(
2776
basis_id, delta, current_revision_id, parents_parents)
2777
cache[current_revision_id] = parent_tree
2779
def _fetch_batch(self, revision_ids, basis_id, cache):
2780
"""Fetch across a few revisions.
2782
:param revision_ids: The revisions to copy
2783
:param basis_id: The revision_id of a tree that must be in cache, used
2784
as a basis for delta when no other base is available
2785
:param cache: A cache of RevisionTrees that we can use.
2786
:return: The revision_id of the last converted tree. The RevisionTree
2787
for it will be in cache
2789
# Walk though all revisions; get inventory deltas, copy referenced
2790
# texts that delta references, insert the delta, revision and
2792
root_keys_to_create = set()
2795
pending_revisions = []
2796
parent_map = self.source.get_parent_map(revision_ids)
2797
self._fetch_parent_invs_for_stacking(parent_map, cache)
2798
self.source._safe_to_return_from_cache = True
2799
for tree in self.source.revision_trees(revision_ids):
2800
# Find a inventory delta for this revision.
2801
# Find text entries that need to be copied, too.
2802
current_revision_id = tree.get_revision_id()
2803
parent_ids = parent_map.get(current_revision_id, ())
2804
parent_trees = self._get_trees(parent_ids, cache)
2805
possible_trees = list(parent_trees)
2806
if len(possible_trees) == 0:
2807
# There either aren't any parents, or the parents are ghosts,
2808
# so just use the last converted tree.
2809
possible_trees.append((basis_id, cache[basis_id]))
2810
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2812
revision = self.source.get_revision(current_revision_id)
2813
pending_deltas.append((basis_id, delta,
2814
current_revision_id, revision.parent_ids))
2815
if self._converting_to_rich_root:
2816
self._revision_id_to_root_id[current_revision_id] = \
2818
# Determine which texts are in present in this revision but not in
2819
# any of the available parents.
2820
texts_possibly_new_in_tree = set()
2821
for old_path, new_path, file_id, entry in delta:
2822
if new_path is None:
2823
# This file_id isn't present in the new rev
2827
if not self.target.supports_rich_root():
2828
# The target doesn't support rich root, so we don't
2831
if self._converting_to_rich_root:
2832
# This can't be copied normally, we have to insert
2834
root_keys_to_create.add((file_id, entry.revision))
2837
texts_possibly_new_in_tree.add((file_id, entry.revision))
2838
for basis_id, basis_tree in possible_trees:
2839
basis_inv = basis_tree.inventory
2840
for file_key in list(texts_possibly_new_in_tree):
2841
file_id, file_revision = file_key
2843
entry = basis_inv[file_id]
2844
except errors.NoSuchId:
2846
if entry.revision == file_revision:
2847
texts_possibly_new_in_tree.remove(file_key)
2848
text_keys.update(texts_possibly_new_in_tree)
2849
pending_revisions.append(revision)
2850
cache[current_revision_id] = tree
2851
basis_id = current_revision_id
2852
self.source._safe_to_return_from_cache = False
2854
from_texts = self.source.texts
2855
to_texts = self.target.texts
2856
if root_keys_to_create:
2857
root_stream = _mod_fetch._new_root_data_stream(
2858
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2860
to_texts.insert_record_stream(root_stream)
2861
to_texts.insert_record_stream(from_texts.get_record_stream(
2862
text_keys, self.target._format._fetch_order,
2863
not self.target._format._fetch_uses_deltas))
2864
# insert inventory deltas
2865
for delta in pending_deltas:
2866
self.target.add_inventory_by_delta(*delta)
2867
if self.target._fallback_repositories:
2868
# Make sure this stacked repository has all the parent inventories
2869
# for the new revisions that we are about to insert. We do this
2870
# before adding the revisions so that no revision is added until
2871
# all the inventories it may depend on are added.
2872
# Note that this is overzealous, as we may have fetched these in an
2875
revision_ids = set()
2876
for revision in pending_revisions:
2877
revision_ids.add(revision.revision_id)
2878
parent_ids.update(revision.parent_ids)
2879
parent_ids.difference_update(revision_ids)
2880
parent_ids.discard(_mod_revision.NULL_REVISION)
2881
parent_map = self.source.get_parent_map(parent_ids)
2882
# we iterate over parent_map and not parent_ids because we don't
2883
# want to try copying any revision which is a ghost
2884
for parent_tree in self.source.revision_trees(parent_map):
2885
current_revision_id = parent_tree.get_revision_id()
2886
parents_parents = parent_map[current_revision_id]
2887
possible_trees = self._get_trees(parents_parents, cache)
2888
if len(possible_trees) == 0:
2889
# There either aren't any parents, or the parents are
2890
# ghosts, so just use the last converted tree.
2891
possible_trees.append((basis_id, cache[basis_id]))
2892
basis_id, delta = self._get_delta_for_revision(parent_tree,
2893
parents_parents, possible_trees)
2894
self.target.add_inventory_by_delta(
2895
basis_id, delta, current_revision_id, parents_parents)
2896
# insert signatures and revisions
2897
for revision in pending_revisions:
2899
signature = self.source.get_signature_text(
2900
revision.revision_id)
2901
self.target.add_signature_text(revision.revision_id,
2903
except errors.NoSuchRevision:
2905
self.target.add_revision(revision.revision_id, revision)
2908
def _fetch_all_revisions(self, revision_ids, pb):
2909
"""Fetch everything for the list of revisions.
2911
:param revision_ids: The list of revisions to fetch. Must be in
2913
:param pb: A ProgressTask
2916
basis_id, basis_tree = self._get_basis(revision_ids[0])
2918
cache = lru_cache.LRUCache(100)
2919
cache[basis_id] = basis_tree
2920
del basis_tree # We don't want to hang on to it here
2924
for offset in range(0, len(revision_ids), batch_size):
2925
self.target.start_write_group()
2927
pb.update(gettext('Transferring revisions'), offset,
2929
batch = revision_ids[offset:offset+batch_size]
2930
basis_id = self._fetch_batch(batch, basis_id, cache)
2932
self.source._safe_to_return_from_cache = False
2933
self.target.abort_write_group()
2936
hint = self.target.commit_write_group()
2939
if hints and self.target._format.pack_compresses:
2940
self.target.pack(hint=hints)
2941
pb.update(gettext('Transferring revisions'), len(revision_ids),
2945
def fetch(self, revision_id=None, find_ghosts=False,
2947
"""See InterRepository.fetch()."""
2948
if fetch_spec is not None:
2949
revision_ids = fetch_spec.get_keys()
2952
if self.source._format.experimental:
2953
ui.ui_factory.show_user_warning('experimental_format_fetch',
2954
from_format=self.source._format,
2955
to_format=self.target._format)
2956
if (not self.source.supports_rich_root()
2957
and self.target.supports_rich_root()):
2958
self._converting_to_rich_root = True
2959
self._revision_id_to_root_id = {}
2961
self._converting_to_rich_root = False
2962
# See <https://launchpad.net/bugs/456077> asking for a warning here
2963
if self.source._format.network_name() != self.target._format.network_name():
2964
ui.ui_factory.show_user_warning('cross_format_fetch',
2965
from_format=self.source._format,
2966
to_format=self.target._format)
2967
if revision_ids is None:
2969
search_revision_ids = [revision_id]
2971
search_revision_ids = None
2972
revision_ids = self.target.search_missing_revision_ids(self.source,
2973
revision_ids=search_revision_ids,
2974
find_ghosts=find_ghosts).get_keys()
2975
if not revision_ids:
2977
revision_ids = tsort.topo_sort(
2978
self.source.get_graph().get_parent_map(revision_ids))
2979
if not revision_ids:
2981
# Walk though all revisions; get inventory deltas, copy referenced
2982
# texts that delta references, insert the delta, revision and
2984
pb = ui.ui_factory.nested_progress_bar()
2986
self._fetch_all_revisions(revision_ids, pb)
2989
return len(revision_ids), 0
2991
def _get_basis(self, first_revision_id):
2992
"""Get a revision and tree which exists in the target.
2994
This assumes that first_revision_id is selected for transmission
2995
because all other ancestors are already present. If we can't find an
2996
ancestor we fall back to NULL_REVISION since we know that is safe.
2998
:return: (basis_id, basis_tree)
3000
first_rev = self.source.get_revision(first_revision_id)
3002
basis_id = first_rev.parent_ids[0]
3003
# only valid as a basis if the target has it
3004
self.target.get_revision(basis_id)
3005
# Try to get a basis tree - if it's a ghost it will hit the
3006
# NoSuchRevision case.
3007
basis_tree = self.source.revision_tree(basis_id)
3008
except (IndexError, errors.NoSuchRevision):
3009
basis_id = _mod_revision.NULL_REVISION
3010
basis_tree = self.source.revision_tree(basis_id)
3011
return basis_id, basis_tree
3014
class InterSameDataRepository(InterVersionedFileRepository):
3015
"""Code for converting between repositories that represent the same data.
3017
Data format and model must match for this to work.
3021
def _get_repo_format_to_test(self):
3022
"""Repository format for testing with.
3024
InterSameData can pull from subtree to subtree and from non-subtree to
3025
non-subtree, so we test this with the richest repository format.
3027
from bzrlib.repofmt import knitrepo
3028
return knitrepo.RepositoryFormatKnit3()
3031
def is_compatible(source, target):
3033
InterRepository._same_model(source, target) and
3034
source._format.supports_full_versioned_files and
3035
target._format.supports_full_versioned_files)
3038
InterRepository.register_optimiser(InterVersionedFileRepository)
3039
InterRepository.register_optimiser(InterDifferingSerializer)
3040
InterRepository.register_optimiser(InterSameDataRepository)
3043
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3044
"""Install all revision data into a repository.
3046
Accepts an iterable of revision, tree, signature tuples. The signature
3049
repository.start_write_group()
3051
inventory_cache = lru_cache.LRUCache(10)
3052
for n, (revision, revision_tree, signature) in enumerate(iterable):
3053
_install_revision(repository, revision, revision_tree, signature,
3056
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3058
repository.abort_write_group()
3061
repository.commit_write_group()
3064
def _install_revision(repository, rev, revision_tree, signature,
3066
"""Install all revision data into a repository."""
3067
present_parents = []
3069
for p_id in rev.parent_ids:
3070
if repository.has_revision(p_id):
3071
present_parents.append(p_id)
3072
parent_trees[p_id] = repository.revision_tree(p_id)
3074
parent_trees[p_id] = repository.revision_tree(
3075
_mod_revision.NULL_REVISION)
3077
inv = revision_tree.inventory
3078
entries = inv.iter_entries()
3079
# backwards compatibility hack: skip the root id.
3080
if not repository.supports_rich_root():
3081
path, root = entries.next()
3082
if root.revision != rev.revision_id:
3083
raise errors.IncompatibleRevision(repr(repository))
3085
for path, ie in entries:
3086
text_keys[(ie.file_id, ie.revision)] = ie
3087
text_parent_map = repository.texts.get_parent_map(text_keys)
3088
missing_texts = set(text_keys) - set(text_parent_map)
3089
# Add the texts that are not already present
3090
for text_key in missing_texts:
3091
ie = text_keys[text_key]
3093
# FIXME: TODO: The following loop overlaps/duplicates that done by
3094
# commit to determine parents. There is a latent/real bug here where
3095
# the parents inserted are not those commit would do - in particular
3096
# they are not filtered by heads(). RBC, AB
3097
for revision, tree in parent_trees.iteritems():
3098
if not tree.has_id(ie.file_id):
3100
parent_id = tree.get_file_revision(ie.file_id)
3101
if parent_id in text_parents:
3103
text_parents.append((ie.file_id, parent_id))
3104
lines = revision_tree.get_file(ie.file_id).readlines()
3105
repository.texts.add_lines(text_key, text_parents, lines)
3107
# install the inventory
3108
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3109
# Cache this inventory
3110
inventory_cache[rev.revision_id] = inv
3112
basis_inv = inventory_cache[rev.parent_ids[0]]
3114
repository.add_inventory(rev.revision_id, inv, present_parents)
3116
delta = inv._make_delta(basis_inv)
3117
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3118
rev.revision_id, present_parents)
3120
repository.add_inventory(rev.revision_id, inv, present_parents)
3121
except errors.RevisionAlreadyPresent:
3123
if signature is not None:
3124
repository.add_signature_text(rev.revision_id, signature)
3125
repository.add_revision(rev.revision_id, rev, inv)
3128
def install_revision(repository, rev, revision_tree):
3129
"""Install all revision data into a repository."""
3130
install_revisions(repository, [(rev, revision_tree, None)])