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
84
# Should commit add an inventory, or an inventory delta to the repository.
85
_commit_inv_deltas = True
86
# What order should fetch operations request streams in?
87
# The default is unordered as that is the cheapest for an origin to
89
_fetch_order = 'unordered'
90
# Does this repository format use deltas that can be fetched as-deltas ?
91
# (E.g. knits, where the knit deltas can be transplanted intact.
92
# We default to False, which will ensure that enough data to get
93
# a full text out of any fetch stream will be grabbed.
94
_fetch_uses_deltas = False
97
class VersionedFileCommitBuilder(CommitBuilder):
98
"""Commit builder implementation for versioned files based repositories.
101
# this commit builder supports the record_entry_contents interface
102
supports_record_entry_contents = True
104
# the default CommitBuilder does not manage trees whose root is versioned.
105
_versioned_root = False
107
def __init__(self, repository, parents, config, timestamp=None,
108
timezone=None, committer=None, revprops=None,
109
revision_id=None, lossy=False):
110
super(VersionedFileCommitBuilder, self).__init__(repository,
111
parents, config, timestamp, timezone, committer, revprops,
114
basis_id = self.parents[0]
116
basis_id = _mod_revision.NULL_REVISION
117
self.basis_delta_revision = basis_id
118
self.new_inventory = Inventory(None)
119
self._basis_delta = []
120
self.__heads = graph.HeadsCache(repository.get_graph()).heads
121
# memo'd check for no-op commits.
122
self._any_changes = False
123
# API compatibility, older code that used CommitBuilder did not call
124
# .record_delete(), which means the delta that is computed would not be
125
# valid. Callers that will call record_delete() should call
126
# .will_record_deletes() to indicate that.
127
self._recording_deletes = False
129
def will_record_deletes(self):
130
"""Tell the commit builder that deletes are being notified.
132
This enables the accumulation of an inventory delta; for the resulting
133
commit to be valid, deletes against the basis MUST be recorded via
134
builder.record_delete().
136
self._recording_deletes = True
138
def any_changes(self):
139
"""Return True if any entries were changed.
141
This includes merge-only changes. It is the core for the --unchanged
144
:return: True if any changes have occured.
146
return self._any_changes
148
def _ensure_fallback_inventories(self):
149
"""Ensure that appropriate inventories are available.
151
This only applies to repositories that are stacked, and is about
152
enusring the stacking invariants. Namely, that for any revision that is
153
present, we either have all of the file content, or we have the parent
154
inventory and the delta file content.
156
if not self.repository._fallback_repositories:
158
if not self.repository._format.supports_chks:
159
raise errors.BzrError("Cannot commit directly to a stacked branch"
160
" in pre-2a formats. See "
161
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
162
# This is a stacked repo, we need to make sure we have the parent
163
# inventories for the parents.
164
parent_keys = [(p,) for p in self.parents]
165
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
166
missing_parent_keys = set([pk for pk in parent_keys
167
if pk not in parent_map])
168
fallback_repos = list(reversed(self.repository._fallback_repositories))
169
missing_keys = [('inventories', pk[0])
170
for pk in missing_parent_keys]
172
while missing_keys and fallback_repos:
173
fallback_repo = fallback_repos.pop()
174
source = fallback_repo._get_source(self.repository._format)
175
sink = self.repository._get_sink()
176
stream = source.get_stream_for_missing_keys(missing_keys)
177
missing_keys = sink.insert_stream_without_locking(stream,
178
self.repository._format)
180
raise errors.BzrError('Unable to fill in parent inventories for a'
183
def commit(self, message):
184
"""Make the actual commit.
186
:return: The revision id of the recorded revision.
188
self._validate_unicode_text(message, 'commit message')
189
rev = _mod_revision.Revision(
190
timestamp=self._timestamp,
191
timezone=self._timezone,
192
committer=self._committer,
194
inventory_sha1=self.inv_sha1,
195
revision_id=self._new_revision_id,
196
properties=self._revprops)
197
rev.parent_ids = self.parents
198
self.repository.add_revision(self._new_revision_id, rev,
199
self.new_inventory, self._config)
200
self._ensure_fallback_inventories()
201
self.repository.commit_write_group()
202
return self._new_revision_id
205
"""Abort the commit that is being built.
207
self.repository.abort_write_group()
209
def revision_tree(self):
210
"""Return the tree that was just committed.
212
After calling commit() this can be called to get a
213
RevisionTree representing the newly committed tree. This is
214
preferred to calling Repository.revision_tree() because that may
215
require deserializing the inventory, while we already have a copy in
218
if self.new_inventory is None:
219
self.new_inventory = self.repository.get_inventory(
220
self._new_revision_id)
221
return InventoryRevisionTree(self.repository, self.new_inventory,
222
self._new_revision_id)
224
def finish_inventory(self):
225
"""Tell the builder that the inventory is finished.
227
:return: The inventory id in the repository, which can be used with
228
repository.get_inventory.
230
if self.new_inventory is None:
231
# an inventory delta was accumulated without creating a new
233
basis_id = self.basis_delta_revision
234
# We ignore the 'inventory' returned by add_inventory_by_delta
235
# because self.new_inventory is used to hint to the rest of the
236
# system what code path was taken
237
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
238
basis_id, self._basis_delta, self._new_revision_id,
241
if self.new_inventory.root is None:
242
raise AssertionError('Root entry should be supplied to'
243
' record_entry_contents, as of bzr 0.10.')
244
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
245
self.new_inventory.revision_id = self._new_revision_id
246
self.inv_sha1 = self.repository.add_inventory(
247
self._new_revision_id,
251
return self._new_revision_id
253
def _check_root(self, ie, parent_invs, tree):
254
"""Helper for record_entry_contents.
256
:param ie: An entry being added.
257
:param parent_invs: The inventories of the parent revisions of the
259
:param tree: The tree that is being committed.
261
# In this revision format, root entries have no knit or weave When
262
# serializing out to disk and back in root.revision is always
264
ie.revision = self._new_revision_id
266
def _require_root_change(self, tree):
267
"""Enforce an appropriate root object change.
269
This is called once when record_iter_changes is called, if and only if
270
the root was not in the delta calculated by record_iter_changes.
272
:param tree: The tree which is being committed.
274
if len(self.parents) == 0:
275
raise errors.RootMissing()
276
entry = entry_factory['directory'](tree.path2id(''), '',
278
entry.revision = self._new_revision_id
279
self._basis_delta.append(('', '', entry.file_id, entry))
281
def _get_delta(self, ie, basis_inv, path):
282
"""Get a delta against the basis inventory for ie."""
283
if not basis_inv.has_id(ie.file_id):
285
result = (None, path, ie.file_id, ie)
286
self._basis_delta.append(result)
288
elif ie != basis_inv[ie.file_id]:
290
# TODO: avoid tis id2path call.
291
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
292
self._basis_delta.append(result)
298
def _heads(self, file_id, revision_ids):
299
"""Calculate the graph heads for revision_ids in the graph of file_id.
301
This can use either a per-file graph or a global revision graph as we
302
have an identity relationship between the two graphs.
304
return self.__heads(revision_ids)
306
def get_basis_delta(self):
307
"""Return the complete inventory delta versus the basis inventory.
309
This has been built up with the calls to record_delete and
310
record_entry_contents. The client must have already called
311
will_record_deletes() to indicate that they will be generating a
314
:return: An inventory delta, suitable for use with apply_delta, or
315
Repository.add_inventory_by_delta, etc.
317
if not self._recording_deletes:
318
raise AssertionError("recording deletes not activated.")
319
return self._basis_delta
321
def record_delete(self, path, file_id):
322
"""Record that a delete occured against a basis tree.
324
This is an optional API - when used it adds items to the basis_delta
325
being accumulated by the commit builder. It cannot be called unless the
326
method will_record_deletes() has been called to inform the builder that
327
a delta is being supplied.
329
:param path: The path of the thing deleted.
330
:param file_id: The file id that was deleted.
332
if not self._recording_deletes:
333
raise AssertionError("recording deletes not activated.")
334
delta = (path, None, file_id, None)
335
self._basis_delta.append(delta)
336
self._any_changes = True
339
def record_entry_contents(self, ie, parent_invs, path, tree,
341
"""Record the content of ie from tree into the commit if needed.
343
Side effect: sets ie.revision when unchanged
345
:param ie: An inventory entry present in the commit.
346
:param parent_invs: The inventories of the parent revisions of the
348
:param path: The path the entry is at in the tree.
349
:param tree: The tree which contains this entry and should be used to
351
:param content_summary: Summary data from the tree about the paths
352
content - stat, length, exec, sha/link target. This is only
353
accessed when the entry has a revision of None - that is when it is
354
a candidate to commit.
355
:return: A tuple (change_delta, version_recorded, fs_hash).
356
change_delta is an inventory_delta change for this entry against
357
the basis tree of the commit, or None if no change occured against
359
version_recorded is True if a new version of the entry has been
360
recorded. For instance, committing a merge where a file was only
361
changed on the other side will return (delta, False).
362
fs_hash is either None, or the hash details for the path (currently
363
a tuple of the contents sha1 and the statvalue returned by
364
tree.get_file_with_stat()).
366
if self.new_inventory.root is None:
367
if ie.parent_id is not None:
368
raise errors.RootMissing()
369
self._check_root(ie, parent_invs, tree)
370
if ie.revision is None:
371
kind = content_summary[0]
373
# ie is carried over from a prior commit
375
# XXX: repository specific check for nested tree support goes here - if
376
# the repo doesn't want nested trees we skip it ?
377
if (kind == 'tree-reference' and
378
not self.repository._format.supports_tree_reference):
379
# mismatch between commit builder logic and repository:
380
# this needs the entry creation pushed down into the builder.
381
raise NotImplementedError('Missing repository subtree support.')
382
self.new_inventory.add(ie)
384
# TODO: slow, take it out of the inner loop.
386
basis_inv = parent_invs[0]
388
basis_inv = Inventory(root_id=None)
390
# ie.revision is always None if the InventoryEntry is considered
391
# for committing. We may record the previous parents revision if the
392
# content is actually unchanged against a sole head.
393
if ie.revision is not None:
394
if not self._versioned_root and path == '':
395
# repositories that do not version the root set the root's
396
# revision to the new commit even when no change occurs (more
397
# specifically, they do not record a revision on the root; and
398
# the rev id is assigned to the root during deserialisation -
399
# this masks when a change may have occurred against the basis.
400
# To match this we always issue a delta, because the revision
401
# of the root will always be changing.
402
if basis_inv.has_id(ie.file_id):
403
delta = (basis_inv.id2path(ie.file_id), path,
407
delta = (None, path, ie.file_id, ie)
408
self._basis_delta.append(delta)
409
return delta, False, None
411
# we don't need to commit this, because the caller already
412
# determined that an existing revision of this file is
413
# appropriate. If it's not being considered for committing then
414
# it and all its parents to the root must be unaltered so
415
# no-change against the basis.
416
if ie.revision == self._new_revision_id:
417
raise AssertionError("Impossible situation, a skipped "
418
"inventory entry (%r) claims to be modified in this "
419
"commit (%r).", (ie, self._new_revision_id))
420
return None, False, None
421
# XXX: Friction: parent_candidates should return a list not a dict
422
# so that we don't have to walk the inventories again.
423
parent_candidate_entries = ie.parent_candidates(parent_invs)
424
head_set = self._heads(ie.file_id, parent_candidate_entries.keys())
426
for inv in parent_invs:
427
if inv.has_id(ie.file_id):
428
old_rev = inv[ie.file_id].revision
429
if old_rev in head_set:
430
heads.append(inv[ie.file_id].revision)
431
head_set.remove(inv[ie.file_id].revision)
434
# now we check to see if we need to write a new record to the
436
# We write a new entry unless there is one head to the ancestors, and
437
# the kind-derived content is unchanged.
439
# Cheapest check first: no ancestors, or more the one head in the
440
# ancestors, we write a new node.
444
# There is a single head, look it up for comparison
445
parent_entry = parent_candidate_entries[heads[0]]
446
# if the non-content specific data has changed, we'll be writing a
448
if (parent_entry.parent_id != ie.parent_id or
449
parent_entry.name != ie.name):
451
# now we need to do content specific checks:
453
# if the kind changed the content obviously has
454
if kind != parent_entry.kind:
456
# Stat cache fingerprint feedback for the caller - None as we usually
457
# don't generate one.
460
if content_summary[2] is None:
461
raise ValueError("Files must not have executable = None")
463
# We can't trust a check of the file length because of content
465
if (# if the exec bit has changed we have to store:
466
parent_entry.executable != content_summary[2]):
468
elif parent_entry.text_sha1 == content_summary[3]:
469
# all meta and content is unchanged (using a hash cache
470
# hit to check the sha)
471
ie.revision = parent_entry.revision
472
ie.text_size = parent_entry.text_size
473
ie.text_sha1 = parent_entry.text_sha1
474
ie.executable = parent_entry.executable
475
return self._get_delta(ie, basis_inv, path), False, None
477
# Either there is only a hash change(no hash cache entry,
478
# or same size content change), or there is no change on
480
# Provide the parent's hash to the store layer, so that the
481
# content is unchanged we will not store a new node.
482
nostore_sha = parent_entry.text_sha1
484
# We want to record a new node regardless of the presence or
485
# absence of a content change in the file.
487
ie.executable = content_summary[2]
488
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
490
text = file_obj.read()
494
ie.text_sha1, ie.text_size = self._add_text_to_weave(
495
ie.file_id, text, heads, nostore_sha)
496
# Let the caller know we generated a stat fingerprint.
497
fingerprint = (ie.text_sha1, stat_value)
498
except errors.ExistingContent:
499
# Turns out that the file content was unchanged, and we were
500
# only going to store a new node if it was changed. Carry over
502
ie.revision = parent_entry.revision
503
ie.text_size = parent_entry.text_size
504
ie.text_sha1 = parent_entry.text_sha1
505
ie.executable = parent_entry.executable
506
return self._get_delta(ie, basis_inv, path), False, None
507
elif kind == 'directory':
509
# all data is meta here, nothing specific to directory, so
511
ie.revision = parent_entry.revision
512
return self._get_delta(ie, basis_inv, path), False, None
513
self._add_text_to_weave(ie.file_id, '', heads, None)
514
elif kind == 'symlink':
515
current_link_target = content_summary[3]
517
# symlink target is not generic metadata, check if it has
519
if current_link_target != parent_entry.symlink_target:
522
# unchanged, carry over.
523
ie.revision = parent_entry.revision
524
ie.symlink_target = parent_entry.symlink_target
525
return self._get_delta(ie, basis_inv, path), False, None
526
ie.symlink_target = current_link_target
527
self._add_text_to_weave(ie.file_id, '', heads, None)
528
elif kind == 'tree-reference':
530
if content_summary[3] != parent_entry.reference_revision:
533
# unchanged, carry over.
534
ie.reference_revision = parent_entry.reference_revision
535
ie.revision = parent_entry.revision
536
return self._get_delta(ie, basis_inv, path), False, None
537
ie.reference_revision = content_summary[3]
538
if ie.reference_revision is None:
539
raise AssertionError("invalid content_summary for nested tree: %r"
540
% (content_summary,))
541
self._add_text_to_weave(ie.file_id, '', heads, None)
543
raise NotImplementedError('unknown kind')
544
ie.revision = self._new_revision_id
545
# The initial commit adds a root directory, but this in itself is not
546
# a worthwhile commit.
547
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
549
self._any_changes = True
550
return self._get_delta(ie, basis_inv, path), True, fingerprint
552
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
553
_entry_factory=entry_factory):
554
"""Record a new tree via iter_changes.
556
:param tree: The tree to obtain text contents from for changed objects.
557
:param basis_revision_id: The revision id of the tree the iter_changes
558
has been generated against. Currently assumed to be the same
559
as self.parents[0] - if it is not, errors may occur.
560
:param iter_changes: An iter_changes iterator with the changes to apply
561
to basis_revision_id. The iterator must not include any items with
562
a current kind of None - missing items must be either filtered out
563
or errored-on before record_iter_changes sees the item.
564
:param _entry_factory: Private method to bind entry_factory locally for
566
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
569
# Create an inventory delta based on deltas between all the parents and
570
# deltas between all the parent inventories. We use inventory delta's
571
# between the inventory objects because iter_changes masks
572
# last-changed-field only changes.
574
# file_id -> change map, change is fileid, paths, changed, versioneds,
575
# parents, names, kinds, executables
577
# {file_id -> revision_id -> inventory entry, for entries in parent
578
# trees that are not parents[0]
582
revtrees = list(self.repository.revision_trees(self.parents))
583
except errors.NoSuchRevision:
584
# one or more ghosts, slow path.
586
for revision_id in self.parents:
588
revtrees.append(self.repository.revision_tree(revision_id))
589
except errors.NoSuchRevision:
591
basis_revision_id = _mod_revision.NULL_REVISION
593
revtrees.append(self.repository.revision_tree(
594
_mod_revision.NULL_REVISION))
595
# The basis inventory from a repository
597
basis_inv = revtrees[0].inventory
599
basis_inv = self.repository.revision_tree(
600
_mod_revision.NULL_REVISION).inventory
601
if len(self.parents) > 0:
602
if basis_revision_id != self.parents[0] and not ghost_basis:
604
"arbitrary basis parents not yet supported with merges")
605
for revtree in revtrees[1:]:
606
for change in revtree.inventory._make_delta(basis_inv):
607
if change[1] is None:
608
# Not present in this parent.
610
if change[2] not in merged_ids:
611
if change[0] is not None:
612
basis_entry = basis_inv[change[2]]
613
merged_ids[change[2]] = [
615
basis_entry.revision,
618
parent_entries[change[2]] = {
620
basis_entry.revision:basis_entry,
622
change[3].revision:change[3],
625
merged_ids[change[2]] = [change[3].revision]
626
parent_entries[change[2]] = {change[3].revision:change[3]}
628
merged_ids[change[2]].append(change[3].revision)
629
parent_entries[change[2]][change[3].revision] = change[3]
632
# Setup the changes from the tree:
633
# changes maps file_id -> (change, [parent revision_ids])
635
for change in iter_changes:
636
# This probably looks up in basis_inv way to much.
637
if change[1][0] is not None:
638
head_candidate = [basis_inv[change[0]].revision]
641
changes[change[0]] = change, merged_ids.get(change[0],
643
unchanged_merged = set(merged_ids) - set(changes)
644
# Extend the changes dict with synthetic changes to record merges of
646
for file_id in unchanged_merged:
647
# Record a merged version of these items that did not change vs the
648
# basis. This can be either identical parallel changes, or a revert
649
# of a specific file after a merge. The recorded content will be
650
# that of the current tree (which is the same as the basis), but
651
# the per-file graph will reflect a merge.
652
# NB:XXX: We are reconstructing path information we had, this
653
# should be preserved instead.
654
# inv delta change: (file_id, (path_in_source, path_in_target),
655
# changed_content, versioned, parent, name, kind,
658
basis_entry = basis_inv[file_id]
659
except errors.NoSuchId:
660
# a change from basis->some_parents but file_id isn't in basis
661
# so was new in the merge, which means it must have changed
662
# from basis -> current, and as it hasn't the add was reverted
663
# by the user. So we discard this change.
667
(basis_inv.id2path(file_id), tree.id2path(file_id)),
669
(basis_entry.parent_id, basis_entry.parent_id),
670
(basis_entry.name, basis_entry.name),
671
(basis_entry.kind, basis_entry.kind),
672
(basis_entry.executable, basis_entry.executable))
673
changes[file_id] = (change, merged_ids[file_id])
674
# changes contains tuples with the change and a set of inventory
675
# candidates for the file.
677
# old_path, new_path, file_id, new_inventory_entry
678
seen_root = False # Is the root in the basis delta?
679
inv_delta = self._basis_delta
680
modified_rev = self._new_revision_id
681
for change, head_candidates in changes.values():
682
if change[3][1]: # versioned in target.
683
# Several things may be happening here:
684
# We may have a fork in the per-file graph
685
# - record a change with the content from tree
686
# We may have a change against < all trees
687
# - carry over the tree that hasn't changed
688
# We may have a change against all trees
689
# - record the change with the content from tree
692
entry = _entry_factory[kind](file_id, change[5][1],
694
head_set = self._heads(change[0], set(head_candidates))
697
for head_candidate in head_candidates:
698
if head_candidate in head_set:
699
heads.append(head_candidate)
700
head_set.remove(head_candidate)
703
# Could be a carry-over situation:
704
parent_entry_revs = parent_entries.get(file_id, None)
705
if parent_entry_revs:
706
parent_entry = parent_entry_revs.get(heads[0], None)
709
if parent_entry is None:
710
# The parent iter_changes was called against is the one
711
# that is the per-file head, so any change is relevant
712
# iter_changes is valid.
713
carry_over_possible = False
715
# could be a carry over situation
716
# A change against the basis may just indicate a merge,
717
# we need to check the content against the source of the
718
# merge to determine if it was changed after the merge
720
if (parent_entry.kind != entry.kind or
721
parent_entry.parent_id != entry.parent_id or
722
parent_entry.name != entry.name):
723
# Metadata common to all entries has changed
724
# against per-file parent
725
carry_over_possible = False
727
carry_over_possible = True
728
# per-type checks for changes against the parent_entry
731
# Cannot be a carry-over situation
732
carry_over_possible = False
733
# Populate the entry in the delta
735
# XXX: There is still a small race here: If someone reverts the content of a file
736
# after iter_changes examines and decides it has changed,
737
# we will unconditionally record a new version even if some
738
# other process reverts it while commit is running (with
739
# the revert happening after iter_changes did its
742
entry.executable = True
744
entry.executable = False
745
if (carry_over_possible and
746
parent_entry.executable == entry.executable):
747
# Check the file length, content hash after reading
749
nostore_sha = parent_entry.text_sha1
752
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
754
text = file_obj.read()
758
entry.text_sha1, entry.text_size = self._add_text_to_weave(
759
file_id, text, heads, nostore_sha)
760
yield file_id, change[1][1], (entry.text_sha1, stat_value)
761
except errors.ExistingContent:
762
# No content change against a carry_over parent
763
# Perhaps this should also yield a fs hash update?
765
entry.text_size = parent_entry.text_size
766
entry.text_sha1 = parent_entry.text_sha1
767
elif kind == 'symlink':
769
entry.symlink_target = tree.get_symlink_target(file_id)
770
if (carry_over_possible and
771
parent_entry.symlink_target == entry.symlink_target):
774
self._add_text_to_weave(change[0], '', heads, None)
775
elif kind == 'directory':
776
if carry_over_possible:
779
# Nothing to set on the entry.
780
# XXX: split into the Root and nonRoot versions.
781
if change[1][1] != '' or self.repository.supports_rich_root():
782
self._add_text_to_weave(change[0], '', heads, None)
783
elif kind == 'tree-reference':
784
if not self.repository._format.supports_tree_reference:
785
# This isn't quite sane as an error, but we shouldn't
786
# ever see this code path in practice: tree's don't
787
# permit references when the repo doesn't support tree
789
raise errors.UnsupportedOperation(tree.add_reference,
791
reference_revision = tree.get_reference_revision(change[0])
792
entry.reference_revision = reference_revision
793
if (carry_over_possible and
794
parent_entry.reference_revision == reference_revision):
797
self._add_text_to_weave(change[0], '', heads, None)
799
raise AssertionError('unknown kind %r' % kind)
801
entry.revision = modified_rev
803
entry.revision = parent_entry.revision
806
new_path = change[1][1]
807
inv_delta.append((change[1][0], new_path, change[0], entry))
810
self.new_inventory = None
811
# The initial commit adds a root directory, but this in itself is not
812
# a worthwhile commit.
813
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
814
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
815
# This should perhaps be guarded by a check that the basis we
816
# commit against is the basis for the commit and if not do a delta
818
self._any_changes = True
820
# housekeeping root entry changes do not affect no-change commits.
821
self._require_root_change(tree)
822
self.basis_delta_revision = basis_revision_id
824
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
825
parent_keys = tuple([(file_id, parent) for parent in parents])
826
return self.repository.texts._add_text(
827
(file_id, self._new_revision_id), parent_keys, new_text,
828
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
831
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
832
"""This commitbuilder actually records the root id"""
834
# the root entry gets versioned properly by this builder.
835
_versioned_root = True
837
def _check_root(self, ie, parent_invs, tree):
838
"""Helper for record_entry_contents.
840
:param ie: An entry being added.
841
:param parent_invs: The inventories of the parent revisions of the
843
:param tree: The tree that is being committed.
846
def _require_root_change(self, tree):
847
"""Enforce an appropriate root object change.
849
This is called once when record_iter_changes is called, if and only if
850
the root was not in the delta calculated by record_iter_changes.
852
:param tree: The tree which is being committed.
854
# versioned roots do not change unless the tree found a change.
857
class VersionedFileRepository(Repository):
858
"""Repository holding history for one or more branches.
860
The repository holds and retrieves historical information including
861
revisions and file history. It's normally accessed only by the Branch,
862
which views a particular line of development through that history.
864
The Repository builds on top of some byte storage facilies (the revisions,
865
signatures, inventories, texts and chk_bytes attributes) and a Transport,
866
which respectively provide byte storage and a means to access the (possibly
869
The byte storage facilities are addressed via tuples, which we refer to
870
as 'keys' throughout the code base. Revision_keys, inventory_keys and
871
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
872
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
873
byte string made up of a hash identifier and a hash value.
874
We use this interface because it allows low friction with the underlying
875
code that implements disk indices, network encoding and other parts of
878
:ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
879
the serialised revisions for the repository. This can be used to obtain
880
revision graph information or to access raw serialised revisions.
881
The result of trying to insert data into the repository via this store
882
is undefined: it should be considered read-only except for implementors
884
:ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
885
the serialised signatures for the repository. This can be used to
886
obtain access to raw serialised signatures. The result of trying to
887
insert data into the repository via this store is undefined: it should
888
be considered read-only except for implementors of repositories.
889
:ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
890
the serialised inventories for the repository. This can be used to
891
obtain unserialised inventories. The result of trying to insert data
892
into the repository via this store is undefined: it should be
893
considered read-only except for implementors of repositories.
894
:ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
895
texts of files and directories for the repository. This can be used to
896
obtain file texts or file graphs. Note that Repository.iter_file_bytes
897
is usually a better interface for accessing file texts.
898
The result of trying to insert data into the repository via this store
899
is undefined: it should be considered read-only except for implementors
901
:ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
902
any data the repository chooses to store or have indexed by its hash.
903
The result of trying to insert data into the repository via this store
904
is undefined: it should be considered read-only except for implementors
906
:ivar _transport: Transport for file access to repository, typically
907
pointing to .bzr/repository.
910
# What class to use for a CommitBuilder. Often it's simpler to change this
911
# in a Repository class subclass rather than to override
912
# get_commit_builder.
913
_commit_builder_class = VersionedFileCommitBuilder
915
def add_fallback_repository(self, repository):
916
"""Add a repository to use for looking up data not held locally.
918
:param repository: A repository.
920
if not self._format.supports_external_lookups:
921
raise errors.UnstackableRepositoryFormat(self._format, self.base)
922
# This can raise an exception, so should be done before we lock the
923
# fallback repository.
924
self._check_fallback_repository(repository)
926
# This repository will call fallback.unlock() when we transition to
927
# the unlocked state, so we make sure to increment the lock count
928
repository.lock_read()
929
self._fallback_repositories.append(repository)
930
self.texts.add_fallback_versioned_files(repository.texts)
931
self.inventories.add_fallback_versioned_files(repository.inventories)
932
self.revisions.add_fallback_versioned_files(repository.revisions)
933
self.signatures.add_fallback_versioned_files(repository.signatures)
934
if self.chk_bytes is not None:
935
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
937
@only_raises(errors.LockNotHeld, errors.LockBroken)
939
super(VersionedFileRepository, self).unlock()
940
if self.control_files._lock_count == 0:
941
self._inventory_entry_cache.clear()
943
def add_inventory(self, revision_id, inv, parents):
944
"""Add the inventory inv to the repository as revision_id.
946
:param parents: The revision ids of the parents that revision_id
947
is known to have and are in the repository already.
949
:returns: The validator(which is a sha1 digest, though what is sha'd is
950
repository format specific) of the serialized inventory.
952
if not self.is_in_write_group():
953
raise AssertionError("%r not in write group" % (self,))
954
_mod_revision.check_not_reserved_id(revision_id)
955
if not (inv.revision_id is None or inv.revision_id == revision_id):
956
raise AssertionError(
957
"Mismatch between inventory revision"
958
" id and insertion revid (%r, %r)"
959
% (inv.revision_id, revision_id))
961
raise errors.RootMissing()
962
return self._add_inventory_checked(revision_id, inv, parents)
964
def _add_inventory_checked(self, revision_id, inv, parents):
965
"""Add inv to the repository after checking the inputs.
967
This function can be overridden to allow different inventory styles.
969
:seealso: add_inventory, for the contract.
971
inv_lines = self._serializer.write_inventory_to_lines(inv)
972
return self._inventory_add_lines(revision_id, parents,
973
inv_lines, check_content=False)
975
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
976
parents, basis_inv=None, propagate_caches=False):
977
"""Add a new inventory expressed as a delta against another revision.
979
See the inventory developers documentation for the theory behind
982
:param basis_revision_id: The inventory id the delta was created
983
against. (This does not have to be a direct parent.)
984
:param delta: The inventory delta (see Inventory.apply_delta for
986
:param new_revision_id: The revision id that the inventory is being
988
:param parents: The revision ids of the parents that revision_id is
989
known to have and are in the repository already. These are supplied
990
for repositories that depend on the inventory graph for revision
991
graph access, as well as for those that pun ancestry with delta
993
:param basis_inv: The basis inventory if it is already known,
995
:param propagate_caches: If True, the caches for this inventory are
996
copied to and updated for the result if possible.
998
:returns: (validator, new_inv)
999
The validator(which is a sha1 digest, though what is sha'd is
1000
repository format specific) of the serialized inventory, and the
1001
resulting inventory.
1003
if not self.is_in_write_group():
1004
raise AssertionError("%r not in write group" % (self,))
1005
_mod_revision.check_not_reserved_id(new_revision_id)
1006
basis_tree = self.revision_tree(basis_revision_id)
1007
basis_tree.lock_read()
1009
# Note that this mutates the inventory of basis_tree, which not all
1010
# inventory implementations may support: A better idiom would be to
1011
# return a new inventory, but as there is no revision tree cache in
1012
# repository this is safe for now - RBC 20081013
1013
if basis_inv is None:
1014
basis_inv = basis_tree.inventory
1015
basis_inv.apply_delta(delta)
1016
basis_inv.revision_id = new_revision_id
1017
return (self.add_inventory(new_revision_id, basis_inv, parents),
1022
def _inventory_add_lines(self, revision_id, parents, lines,
1023
check_content=True):
1024
"""Store lines in inv_vf and return the sha1 of the inventory."""
1025
parents = [(parent,) for parent in parents]
1026
result = self.inventories.add_lines((revision_id,), parents, lines,
1027
check_content=check_content)[0]
1028
self.inventories._access.flush()
1031
def add_revision(self, revision_id, rev, inv=None, config=None):
1032
"""Add rev to the revision store as revision_id.
1034
:param revision_id: the revision id to use.
1035
:param rev: The revision object.
1036
:param inv: The inventory for the revision. if None, it will be looked
1037
up in the inventory storer
1038
:param config: If None no digital signature will be created.
1039
If supplied its signature_needed method will be used
1040
to determine if a signature should be made.
1042
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1044
_mod_revision.check_not_reserved_id(revision_id)
1045
if config is not None and config.signature_needed():
1047
inv = self.get_inventory(revision_id)
1048
tree = InventoryRevisionTree(self, inv, revision_id)
1049
testament = Testament(rev, tree)
1050
plaintext = testament.as_short_text()
1051
self.store_revision_signature(
1052
gpg.GPGStrategy(config), plaintext, revision_id)
1053
# check inventory present
1054
if not self.inventories.get_parent_map([(revision_id,)]):
1056
raise errors.WeaveRevisionNotPresent(revision_id,
1059
# yes, this is not suitable for adding with ghosts.
1060
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1063
key = (revision_id,)
1064
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1065
self._add_revision(rev)
1067
def _add_revision(self, revision):
1068
text = self._serializer.write_revision_to_string(revision)
1069
key = (revision.revision_id,)
1070
parents = tuple((parent,) for parent in revision.parent_ids)
1071
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1073
def _check_inventories(self, checker):
1074
"""Check the inventories found from the revision scan.
1076
This is responsible for verifying the sha1 of inventories and
1077
creating a pending_keys set that covers data referenced by inventories.
1079
bar = ui.ui_factory.nested_progress_bar()
1081
self._do_check_inventories(checker, bar)
1085
def _do_check_inventories(self, checker, bar):
1086
"""Helper for _check_inventories."""
1088
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1089
kinds = ['chk_bytes', 'texts']
1090
count = len(checker.pending_keys)
1091
bar.update(gettext("inventories"), 0, 2)
1092
current_keys = checker.pending_keys
1093
checker.pending_keys = {}
1094
# Accumulate current checks.
1095
for key in current_keys:
1096
if key[0] != 'inventories' and key[0] not in kinds:
1097
checker._report_items.append('unknown key type %r' % (key,))
1098
keys[key[0]].add(key[1:])
1099
if keys['inventories']:
1100
# NB: output order *should* be roughly sorted - topo or
1101
# inverse topo depending on repository - either way decent
1102
# to just delta against. However, pre-CHK formats didn't
1103
# try to optimise inventory layout on disk. As such the
1104
# pre-CHK code path does not use inventory deltas.
1106
for record in self.inventories.check(keys=keys['inventories']):
1107
if record.storage_kind == 'absent':
1108
checker._report_items.append(
1109
'Missing inventory {%s}' % (record.key,))
1111
last_object = self._check_record('inventories', record,
1112
checker, last_object,
1113
current_keys[('inventories',) + record.key])
1114
del keys['inventories']
1117
bar.update(gettext("texts"), 1)
1118
while (checker.pending_keys or keys['chk_bytes']
1120
# Something to check.
1121
current_keys = checker.pending_keys
1122
checker.pending_keys = {}
1123
# Accumulate current checks.
1124
for key in current_keys:
1125
if key[0] not in kinds:
1126
checker._report_items.append('unknown key type %r' % (key,))
1127
keys[key[0]].add(key[1:])
1128
# Check the outermost kind only - inventories || chk_bytes || texts
1132
for record in getattr(self, kind).check(keys=keys[kind]):
1133
if record.storage_kind == 'absent':
1134
checker._report_items.append(
1135
'Missing %s {%s}' % (kind, record.key,))
1137
last_object = self._check_record(kind, record,
1138
checker, last_object, current_keys[(kind,) + record.key])
1142
def _check_record(self, kind, record, checker, last_object, item_data):
1143
"""Check a single text from this repository."""
1144
if kind == 'inventories':
1145
rev_id = record.key[0]
1146
inv = self._deserialise_inventory(rev_id,
1147
record.get_bytes_as('fulltext'))
1148
if last_object is not None:
1149
delta = inv._make_delta(last_object)
1150
for old_path, path, file_id, ie in delta:
1153
ie.check(checker, rev_id, inv)
1155
for path, ie in inv.iter_entries():
1156
ie.check(checker, rev_id, inv)
1157
if self._format.fast_deltas:
1159
elif kind == 'chk_bytes':
1160
# No code written to check chk_bytes for this repo format.
1161
checker._report_items.append(
1162
'unsupported key type chk_bytes for %s' % (record.key,))
1163
elif kind == 'texts':
1164
self._check_text(record, checker, item_data)
1166
checker._report_items.append(
1167
'unknown key type %s for %s' % (kind, record.key))
1169
def _check_text(self, record, checker, item_data):
1170
"""Check a single text."""
1171
# Check it is extractable.
1172
# TODO: check length.
1173
if record.storage_kind == 'chunked':
1174
chunks = record.get_bytes_as(record.storage_kind)
1175
sha1 = osutils.sha_strings(chunks)
1176
length = sum(map(len, chunks))
1178
content = record.get_bytes_as('fulltext')
1179
sha1 = osutils.sha_string(content)
1180
length = len(content)
1181
if item_data and sha1 != item_data[1]:
1182
checker._report_items.append(
1183
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1184
(record.key, sha1, item_data[1], item_data[2]))
1187
def _eliminate_revisions_not_present(self, revision_ids):
1188
"""Check every revision id in revision_ids to see if we have it.
1190
Returns a set of the present revisions.
1193
graph = self.get_graph()
1194
parent_map = graph.get_parent_map(revision_ids)
1195
# The old API returned a list, should this actually be a set?
1196
return parent_map.keys()
1198
def __init__(self, _format, a_bzrdir, control_files):
1199
"""Instantiate a VersionedFileRepository.
1201
:param _format: The format of the repository on disk.
1202
:param controldir: The ControlDir of the repository.
1203
:param control_files: Control files to use for locking, etc.
1205
# In the future we will have a single api for all stores for
1206
# getting file texts, inventories and revisions, then
1207
# this construct will accept instances of those things.
1208
super(VersionedFileRepository, self).__init__(_format, a_bzrdir,
1210
self._transport = control_files._transport
1211
self.base = self._transport.base
1213
self._reconcile_does_inventory_gc = True
1214
self._reconcile_fixes_text_parents = False
1215
self._reconcile_backsup_inventory = True
1216
# An InventoryEntry cache, used during deserialization
1217
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1218
# Is it safe to return inventory entries directly from the entry cache,
1219
# rather copying them?
1220
self._safe_to_return_from_cache = False
1223
def gather_stats(self, revid=None, committers=None):
1224
"""See Repository.gather_stats()."""
1225
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1226
# now gather global repository information
1227
# XXX: This is available for many repos regardless of listability.
1228
if self.user_transport.listable():
1229
# XXX: do we want to __define len__() ?
1230
# Maybe the versionedfiles object should provide a different
1231
# method to get the number of keys.
1232
result['revisions'] = len(self.revisions.keys())
1233
# result['size'] = t
1236
def get_commit_builder(self, branch, parents, config, timestamp=None,
1237
timezone=None, committer=None, revprops=None,
1238
revision_id=None, lossy=False):
1239
"""Obtain a CommitBuilder for this repository.
1241
:param branch: Branch to commit to.
1242
:param parents: Revision ids of the parents of the new revision.
1243
:param config: Configuration to use.
1244
:param timestamp: Optional timestamp recorded for commit.
1245
:param timezone: Optional timezone for timestamp.
1246
:param committer: Optional committer to set for commit.
1247
:param revprops: Optional dictionary of revision properties.
1248
:param revision_id: Optional revision id.
1249
:param lossy: Whether to discard data that can not be natively
1250
represented, when pushing to a foreign VCS
1252
if self._fallback_repositories and not self._format.supports_chks:
1253
raise errors.BzrError("Cannot commit directly to a stacked branch"
1254
" in pre-2a formats. See "
1255
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1256
result = self._commit_builder_class(self, parents, config,
1257
timestamp, timezone, committer, revprops, revision_id,
1259
self.start_write_group()
1262
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1263
"""Return the keys of missing inventory parents for revisions added in
1266
A revision is not complete if the inventory delta for that revision
1267
cannot be calculated. Therefore if the parent inventories of a
1268
revision are not present, the revision is incomplete, and e.g. cannot
1269
be streamed by a smart server. This method finds missing inventory
1270
parents for revisions added in this write group.
1272
if not self._format.supports_external_lookups:
1273
# This is only an issue for stacked repositories
1275
if not self.is_in_write_group():
1276
raise AssertionError('not in a write group')
1278
# XXX: We assume that every added revision already has its
1279
# corresponding inventory, so we only check for parent inventories that
1280
# might be missing, rather than all inventories.
1281
parents = set(self.revisions._index.get_missing_parents())
1282
parents.discard(_mod_revision.NULL_REVISION)
1283
unstacked_inventories = self.inventories._index
1284
present_inventories = unstacked_inventories.get_parent_map(
1285
key[-1:] for key in parents)
1286
parents.difference_update(present_inventories)
1287
if len(parents) == 0:
1288
# No missing parent inventories.
1290
if not check_for_missing_texts:
1291
return set(('inventories', rev_id) for (rev_id,) in parents)
1292
# Ok, now we have a list of missing inventories. But these only matter
1293
# if the inventories that reference them are missing some texts they
1294
# appear to introduce.
1295
# XXX: Texts referenced by all added inventories need to be present,
1296
# but at the moment we're only checking for texts referenced by
1297
# inventories at the graph's edge.
1298
key_deps = self.revisions._index._key_dependencies
1299
key_deps.satisfy_refs_for_keys(present_inventories)
1300
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1301
file_ids = self.fileids_altered_by_revision_ids(referrers)
1302
missing_texts = set()
1303
for file_id, version_ids in file_ids.iteritems():
1304
missing_texts.update(
1305
(file_id, version_id) for version_id in version_ids)
1306
present_texts = self.texts.get_parent_map(missing_texts)
1307
missing_texts.difference_update(present_texts)
1308
if not missing_texts:
1309
# No texts are missing, so all revisions and their deltas are
1312
# Alternatively the text versions could be returned as the missing
1313
# keys, but this is likely to be less data.
1314
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1318
def has_revisions(self, revision_ids):
1319
"""Probe to find out the presence of multiple revisions.
1321
:param revision_ids: An iterable of revision_ids.
1322
:return: A set of the revision_ids that were present.
1324
parent_map = self.revisions.get_parent_map(
1325
[(rev_id,) for rev_id in revision_ids])
1327
if _mod_revision.NULL_REVISION in revision_ids:
1328
result.add(_mod_revision.NULL_REVISION)
1329
result.update([key[0] for key in parent_map])
1333
def get_revision_reconcile(self, revision_id):
1334
"""'reconcile' helper routine that allows access to a revision always.
1336
This variant of get_revision does not cross check the weave graph
1337
against the revision one as get_revision does: but it should only
1338
be used by reconcile, or reconcile-alike commands that are correcting
1339
or testing the revision graph.
1341
return self._get_revisions([revision_id])[0]
1344
def get_revisions(self, revision_ids):
1345
"""Get many revisions at once.
1347
Repositories that need to check data on every revision read should
1348
subclass this method.
1350
return self._get_revisions(revision_ids)
1353
def _get_revisions(self, revision_ids):
1354
"""Core work logic to get many revisions without sanity checks."""
1356
for revid, rev in self._iter_revisions(revision_ids):
1358
raise errors.NoSuchRevision(self, revid)
1360
return [revs[revid] for revid in revision_ids]
1362
def _iter_revisions(self, revision_ids):
1363
"""Iterate over revision objects.
1365
:param revision_ids: An iterable of revisions to examine. None may be
1366
passed to request all revisions known to the repository. Note that
1367
not all repositories can find unreferenced revisions; for those
1368
repositories only referenced ones will be returned.
1369
:return: An iterator of (revid, revision) tuples. Absent revisions (
1370
those asked for but not available) are returned as (revid, None).
1372
if revision_ids is None:
1373
revision_ids = self.all_revision_ids()
1375
for rev_id in revision_ids:
1376
if not rev_id or not isinstance(rev_id, basestring):
1377
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1378
keys = [(key,) for key in revision_ids]
1379
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1380
for record in stream:
1381
revid = record.key[0]
1382
if record.storage_kind == 'absent':
1385
text = record.get_bytes_as('fulltext')
1386
rev = self._serializer.read_revision_from_string(text)
1390
def add_signature_text(self, revision_id, signature):
1391
"""Store a signature text for a revision.
1393
:param revision_id: Revision id of the revision
1394
:param signature: Signature text.
1396
self.signatures.add_lines((revision_id,), (),
1397
osutils.split_lines(signature))
1399
def find_text_key_references(self):
1400
"""Find the text key references within the repository.
1402
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1403
to whether they were referred to by the inventory of the
1404
revision_id that they contain. The inventory texts from all present
1405
revision ids are assessed to generate this report.
1407
revision_keys = self.revisions.keys()
1408
w = self.inventories
1409
pb = ui.ui_factory.nested_progress_bar()
1411
return self._serializer._find_text_key_references(
1412
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1416
def _inventory_xml_lines_for_keys(self, keys):
1417
"""Get a line iterator of the sort needed for findind references.
1419
Not relevant for non-xml inventory repositories.
1421
Ghosts in revision_keys are ignored.
1423
:param revision_keys: The revision keys for the inventories to inspect.
1424
:return: An iterator over (inventory line, revid) for the fulltexts of
1425
all of the xml inventories specified by revision_keys.
1427
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1428
for record in stream:
1429
if record.storage_kind != 'absent':
1430
chunks = record.get_bytes_as('chunked')
1431
revid = record.key[-1]
1432
lines = osutils.chunks_to_lines(chunks)
1436
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1438
"""Helper routine for fileids_altered_by_revision_ids.
1440
This performs the translation of xml lines to revision ids.
1442
:param line_iterator: An iterator of lines, origin_version_id
1443
:param revision_keys: The revision ids to filter for. This should be a
1444
set or other type which supports efficient __contains__ lookups, as
1445
the revision key from each parsed line will be looked up in the
1446
revision_keys filter.
1447
:return: a dictionary mapping altered file-ids to an iterable of
1448
revision_ids. Each altered file-ids has the exact revision_ids that
1449
altered it listed explicitly.
1451
seen = set(self._serializer._find_text_key_references(
1452
line_iterator).iterkeys())
1453
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1454
parent_seen = set(self._serializer._find_text_key_references(
1455
self._inventory_xml_lines_for_keys(parent_keys)))
1456
new_keys = seen - parent_seen
1458
setdefault = result.setdefault
1459
for key in new_keys:
1460
setdefault(key[0], set()).add(key[-1])
1463
def _find_parent_keys_of_revisions(self, revision_keys):
1464
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1466
:param revision_keys: An iterable of revision_keys.
1467
:return: The parents of all revision_keys that are not already in
1470
parent_map = self.revisions.get_parent_map(revision_keys)
1472
map(parent_keys.update, parent_map.itervalues())
1473
parent_keys.difference_update(revision_keys)
1474
parent_keys.discard(_mod_revision.NULL_REVISION)
1477
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1478
"""Find the file ids and versions affected by revisions.
1480
:param revisions: an iterable containing revision ids.
1481
:param _inv_weave: The inventory weave from this repository or None.
1482
If None, the inventory weave will be opened automatically.
1483
:return: a dictionary mapping altered file-ids to an iterable of
1484
revision_ids. Each altered file-ids has the exact revision_ids that
1485
altered it listed explicitly.
1487
selected_keys = set((revid,) for revid in revision_ids)
1488
w = _inv_weave or self.inventories
1489
return self._find_file_ids_from_xml_inventory_lines(
1490
w.iter_lines_added_or_present_in_keys(
1491
selected_keys, pb=None),
1494
def iter_files_bytes(self, desired_files):
1495
"""Iterate through file versions.
1497
Files will not necessarily be returned in the order they occur in
1498
desired_files. No specific order is guaranteed.
1500
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1501
value supplied by the caller as part of desired_files. It should
1502
uniquely identify the file version in the caller's context. (Examples:
1503
an index number or a TreeTransform trans_id.)
1505
bytes_iterator is an iterable of bytestrings for the file. The
1506
kind of iterable and length of the bytestrings are unspecified, but for
1507
this implementation, it is a list of bytes produced by
1508
VersionedFile.get_record_stream().
1510
:param desired_files: a list of (file_id, revision_id, identifier)
1514
for file_id, revision_id, callable_data in desired_files:
1515
text_keys[(file_id, revision_id)] = callable_data
1516
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1517
if record.storage_kind == 'absent':
1518
raise errors.RevisionNotPresent(record.key, self)
1519
yield text_keys[record.key], record.get_bytes_as('chunked')
1521
def _generate_text_key_index(self, text_key_references=None,
1523
"""Generate a new text key index for the repository.
1525
This is an expensive function that will take considerable time to run.
1527
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1528
list of parents, also text keys. When a given key has no parents,
1529
the parents list will be [NULL_REVISION].
1531
# All revisions, to find inventory parents.
1532
if ancestors is None:
1533
graph = self.get_graph()
1534
ancestors = graph.get_parent_map(self.all_revision_ids())
1535
if text_key_references is None:
1536
text_key_references = self.find_text_key_references()
1537
pb = ui.ui_factory.nested_progress_bar()
1539
return self._do_generate_text_key_index(ancestors,
1540
text_key_references, pb)
1544
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1545
"""Helper for _generate_text_key_index to avoid deep nesting."""
1546
revision_order = tsort.topo_sort(ancestors)
1547
invalid_keys = set()
1549
for revision_id in revision_order:
1550
revision_keys[revision_id] = set()
1551
text_count = len(text_key_references)
1552
# a cache of the text keys to allow reuse; costs a dict of all the
1553
# keys, but saves a 2-tuple for every child of a given key.
1555
for text_key, valid in text_key_references.iteritems():
1557
invalid_keys.add(text_key)
1559
revision_keys[text_key[1]].add(text_key)
1560
text_key_cache[text_key] = text_key
1561
del text_key_references
1563
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1564
NULL_REVISION = _mod_revision.NULL_REVISION
1565
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1566
# too small for large or very branchy trees. However, for 55K path
1567
# trees, it would be easy to use too much memory trivially. Ideally we
1568
# could gauge this by looking at available real memory etc, but this is
1569
# always a tricky proposition.
1570
inventory_cache = lru_cache.LRUCache(10)
1571
batch_size = 10 # should be ~150MB on a 55K path tree
1572
batch_count = len(revision_order) / batch_size + 1
1574
pb.update(gettext("Calculating text parents"), processed_texts, text_count)
1575
for offset in xrange(batch_count):
1576
to_query = revision_order[offset * batch_size:(offset + 1) *
1580
for revision_id in to_query:
1581
parent_ids = ancestors[revision_id]
1582
for text_key in revision_keys[revision_id]:
1583
pb.update(gettext("Calculating text parents"), processed_texts)
1584
processed_texts += 1
1585
candidate_parents = []
1586
for parent_id in parent_ids:
1587
parent_text_key = (text_key[0], parent_id)
1589
check_parent = parent_text_key not in \
1590
revision_keys[parent_id]
1592
# the parent parent_id is a ghost:
1593
check_parent = False
1594
# truncate the derived graph against this ghost.
1595
parent_text_key = None
1597
# look at the parent commit details inventories to
1598
# determine possible candidates in the per file graph.
1601
inv = inventory_cache[parent_id]
1603
inv = self.revision_tree(parent_id).inventory
1604
inventory_cache[parent_id] = inv
1606
parent_entry = inv[text_key[0]]
1607
except (KeyError, errors.NoSuchId):
1609
if parent_entry is not None:
1611
text_key[0], parent_entry.revision)
1613
parent_text_key = None
1614
if parent_text_key is not None:
1615
candidate_parents.append(
1616
text_key_cache[parent_text_key])
1617
parent_heads = text_graph.heads(candidate_parents)
1618
new_parents = list(parent_heads)
1619
new_parents.sort(key=lambda x:candidate_parents.index(x))
1620
if new_parents == []:
1621
new_parents = [NULL_REVISION]
1622
text_index[text_key] = new_parents
1624
for text_key in invalid_keys:
1625
text_index[text_key] = [NULL_REVISION]
1628
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1629
"""Get an iterable listing the keys of all the data introduced by a set
1632
The keys will be ordered so that the corresponding items can be safely
1633
fetched and inserted in that order.
1635
:returns: An iterable producing tuples of (knit-kind, file-id,
1636
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1637
'revisions'. file-id is None unless knit-kind is 'file'.
1639
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1642
for result in self._find_non_file_keys_to_fetch(revision_ids):
1645
def _find_file_keys_to_fetch(self, revision_ids, pb):
1646
# XXX: it's a bit weird to control the inventory weave caching in this
1647
# generator. Ideally the caching would be done in fetch.py I think. Or
1648
# maybe this generator should explicitly have the contract that it
1649
# should not be iterated until the previously yielded item has been
1651
inv_w = self.inventories
1653
# file ids that changed
1654
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1656
num_file_ids = len(file_ids)
1657
for file_id, altered_versions in file_ids.iteritems():
1659
pb.update(gettext("Fetch texts"), count, num_file_ids)
1661
yield ("file", file_id, altered_versions)
1663
def _find_non_file_keys_to_fetch(self, revision_ids):
1665
yield ("inventory", None, revision_ids)
1668
# XXX: Note ATM no callers actually pay attention to this return
1669
# instead they just use the list of revision ids and ignore
1670
# missing sigs. Consider removing this work entirely
1671
revisions_with_signatures = set(self.signatures.get_parent_map(
1672
[(r,) for r in revision_ids]))
1673
revisions_with_signatures = set(
1674
[r for (r,) in revisions_with_signatures])
1675
revisions_with_signatures.intersection_update(revision_ids)
1676
yield ("signatures", None, revisions_with_signatures)
1679
yield ("revisions", None, revision_ids)
1682
def get_inventory(self, revision_id):
1683
"""Get Inventory object by revision id."""
1684
return self.iter_inventories([revision_id]).next()
1686
def iter_inventories(self, revision_ids, ordering=None):
1687
"""Get many inventories by revision_ids.
1689
This will buffer some or all of the texts used in constructing the
1690
inventories in memory, but will only parse a single inventory at a
1693
:param revision_ids: The expected revision ids of the inventories.
1694
:param ordering: optional ordering, e.g. 'topological'. If not
1695
specified, the order of revision_ids will be preserved (by
1696
buffering if necessary).
1697
:return: An iterator of inventories.
1699
if ((None in revision_ids)
1700
or (_mod_revision.NULL_REVISION in revision_ids)):
1701
raise ValueError('cannot get null revision inventory')
1702
return self._iter_inventories(revision_ids, ordering)
1704
def _iter_inventories(self, revision_ids, ordering):
1705
"""single-document based inventory iteration."""
1706
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1707
for text, revision_id in inv_xmls:
1708
yield self._deserialise_inventory(revision_id, text)
1710
def _iter_inventory_xmls(self, revision_ids, ordering):
1711
if ordering is None:
1712
order_as_requested = True
1713
ordering = 'unordered'
1715
order_as_requested = False
1716
keys = [(revision_id,) for revision_id in revision_ids]
1719
if order_as_requested:
1720
key_iter = iter(keys)
1721
next_key = key_iter.next()
1722
stream = self.inventories.get_record_stream(keys, ordering, True)
1724
for record in stream:
1725
if record.storage_kind != 'absent':
1726
chunks = record.get_bytes_as('chunked')
1727
if order_as_requested:
1728
text_chunks[record.key] = chunks
1730
yield ''.join(chunks), record.key[-1]
1732
raise errors.NoSuchRevision(self, record.key)
1733
if order_as_requested:
1734
# Yield as many results as we can while preserving order.
1735
while next_key in text_chunks:
1736
chunks = text_chunks.pop(next_key)
1737
yield ''.join(chunks), next_key[-1]
1739
next_key = key_iter.next()
1740
except StopIteration:
1741
# We still want to fully consume the get_record_stream,
1742
# just in case it is not actually finished at this point
1746
def _deserialise_inventory(self, revision_id, xml):
1747
"""Transform the xml into an inventory object.
1749
:param revision_id: The expected revision id of the inventory.
1750
:param xml: A serialised inventory.
1752
result = self._serializer.read_inventory_from_string(xml, revision_id,
1753
entry_cache=self._inventory_entry_cache,
1754
return_from_cache=self._safe_to_return_from_cache)
1755
if result.revision_id != revision_id:
1756
raise AssertionError('revision id mismatch %s != %s' % (
1757
result.revision_id, revision_id))
1760
def get_serializer_format(self):
1761
return self._serializer.format_num
1764
def _get_inventory_xml(self, revision_id):
1765
"""Get serialized inventory as a string."""
1766
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1768
text, revision_id = texts.next()
1769
except StopIteration:
1770
raise errors.HistoryMissing(self, 'inventory', revision_id)
1774
def revision_tree(self, revision_id):
1775
"""Return Tree for a revision on this branch.
1777
`revision_id` may be NULL_REVISION for the empty tree revision.
1779
revision_id = _mod_revision.ensure_null(revision_id)
1780
# TODO: refactor this to use an existing revision object
1781
# so we don't need to read it in twice.
1782
if revision_id == _mod_revision.NULL_REVISION:
1783
return InventoryRevisionTree(self,
1784
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1786
inv = self.get_inventory(revision_id)
1787
return InventoryRevisionTree(self, inv, revision_id)
1789
def revision_trees(self, revision_ids):
1790
"""Return Trees for revisions in this repository.
1792
:param revision_ids: a sequence of revision-ids;
1793
a revision-id may not be None or 'null:'
1795
inventories = self.iter_inventories(revision_ids)
1796
for inv in inventories:
1797
yield InventoryRevisionTree(self, inv, inv.revision_id)
1799
def _filtered_revision_trees(self, revision_ids, file_ids):
1800
"""Return Tree for a revision on this branch with only some files.
1802
:param revision_ids: a sequence of revision-ids;
1803
a revision-id may not be None or 'null:'
1804
:param file_ids: if not None, the result is filtered
1805
so that only those file-ids, their parents and their
1806
children are included.
1808
inventories = self.iter_inventories(revision_ids)
1809
for inv in inventories:
1810
# Should we introduce a FilteredRevisionTree class rather
1811
# than pre-filter the inventory here?
1812
filtered_inv = inv.filter(file_ids)
1813
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1815
def get_parent_map(self, revision_ids):
1816
"""See graph.StackedParentsProvider.get_parent_map"""
1817
# revisions index works in keys; this just works in revisions
1818
# therefore wrap and unwrap
1821
for revision_id in revision_ids:
1822
if revision_id == _mod_revision.NULL_REVISION:
1823
result[revision_id] = ()
1824
elif revision_id is None:
1825
raise ValueError('get_parent_map(None) is not valid')
1827
query_keys.append((revision_id ,))
1828
for ((revision_id,), parent_keys) in \
1829
self.revisions.get_parent_map(query_keys).iteritems():
1831
result[revision_id] = tuple([parent_revid
1832
for (parent_revid,) in parent_keys])
1834
result[revision_id] = (_mod_revision.NULL_REVISION,)
1838
def get_known_graph_ancestry(self, revision_ids):
1839
"""Return the known graph for a set of revision ids and their ancestors.
1841
st = static_tuple.StaticTuple
1842
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1843
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1844
return graph.GraphThunkIdsToKeys(known_graph)
1847
def get_file_graph(self):
1848
"""Return the graph walker for text revisions."""
1849
return graph.Graph(self.texts)
1851
def _get_versioned_file_checker(self, text_key_references=None,
1853
"""Return an object suitable for checking versioned files.
1855
:param text_key_references: if non-None, an already built
1856
dictionary mapping text keys ((fileid, revision_id) tuples)
1857
to whether they were referred to by the inventory of the
1858
revision_id that they contain. If None, this will be
1860
:param ancestors: Optional result from
1861
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1864
return _VersionedFileChecker(self,
1865
text_key_references=text_key_references, ancestors=ancestors)
1868
def has_signature_for_revision_id(self, revision_id):
1869
"""Query for a revision signature for revision_id in the repository."""
1870
if not self.has_revision(revision_id):
1871
raise errors.NoSuchRevision(self, revision_id)
1872
sig_present = (1 == len(
1873
self.signatures.get_parent_map([(revision_id,)])))
1877
def get_signature_text(self, revision_id):
1878
"""Return the text for a signature."""
1879
stream = self.signatures.get_record_stream([(revision_id,)],
1881
record = stream.next()
1882
if record.storage_kind == 'absent':
1883
raise errors.NoSuchRevision(self, revision_id)
1884
return record.get_bytes_as('fulltext')
1887
def _check(self, revision_ids, callback_refs, check_repo):
1888
result = check.VersionedFileCheck(self, check_repo=check_repo)
1889
result.check(callback_refs)
1892
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1893
"""Find revisions with different parent lists in the revision object
1894
and in the index graph.
1896
:param revisions_iterator: None, or an iterator of (revid,
1897
Revision-or-None). This iterator controls the revisions checked.
1898
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1899
parents-in-revision).
1901
if not self.is_locked():
1902
raise AssertionError()
1904
if revisions_iterator is None:
1905
revisions_iterator = self._iter_revisions(None)
1906
for revid, revision in revisions_iterator:
1907
if revision is None:
1909
parent_map = vf.get_parent_map([(revid,)])
1910
parents_according_to_index = tuple(parent[-1] for parent in
1911
parent_map[(revid,)])
1912
parents_according_to_revision = tuple(revision.parent_ids)
1913
if parents_according_to_index != parents_according_to_revision:
1914
yield (revid, parents_according_to_index,
1915
parents_according_to_revision)
1917
def _check_for_inconsistent_revision_parents(self):
1918
inconsistencies = list(self._find_inconsistent_revision_parents())
1920
raise errors.BzrCheckError(
1921
"Revision knit has inconsistent parents.")
1923
def _get_sink(self):
1924
"""Return a sink for streaming into this repository."""
1925
return StreamSink(self)
1927
def _get_source(self, to_format):
1928
"""Return a source for streaming from this repository."""
1929
return StreamSource(self, to_format)
1932
class MetaDirVersionedFileRepository(MetaDirRepository,
1933
VersionedFileRepository):
1934
"""Repositories in a meta-dir, that work via versioned file objects."""
1936
def __init__(self, _format, a_bzrdir, control_files):
1937
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
1941
class MetaDirVersionedFileRepositoryFormat(MetaDirRepositoryFormat,
1942
VersionedFileRepositoryFormat):
1943
"""Base class for repository formats using versioned files in metadirs."""
1946
class StreamSink(object):
1947
"""An object that can insert a stream into a repository.
1949
This interface handles the complexity of reserialising inventories and
1950
revisions from different formats, and allows unidirectional insertion into
1951
stacked repositories without looking for the missing basis parents
1955
def __init__(self, target_repo):
1956
self.target_repo = target_repo
1958
def insert_stream(self, stream, src_format, resume_tokens):
1959
"""Insert a stream's content into the target repository.
1961
:param src_format: a bzr repository format.
1963
:return: a list of resume tokens and an iterable of keys additional
1964
items required before the insertion can be completed.
1966
self.target_repo.lock_write()
1969
self.target_repo.resume_write_group(resume_tokens)
1972
self.target_repo.start_write_group()
1975
# locked_insert_stream performs a commit|suspend.
1976
missing_keys = self.insert_stream_without_locking(stream,
1977
src_format, is_resume)
1979
# suspend the write group and tell the caller what we is
1980
# missing. We know we can suspend or else we would not have
1981
# entered this code path. (All repositories that can handle
1982
# missing keys can handle suspending a write group).
1983
write_group_tokens = self.target_repo.suspend_write_group()
1984
return write_group_tokens, missing_keys
1985
hint = self.target_repo.commit_write_group()
1986
to_serializer = self.target_repo._format._serializer
1987
src_serializer = src_format._serializer
1988
if (to_serializer != src_serializer and
1989
self.target_repo._format.pack_compresses):
1990
self.target_repo.pack(hint=hint)
1993
self.target_repo.abort_write_group(suppress_errors=True)
1996
self.target_repo.unlock()
1998
def insert_stream_without_locking(self, stream, src_format,
2000
"""Insert a stream's content into the target repository.
2002
This assumes that you already have a locked repository and an active
2005
:param src_format: a bzr repository format.
2006
:param is_resume: Passed down to get_missing_parent_inventories to
2007
indicate if we should be checking for missing texts at the same
2010
:return: A set of keys that are missing.
2012
if not self.target_repo.is_write_locked():
2013
raise errors.ObjectNotLocked(self)
2014
if not self.target_repo.is_in_write_group():
2015
raise errors.BzrError('you must already be in a write group')
2016
to_serializer = self.target_repo._format._serializer
2017
src_serializer = src_format._serializer
2019
if to_serializer == src_serializer:
2020
# If serializers match and the target is a pack repository, set the
2021
# write cache size on the new pack. This avoids poor performance
2022
# on transports where append is unbuffered (such as
2023
# RemoteTransport). This is safe to do because nothing should read
2024
# back from the target repository while a stream with matching
2025
# serialization is being inserted.
2026
# The exception is that a delta record from the source that should
2027
# be a fulltext may need to be expanded by the target (see
2028
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2029
# explicitly flush any buffered writes first in that rare case.
2031
new_pack = self.target_repo._pack_collection._new_pack
2032
except AttributeError:
2033
# Not a pack repository
2036
new_pack.set_write_cache_size(1024*1024)
2037
for substream_type, substream in stream:
2038
if 'stream' in debug.debug_flags:
2039
mutter('inserting substream: %s', substream_type)
2040
if substream_type == 'texts':
2041
self.target_repo.texts.insert_record_stream(substream)
2042
elif substream_type == 'inventories':
2043
if src_serializer == to_serializer:
2044
self.target_repo.inventories.insert_record_stream(
2047
self._extract_and_insert_inventories(
2048
substream, src_serializer)
2049
elif substream_type == 'inventory-deltas':
2050
self._extract_and_insert_inventory_deltas(
2051
substream, src_serializer)
2052
elif substream_type == 'chk_bytes':
2053
# XXX: This doesn't support conversions, as it assumes the
2054
# conversion was done in the fetch code.
2055
self.target_repo.chk_bytes.insert_record_stream(substream)
2056
elif substream_type == 'revisions':
2057
# This may fallback to extract-and-insert more often than
2058
# required if the serializers are different only in terms of
2060
if src_serializer == to_serializer:
2061
self.target_repo.revisions.insert_record_stream(substream)
2063
self._extract_and_insert_revisions(substream,
2065
elif substream_type == 'signatures':
2066
self.target_repo.signatures.insert_record_stream(substream)
2068
raise AssertionError('kaboom! %s' % (substream_type,))
2069
# Done inserting data, and the missing_keys calculations will try to
2070
# read back from the inserted data, so flush the writes to the new pack
2071
# (if this is pack format).
2072
if new_pack is not None:
2073
new_pack._write_data('', flush=True)
2074
# Find all the new revisions (including ones from resume_tokens)
2075
missing_keys = self.target_repo.get_missing_parent_inventories(
2076
check_for_missing_texts=is_resume)
2078
for prefix, versioned_file in (
2079
('texts', self.target_repo.texts),
2080
('inventories', self.target_repo.inventories),
2081
('revisions', self.target_repo.revisions),
2082
('signatures', self.target_repo.signatures),
2083
('chk_bytes', self.target_repo.chk_bytes),
2085
if versioned_file is None:
2087
# TODO: key is often going to be a StaticTuple object
2088
# I don't believe we can define a method by which
2089
# (prefix,) + StaticTuple will work, though we could
2090
# define a StaticTuple.sq_concat that would allow you to
2091
# pass in either a tuple or a StaticTuple as the second
2092
# object, so instead we could have:
2093
# StaticTuple(prefix) + key here...
2094
missing_keys.update((prefix,) + key for key in
2095
versioned_file.get_missing_compression_parent_keys())
2096
except NotImplementedError:
2097
# cannot even attempt suspending, and missing would have failed
2098
# during stream insertion.
2099
missing_keys = set()
2102
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2103
target_rich_root = self.target_repo._format.rich_root_data
2104
target_tree_refs = self.target_repo._format.supports_tree_reference
2105
for record in substream:
2106
# Insert the delta directly
2107
inventory_delta_bytes = record.get_bytes_as('fulltext')
2108
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2110
parse_result = deserialiser.parse_text_bytes(
2111
inventory_delta_bytes)
2112
except inventory_delta.IncompatibleInventoryDelta, err:
2113
mutter("Incompatible delta: %s", err.msg)
2114
raise errors.IncompatibleRevision(self.target_repo._format)
2115
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2116
revision_id = new_id
2117
parents = [key[0] for key in record.parents]
2118
self.target_repo.add_inventory_by_delta(
2119
basis_id, inv_delta, revision_id, parents)
2121
def _extract_and_insert_inventories(self, substream, serializer,
2123
"""Generate a new inventory versionedfile in target, converting data.
2125
The inventory is retrieved from the source, (deserializing it), and
2126
stored in the target (reserializing it in a different format).
2128
target_rich_root = self.target_repo._format.rich_root_data
2129
target_tree_refs = self.target_repo._format.supports_tree_reference
2130
for record in substream:
2131
# It's not a delta, so it must be a fulltext in the source
2132
# serializer's format.
2133
bytes = record.get_bytes_as('fulltext')
2134
revision_id = record.key[0]
2135
inv = serializer.read_inventory_from_string(bytes, revision_id)
2136
parents = [key[0] for key in record.parents]
2137
self.target_repo.add_inventory(revision_id, inv, parents)
2138
# No need to keep holding this full inv in memory when the rest of
2139
# the substream is likely to be all deltas.
2142
def _extract_and_insert_revisions(self, substream, serializer):
2143
for record in substream:
2144
bytes = record.get_bytes_as('fulltext')
2145
revision_id = record.key[0]
2146
rev = serializer.read_revision_from_string(bytes)
2147
if rev.revision_id != revision_id:
2148
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2149
self.target_repo.add_revision(revision_id, rev)
2152
if self.target_repo._format._fetch_reconcile:
2153
self.target_repo.reconcile()
2156
class StreamSource(object):
2157
"""A source of a stream for fetching between repositories."""
2159
def __init__(self, from_repository, to_format):
2160
"""Create a StreamSource streaming from from_repository."""
2161
self.from_repository = from_repository
2162
self.to_format = to_format
2163
self._record_counter = RecordCounter()
2165
def delta_on_metadata(self):
2166
"""Return True if delta's are permitted on metadata streams.
2168
That is on revisions and signatures.
2170
src_serializer = self.from_repository._format._serializer
2171
target_serializer = self.to_format._serializer
2172
return (self.to_format._fetch_uses_deltas and
2173
src_serializer == target_serializer)
2175
def _fetch_revision_texts(self, revs):
2176
# fetch signatures first and then the revision texts
2177
# may need to be a InterRevisionStore call here.
2178
from_sf = self.from_repository.signatures
2179
# A missing signature is just skipped.
2180
keys = [(rev_id,) for rev_id in revs]
2181
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2183
self.to_format._fetch_order,
2184
not self.to_format._fetch_uses_deltas))
2185
# If a revision has a delta, this is actually expanded inside the
2186
# insert_record_stream code now, which is an alternate fix for
2188
from_rf = self.from_repository.revisions
2189
revisions = from_rf.get_record_stream(
2191
self.to_format._fetch_order,
2192
not self.delta_on_metadata())
2193
return [('signatures', signatures), ('revisions', revisions)]
2195
def _generate_root_texts(self, revs):
2196
"""This will be called by get_stream between fetching weave texts and
2197
fetching the inventory weave.
2199
if self._rich_root_upgrade():
2200
return _mod_fetch.Inter1and2Helper(
2201
self.from_repository).generate_root_texts(revs)
2205
def get_stream(self, search):
2207
revs = search.get_keys()
2208
graph = self.from_repository.get_graph()
2209
revs = tsort.topo_sort(graph.get_parent_map(revs))
2210
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2212
for knit_kind, file_id, revisions in data_to_fetch:
2213
if knit_kind != phase:
2215
# Make a new progress bar for this phase
2216
if knit_kind == "file":
2217
# Accumulate file texts
2218
text_keys.extend([(file_id, revision) for revision in
2220
elif knit_kind == "inventory":
2221
# Now copy the file texts.
2222
from_texts = self.from_repository.texts
2223
yield ('texts', from_texts.get_record_stream(
2224
text_keys, self.to_format._fetch_order,
2225
not self.to_format._fetch_uses_deltas))
2226
# Cause an error if a text occurs after we have done the
2229
# Before we process the inventory we generate the root
2230
# texts (if necessary) so that the inventories references
2232
for _ in self._generate_root_texts(revs):
2234
# we fetch only the referenced inventories because we do not
2235
# know for unselected inventories whether all their required
2236
# texts are present in the other repository - it could be
2238
for info in self._get_inventory_stream(revs):
2240
elif knit_kind == "signatures":
2241
# Nothing to do here; this will be taken care of when
2242
# _fetch_revision_texts happens.
2244
elif knit_kind == "revisions":
2245
for record in self._fetch_revision_texts(revs):
2248
raise AssertionError("Unknown knit kind %r" % knit_kind)
2250
def get_stream_for_missing_keys(self, missing_keys):
2251
# missing keys can only occur when we are byte copying and not
2252
# translating (because translation means we don't send
2253
# unreconstructable deltas ever).
2255
keys['texts'] = set()
2256
keys['revisions'] = set()
2257
keys['inventories'] = set()
2258
keys['chk_bytes'] = set()
2259
keys['signatures'] = set()
2260
for key in missing_keys:
2261
keys[key[0]].add(key[1:])
2262
if len(keys['revisions']):
2263
# If we allowed copying revisions at this point, we could end up
2264
# copying a revision without copying its required texts: a
2265
# violation of the requirements for repository integrity.
2266
raise AssertionError(
2267
'cannot copy revisions to fill in missing deltas %s' % (
2268
keys['revisions'],))
2269
for substream_kind, keys in keys.iteritems():
2270
vf = getattr(self.from_repository, substream_kind)
2271
if vf is None and keys:
2272
raise AssertionError(
2273
"cannot fill in keys for a versioned file we don't"
2274
" have: %s needs %s" % (substream_kind, keys))
2276
# No need to stream something we don't have
2278
if substream_kind == 'inventories':
2279
# Some missing keys are genuinely ghosts, filter those out.
2280
present = self.from_repository.inventories.get_parent_map(keys)
2281
revs = [key[0] for key in present]
2282
# Get the inventory stream more-or-less as we do for the
2283
# original stream; there's no reason to assume that records
2284
# direct from the source will be suitable for the sink. (Think
2285
# e.g. 2a -> 1.9-rich-root).
2286
for info in self._get_inventory_stream(revs, missing=True):
2290
# Ask for full texts always so that we don't need more round trips
2291
# after this stream.
2292
# Some of the missing keys are genuinely ghosts, so filter absent
2293
# records. The Sink is responsible for doing another check to
2294
# ensure that ghosts don't introduce missing data for future
2296
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2297
self.to_format._fetch_order, True))
2298
yield substream_kind, stream
2300
def inventory_fetch_order(self):
2301
if self._rich_root_upgrade():
2302
return 'topological'
2304
return self.to_format._fetch_order
2306
def _rich_root_upgrade(self):
2307
return (not self.from_repository._format.rich_root_data and
2308
self.to_format.rich_root_data)
2310
def _get_inventory_stream(self, revision_ids, missing=False):
2311
from_format = self.from_repository._format
2312
if (from_format.supports_chks and self.to_format.supports_chks and
2313
from_format.network_name() == self.to_format.network_name()):
2314
raise AssertionError(
2315
"this case should be handled by GroupCHKStreamSource")
2316
elif 'forceinvdeltas' in debug.debug_flags:
2317
return self._get_convertable_inventory_stream(revision_ids,
2318
delta_versus_null=missing)
2319
elif from_format.network_name() == self.to_format.network_name():
2321
return self._get_simple_inventory_stream(revision_ids,
2323
elif (not from_format.supports_chks and not self.to_format.supports_chks
2324
and from_format._serializer == self.to_format._serializer):
2325
# Essentially the same format.
2326
return self._get_simple_inventory_stream(revision_ids,
2329
# Any time we switch serializations, we want to use an
2330
# inventory-delta based approach.
2331
return self._get_convertable_inventory_stream(revision_ids,
2332
delta_versus_null=missing)
2334
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2335
# NB: This currently reopens the inventory weave in source;
2336
# using a single stream interface instead would avoid this.
2337
from_weave = self.from_repository.inventories
2339
delta_closure = True
2341
delta_closure = not self.delta_on_metadata()
2342
yield ('inventories', from_weave.get_record_stream(
2343
[(rev_id,) for rev_id in revision_ids],
2344
self.inventory_fetch_order(), delta_closure))
2346
def _get_convertable_inventory_stream(self, revision_ids,
2347
delta_versus_null=False):
2348
# The two formats are sufficiently different that there is no fast
2349
# path, so we need to send just inventorydeltas, which any
2350
# sufficiently modern client can insert into any repository.
2351
# The StreamSink code expects to be able to
2352
# convert on the target, so we need to put bytes-on-the-wire that can
2353
# be converted. That means inventory deltas (if the remote is <1.19,
2354
# RemoteStreamSink will fallback to VFS to insert the deltas).
2355
yield ('inventory-deltas',
2356
self._stream_invs_as_deltas(revision_ids,
2357
delta_versus_null=delta_versus_null))
2359
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2360
"""Return a stream of inventory-deltas for the given rev ids.
2362
:param revision_ids: The list of inventories to transmit
2363
:param delta_versus_null: Don't try to find a minimal delta for this
2364
entry, instead compute the delta versus the NULL_REVISION. This
2365
effectively streams a complete inventory. Used for stuff like
2366
filling in missing parents, etc.
2368
from_repo = self.from_repository
2369
revision_keys = [(rev_id,) for rev_id in revision_ids]
2370
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2371
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2373
inventories = self.from_repository.iter_inventories(
2374
revision_ids, 'topological')
2375
format = from_repo._format
2376
invs_sent_so_far = set([_mod_revision.NULL_REVISION])
2377
inventory_cache = lru_cache.LRUCache(50)
2378
null_inventory = from_repo.revision_tree(
2379
_mod_revision.NULL_REVISION).inventory
2380
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2381
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2382
# repo back into a non-rich-root repo ought to be allowed)
2383
serializer = inventory_delta.InventoryDeltaSerializer(
2384
versioned_root=format.rich_root_data,
2385
tree_references=format.supports_tree_reference)
2386
for inv in inventories:
2387
key = (inv.revision_id,)
2388
parent_keys = parent_map.get(key, ())
2390
if not delta_versus_null and parent_keys:
2391
# The caller did not ask for complete inventories and we have
2392
# some parents that we can delta against. Make a delta against
2393
# each parent so that we can find the smallest.
2394
parent_ids = [parent_key[0] for parent_key in parent_keys]
2395
for parent_id in parent_ids:
2396
if parent_id not in invs_sent_so_far:
2397
# We don't know that the remote side has this basis, so
2400
if parent_id == _mod_revision.NULL_REVISION:
2401
parent_inv = null_inventory
2403
parent_inv = inventory_cache.get(parent_id, None)
2404
if parent_inv is None:
2405
parent_inv = from_repo.get_inventory(parent_id)
2406
candidate_delta = inv._make_delta(parent_inv)
2407
if (delta is None or
2408
len(delta) > len(candidate_delta)):
2409
delta = candidate_delta
2410
basis_id = parent_id
2412
# Either none of the parents ended up being suitable, or we
2413
# were asked to delta against NULL
2414
basis_id = _mod_revision.NULL_REVISION
2415
delta = inv._make_delta(null_inventory)
2416
invs_sent_so_far.add(inv.revision_id)
2417
inventory_cache[inv.revision_id] = inv
2418
delta_serialized = ''.join(
2419
serializer.delta_to_lines(basis_id, key[-1], delta))
2420
yield versionedfile.FulltextContentFactory(
2421
key, parent_keys, None, delta_serialized)
2424
class _VersionedFileChecker(object):
2426
def __init__(self, repository, text_key_references=None, ancestors=None):
2427
self.repository = repository
2428
self.text_index = self.repository._generate_text_key_index(
2429
text_key_references=text_key_references, ancestors=ancestors)
2431
def calculate_file_version_parents(self, text_key):
2432
"""Calculate the correct parents for a file version according to
2435
parent_keys = self.text_index[text_key]
2436
if parent_keys == [_mod_revision.NULL_REVISION]:
2438
return tuple(parent_keys)
2440
def check_file_version_parents(self, texts, progress_bar=None):
2441
"""Check the parents stored in a versioned file are correct.
2443
It also detects file versions that are not referenced by their
2444
corresponding revision's inventory.
2446
:returns: A tuple of (wrong_parents, dangling_file_versions).
2447
wrong_parents is a dict mapping {revision_id: (stored_parents,
2448
correct_parents)} for each revision_id where the stored parents
2449
are not correct. dangling_file_versions is a set of (file_id,
2450
revision_id) tuples for versions that are present in this versioned
2451
file, but not used by the corresponding inventory.
2453
local_progress = None
2454
if progress_bar is None:
2455
local_progress = ui.ui_factory.nested_progress_bar()
2456
progress_bar = local_progress
2458
return self._check_file_version_parents(texts, progress_bar)
2461
local_progress.finished()
2463
def _check_file_version_parents(self, texts, progress_bar):
2464
"""See check_file_version_parents."""
2466
self.file_ids = set([file_id for file_id, _ in
2467
self.text_index.iterkeys()])
2468
# text keys is now grouped by file_id
2469
n_versions = len(self.text_index)
2470
progress_bar.update(gettext('loading text store'), 0, n_versions)
2471
parent_map = self.repository.texts.get_parent_map(self.text_index)
2472
# On unlistable transports this could well be empty/error...
2473
text_keys = self.repository.texts.keys()
2474
unused_keys = frozenset(text_keys) - set(self.text_index)
2475
for num, key in enumerate(self.text_index.iterkeys()):
2476
progress_bar.update(gettext('checking text graph'), num, n_versions)
2477
correct_parents = self.calculate_file_version_parents(key)
2479
knit_parents = parent_map[key]
2480
except errors.RevisionNotPresent:
2483
if correct_parents != knit_parents:
2484
wrong_parents[key] = (knit_parents, correct_parents)
2485
return wrong_parents, unused_keys
2488
class InterVersionedFileRepository(InterRepository):
2490
_walk_to_common_revisions_batch_size = 50
2493
def fetch(self, revision_id=None, find_ghosts=False,
2495
"""Fetch the content required to construct revision_id.
2497
The content is copied from self.source to self.target.
2499
:param revision_id: if None all content is copied, if NULL_REVISION no
2503
if self.target._format.experimental:
2504
ui.ui_factory.show_user_warning('experimental_format_fetch',
2505
from_format=self.source._format,
2506
to_format=self.target._format)
2507
from bzrlib.fetch import RepoFetcher
2508
# See <https://launchpad.net/bugs/456077> asking for a warning here
2509
if self.source._format.network_name() != self.target._format.network_name():
2510
ui.ui_factory.show_user_warning('cross_format_fetch',
2511
from_format=self.source._format,
2512
to_format=self.target._format)
2513
f = RepoFetcher(to_repository=self.target,
2514
from_repository=self.source,
2515
last_revision=revision_id,
2516
fetch_spec=fetch_spec,
2517
find_ghosts=find_ghosts)
2519
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2520
"""Walk out from revision_ids in source to revisions target has.
2522
:param revision_ids: The start point for the search.
2523
:return: A set of revision ids.
2525
target_graph = self.target.get_graph()
2526
revision_ids = frozenset(revision_ids)
2528
all_wanted_revs = revision_ids.union(if_present_ids)
2530
all_wanted_revs = revision_ids
2531
missing_revs = set()
2532
source_graph = self.source.get_graph()
2533
# ensure we don't pay silly lookup costs.
2534
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2535
null_set = frozenset([_mod_revision.NULL_REVISION])
2536
searcher_exhausted = False
2540
# Iterate the searcher until we have enough next_revs
2541
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2543
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2544
next_revs.update(next_revs_part)
2545
ghosts.update(ghosts_part)
2546
except StopIteration:
2547
searcher_exhausted = True
2549
# If there are ghosts in the source graph, and the caller asked for
2550
# them, make sure that they are present in the target.
2551
# We don't care about other ghosts as we can't fetch them and
2552
# haven't been asked to.
2553
ghosts_to_check = set(revision_ids.intersection(ghosts))
2554
revs_to_get = set(next_revs).union(ghosts_to_check)
2556
have_revs = set(target_graph.get_parent_map(revs_to_get))
2557
# we always have NULL_REVISION present.
2558
have_revs = have_revs.union(null_set)
2559
# Check if the target is missing any ghosts we need.
2560
ghosts_to_check.difference_update(have_revs)
2562
# One of the caller's revision_ids is a ghost in both the
2563
# source and the target.
2564
raise errors.NoSuchRevision(
2565
self.source, ghosts_to_check.pop())
2566
missing_revs.update(next_revs - have_revs)
2567
# Because we may have walked past the original stop point, make
2568
# sure everything is stopped
2569
stop_revs = searcher.find_seen_ancestors(have_revs)
2570
searcher.stop_searching_any(stop_revs)
2571
if searcher_exhausted:
2573
return searcher.get_result()
2576
def search_missing_revision_ids(self,
2577
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
2578
find_ghosts=True, revision_ids=None, if_present_ids=None,
2580
"""Return the revision ids that source has that target does not.
2582
:param revision_id: only return revision ids included by this
2584
:param revision_ids: return revision ids included by these
2585
revision_ids. NoSuchRevision will be raised if any of these
2586
revisions are not present.
2587
:param if_present_ids: like revision_ids, but will not cause
2588
NoSuchRevision if any of these are absent, instead they will simply
2589
not be in the result. This is useful for e.g. finding revisions
2590
to fetch for tags, which may reference absent revisions.
2591
:param find_ghosts: If True find missing revisions in deep history
2592
rather than just finding the surface difference.
2593
:return: A bzrlib.graph.SearchResult.
2595
if symbol_versioning.deprecated_passed(revision_id):
2596
symbol_versioning.warn(
2597
'search_missing_revision_ids(revision_id=...) was '
2598
'deprecated in 2.4. Use revision_ids=[...] instead.',
2599
DeprecationWarning, stacklevel=2)
2600
if revision_ids is not None:
2601
raise AssertionError(
2602
'revision_ids is mutually exclusive with revision_id')
2603
if revision_id is not None:
2604
revision_ids = [revision_id]
2606
# stop searching at found target revisions.
2607
if not find_ghosts and (revision_ids is not None or if_present_ids is
2609
result = self._walk_to_common_revisions(revision_ids,
2610
if_present_ids=if_present_ids)
2613
result_set = result.get_keys()
2615
# generic, possibly worst case, slow code path.
2616
target_ids = set(self.target.all_revision_ids())
2617
source_ids = self._present_source_revisions_for(
2618
revision_ids, if_present_ids)
2619
result_set = set(source_ids).difference(target_ids)
2620
if limit is not None:
2621
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2622
result_set = set(itertools.islice(topo_ordered, limit))
2623
return self.source.revision_ids_to_search_result(result_set)
2625
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2626
"""Returns set of all revisions in ancestry of revision_ids present in
2629
:param revision_ids: if None, all revisions in source are returned.
2630
:param if_present_ids: like revision_ids, but if any/all of these are
2631
absent no error is raised.
2633
if revision_ids is not None or if_present_ids is not None:
2634
# First, ensure all specified revisions exist. Callers expect
2635
# NoSuchRevision when they pass absent revision_ids here.
2636
if revision_ids is None:
2637
revision_ids = set()
2638
if if_present_ids is None:
2639
if_present_ids = set()
2640
revision_ids = set(revision_ids)
2641
if_present_ids = set(if_present_ids)
2642
all_wanted_ids = revision_ids.union(if_present_ids)
2643
graph = self.source.get_graph()
2644
present_revs = set(graph.get_parent_map(all_wanted_ids))
2645
missing = revision_ids.difference(present_revs)
2647
raise errors.NoSuchRevision(self.source, missing.pop())
2648
found_ids = all_wanted_ids.intersection(present_revs)
2649
source_ids = [rev_id for (rev_id, parents) in
2650
graph.iter_ancestry(found_ids)
2651
if rev_id != _mod_revision.NULL_REVISION
2652
and parents is not None]
2654
source_ids = self.source.all_revision_ids()
2655
return set(source_ids)
2658
def _get_repo_format_to_test(self):
2662
def is_compatible(cls, source, target):
2663
# The default implementation is compatible with everything
2664
return (source._format.supports_full_versioned_files and
2665
target._format.supports_full_versioned_files)
2668
class InterDifferingSerializer(InterVersionedFileRepository):
2671
def _get_repo_format_to_test(self):
2675
def is_compatible(source, target):
2676
if not source._format.supports_full_versioned_files:
2678
if not target._format.supports_full_versioned_files:
2680
# This is redundant with format.check_conversion_target(), however that
2681
# raises an exception, and we just want to say "False" as in we won't
2682
# support converting between these formats.
2683
if 'IDS_never' in debug.debug_flags:
2685
if source.supports_rich_root() and not target.supports_rich_root():
2687
if (source._format.supports_tree_reference
2688
and not target._format.supports_tree_reference):
2690
if target._fallback_repositories and target._format.supports_chks:
2691
# IDS doesn't know how to copy CHKs for the parent inventories it
2692
# adds to stacked repos.
2694
if 'IDS_always' in debug.debug_flags:
2696
# Only use this code path for local source and target. IDS does far
2697
# too much IO (both bandwidth and roundtrips) over a network.
2698
if not source.bzrdir.transport.base.startswith('file:///'):
2700
if not target.bzrdir.transport.base.startswith('file:///'):
2704
def _get_trees(self, revision_ids, cache):
2706
for rev_id in revision_ids:
2708
possible_trees.append((rev_id, cache[rev_id]))
2710
# Not cached, but inventory might be present anyway.
2712
tree = self.source.revision_tree(rev_id)
2713
except errors.NoSuchRevision:
2714
# Nope, parent is ghost.
2717
cache[rev_id] = tree
2718
possible_trees.append((rev_id, tree))
2719
return possible_trees
2721
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2722
"""Get the best delta and base for this revision.
2724
:return: (basis_id, delta)
2727
# Generate deltas against each tree, to find the shortest.
2728
texts_possibly_new_in_tree = set()
2729
for basis_id, basis_tree in possible_trees:
2730
delta = tree.inventory._make_delta(basis_tree.inventory)
2731
for old_path, new_path, file_id, new_entry in delta:
2732
if new_path is None:
2733
# This file_id isn't present in the new rev, so we don't
2737
# Rich roots are handled elsewhere...
2739
kind = new_entry.kind
2740
if kind != 'directory' and kind != 'file':
2741
# No text record associated with this inventory entry.
2743
# This is a directory or file that has changed somehow.
2744
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2745
deltas.append((len(delta), basis_id, delta))
2747
return deltas[0][1:]
2749
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2750
"""Find all parent revisions that are absent, but for which the
2751
inventory is present, and copy those inventories.
2753
This is necessary to preserve correctness when the source is stacked
2754
without fallbacks configured. (Note that in cases like upgrade the
2755
source may be not have _fallback_repositories even though it is
2759
for parents in parent_map.values():
2760
parent_revs.update(parents)
2761
present_parents = self.source.get_parent_map(parent_revs)
2762
absent_parents = set(parent_revs).difference(present_parents)
2763
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2764
(rev_id,) for rev_id in absent_parents)
2765
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2766
for parent_tree in self.source.revision_trees(parent_inv_ids):
2767
current_revision_id = parent_tree.get_revision_id()
2768
parents_parents_keys = parent_invs_keys_for_stacking[
2769
(current_revision_id,)]
2770
parents_parents = [key[-1] for key in parents_parents_keys]
2771
basis_id = _mod_revision.NULL_REVISION
2772
basis_tree = self.source.revision_tree(basis_id)
2773
delta = parent_tree.inventory._make_delta(basis_tree.inventory)
2774
self.target.add_inventory_by_delta(
2775
basis_id, delta, current_revision_id, parents_parents)
2776
cache[current_revision_id] = parent_tree
2778
def _fetch_batch(self, revision_ids, basis_id, cache):
2779
"""Fetch across a few revisions.
2781
:param revision_ids: The revisions to copy
2782
:param basis_id: The revision_id of a tree that must be in cache, used
2783
as a basis for delta when no other base is available
2784
:param cache: A cache of RevisionTrees that we can use.
2785
:return: The revision_id of the last converted tree. The RevisionTree
2786
for it will be in cache
2788
# Walk though all revisions; get inventory deltas, copy referenced
2789
# texts that delta references, insert the delta, revision and
2791
root_keys_to_create = set()
2794
pending_revisions = []
2795
parent_map = self.source.get_parent_map(revision_ids)
2796
self._fetch_parent_invs_for_stacking(parent_map, cache)
2797
self.source._safe_to_return_from_cache = True
2798
for tree in self.source.revision_trees(revision_ids):
2799
# Find a inventory delta for this revision.
2800
# Find text entries that need to be copied, too.
2801
current_revision_id = tree.get_revision_id()
2802
parent_ids = parent_map.get(current_revision_id, ())
2803
parent_trees = self._get_trees(parent_ids, cache)
2804
possible_trees = list(parent_trees)
2805
if len(possible_trees) == 0:
2806
# There either aren't any parents, or the parents are ghosts,
2807
# so just use the last converted tree.
2808
possible_trees.append((basis_id, cache[basis_id]))
2809
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2811
revision = self.source.get_revision(current_revision_id)
2812
pending_deltas.append((basis_id, delta,
2813
current_revision_id, revision.parent_ids))
2814
if self._converting_to_rich_root:
2815
self._revision_id_to_root_id[current_revision_id] = \
2817
# Determine which texts are in present in this revision but not in
2818
# any of the available parents.
2819
texts_possibly_new_in_tree = set()
2820
for old_path, new_path, file_id, entry in delta:
2821
if new_path is None:
2822
# This file_id isn't present in the new rev
2826
if not self.target.supports_rich_root():
2827
# The target doesn't support rich root, so we don't
2830
if self._converting_to_rich_root:
2831
# This can't be copied normally, we have to insert
2833
root_keys_to_create.add((file_id, entry.revision))
2836
texts_possibly_new_in_tree.add((file_id, entry.revision))
2837
for basis_id, basis_tree in possible_trees:
2838
basis_inv = basis_tree.inventory
2839
for file_key in list(texts_possibly_new_in_tree):
2840
file_id, file_revision = file_key
2842
entry = basis_inv[file_id]
2843
except errors.NoSuchId:
2845
if entry.revision == file_revision:
2846
texts_possibly_new_in_tree.remove(file_key)
2847
text_keys.update(texts_possibly_new_in_tree)
2848
pending_revisions.append(revision)
2849
cache[current_revision_id] = tree
2850
basis_id = current_revision_id
2851
self.source._safe_to_return_from_cache = False
2853
from_texts = self.source.texts
2854
to_texts = self.target.texts
2855
if root_keys_to_create:
2856
root_stream = _mod_fetch._new_root_data_stream(
2857
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2859
to_texts.insert_record_stream(root_stream)
2860
to_texts.insert_record_stream(from_texts.get_record_stream(
2861
text_keys, self.target._format._fetch_order,
2862
not self.target._format._fetch_uses_deltas))
2863
# insert inventory deltas
2864
for delta in pending_deltas:
2865
self.target.add_inventory_by_delta(*delta)
2866
if self.target._fallback_repositories:
2867
# Make sure this stacked repository has all the parent inventories
2868
# for the new revisions that we are about to insert. We do this
2869
# before adding the revisions so that no revision is added until
2870
# all the inventories it may depend on are added.
2871
# Note that this is overzealous, as we may have fetched these in an
2874
revision_ids = set()
2875
for revision in pending_revisions:
2876
revision_ids.add(revision.revision_id)
2877
parent_ids.update(revision.parent_ids)
2878
parent_ids.difference_update(revision_ids)
2879
parent_ids.discard(_mod_revision.NULL_REVISION)
2880
parent_map = self.source.get_parent_map(parent_ids)
2881
# we iterate over parent_map and not parent_ids because we don't
2882
# want to try copying any revision which is a ghost
2883
for parent_tree in self.source.revision_trees(parent_map):
2884
current_revision_id = parent_tree.get_revision_id()
2885
parents_parents = parent_map[current_revision_id]
2886
possible_trees = self._get_trees(parents_parents, cache)
2887
if len(possible_trees) == 0:
2888
# There either aren't any parents, or the parents are
2889
# ghosts, so just use the last converted tree.
2890
possible_trees.append((basis_id, cache[basis_id]))
2891
basis_id, delta = self._get_delta_for_revision(parent_tree,
2892
parents_parents, possible_trees)
2893
self.target.add_inventory_by_delta(
2894
basis_id, delta, current_revision_id, parents_parents)
2895
# insert signatures and revisions
2896
for revision in pending_revisions:
2898
signature = self.source.get_signature_text(
2899
revision.revision_id)
2900
self.target.add_signature_text(revision.revision_id,
2902
except errors.NoSuchRevision:
2904
self.target.add_revision(revision.revision_id, revision)
2907
def _fetch_all_revisions(self, revision_ids, pb):
2908
"""Fetch everything for the list of revisions.
2910
:param revision_ids: The list of revisions to fetch. Must be in
2912
:param pb: A ProgressTask
2915
basis_id, basis_tree = self._get_basis(revision_ids[0])
2917
cache = lru_cache.LRUCache(100)
2918
cache[basis_id] = basis_tree
2919
del basis_tree # We don't want to hang on to it here
2923
for offset in range(0, len(revision_ids), batch_size):
2924
self.target.start_write_group()
2926
pb.update(gettext('Transferring revisions'), offset,
2928
batch = revision_ids[offset:offset+batch_size]
2929
basis_id = self._fetch_batch(batch, basis_id, cache)
2931
self.source._safe_to_return_from_cache = False
2932
self.target.abort_write_group()
2935
hint = self.target.commit_write_group()
2938
if hints and self.target._format.pack_compresses:
2939
self.target.pack(hint=hints)
2940
pb.update(gettext('Transferring revisions'), len(revision_ids),
2944
def fetch(self, revision_id=None, find_ghosts=False,
2946
"""See InterRepository.fetch()."""
2947
if fetch_spec is not None:
2948
revision_ids = fetch_spec.get_keys()
2951
if self.source._format.experimental:
2952
ui.ui_factory.show_user_warning('experimental_format_fetch',
2953
from_format=self.source._format,
2954
to_format=self.target._format)
2955
if (not self.source.supports_rich_root()
2956
and self.target.supports_rich_root()):
2957
self._converting_to_rich_root = True
2958
self._revision_id_to_root_id = {}
2960
self._converting_to_rich_root = False
2961
# See <https://launchpad.net/bugs/456077> asking for a warning here
2962
if self.source._format.network_name() != self.target._format.network_name():
2963
ui.ui_factory.show_user_warning('cross_format_fetch',
2964
from_format=self.source._format,
2965
to_format=self.target._format)
2966
if revision_ids is None:
2968
search_revision_ids = [revision_id]
2970
search_revision_ids = None
2971
revision_ids = self.target.search_missing_revision_ids(self.source,
2972
revision_ids=search_revision_ids,
2973
find_ghosts=find_ghosts).get_keys()
2974
if not revision_ids:
2976
revision_ids = tsort.topo_sort(
2977
self.source.get_graph().get_parent_map(revision_ids))
2978
if not revision_ids:
2980
# Walk though all revisions; get inventory deltas, copy referenced
2981
# texts that delta references, insert the delta, revision and
2983
pb = ui.ui_factory.nested_progress_bar()
2985
self._fetch_all_revisions(revision_ids, pb)
2988
return len(revision_ids), 0
2990
def _get_basis(self, first_revision_id):
2991
"""Get a revision and tree which exists in the target.
2993
This assumes that first_revision_id is selected for transmission
2994
because all other ancestors are already present. If we can't find an
2995
ancestor we fall back to NULL_REVISION since we know that is safe.
2997
:return: (basis_id, basis_tree)
2999
first_rev = self.source.get_revision(first_revision_id)
3001
basis_id = first_rev.parent_ids[0]
3002
# only valid as a basis if the target has it
3003
self.target.get_revision(basis_id)
3004
# Try to get a basis tree - if it's a ghost it will hit the
3005
# NoSuchRevision case.
3006
basis_tree = self.source.revision_tree(basis_id)
3007
except (IndexError, errors.NoSuchRevision):
3008
basis_id = _mod_revision.NULL_REVISION
3009
basis_tree = self.source.revision_tree(basis_id)
3010
return basis_id, basis_tree
3013
class InterSameDataRepository(InterVersionedFileRepository):
3014
"""Code for converting between repositories that represent the same data.
3016
Data format and model must match for this to work.
3020
def _get_repo_format_to_test(self):
3021
"""Repository format for testing with.
3023
InterSameData can pull from subtree to subtree and from non-subtree to
3024
non-subtree, so we test this with the richest repository format.
3026
from bzrlib.repofmt import knitrepo
3027
return knitrepo.RepositoryFormatKnit3()
3030
def is_compatible(source, target):
3032
InterRepository._same_model(source, target) and
3033
source._format.supports_full_versioned_files and
3034
target._format.supports_full_versioned_files)
3037
InterRepository.register_optimiser(InterVersionedFileRepository)
3038
InterRepository.register_optimiser(InterDifferingSerializer)
3039
InterRepository.register_optimiser(InterSameDataRepository)
3042
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3043
"""Install all revision data into a repository.
3045
Accepts an iterable of revision, tree, signature tuples. The signature
3048
repository.start_write_group()
3050
inventory_cache = lru_cache.LRUCache(10)
3051
for n, (revision, revision_tree, signature) in enumerate(iterable):
3052
_install_revision(repository, revision, revision_tree, signature,
3055
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3057
repository.abort_write_group()
3060
repository.commit_write_group()
3063
def _install_revision(repository, rev, revision_tree, signature,
3065
"""Install all revision data into a repository."""
3066
present_parents = []
3068
for p_id in rev.parent_ids:
3069
if repository.has_revision(p_id):
3070
present_parents.append(p_id)
3071
parent_trees[p_id] = repository.revision_tree(p_id)
3073
parent_trees[p_id] = repository.revision_tree(
3074
_mod_revision.NULL_REVISION)
3076
inv = revision_tree.inventory
3077
entries = inv.iter_entries()
3078
# backwards compatibility hack: skip the root id.
3079
if not repository.supports_rich_root():
3080
path, root = entries.next()
3081
if root.revision != rev.revision_id:
3082
raise errors.IncompatibleRevision(repr(repository))
3084
for path, ie in entries:
3085
text_keys[(ie.file_id, ie.revision)] = ie
3086
text_parent_map = repository.texts.get_parent_map(text_keys)
3087
missing_texts = set(text_keys) - set(text_parent_map)
3088
# Add the texts that are not already present
3089
for text_key in missing_texts:
3090
ie = text_keys[text_key]
3092
# FIXME: TODO: The following loop overlaps/duplicates that done by
3093
# commit to determine parents. There is a latent/real bug here where
3094
# the parents inserted are not those commit would do - in particular
3095
# they are not filtered by heads(). RBC, AB
3096
for revision, tree in parent_trees.iteritems():
3097
if not tree.has_id(ie.file_id):
3099
parent_id = tree.get_file_revision(ie.file_id)
3100
if parent_id in text_parents:
3102
text_parents.append((ie.file_id, parent_id))
3103
lines = revision_tree.get_file(ie.file_id).readlines()
3104
repository.texts.add_lines(text_key, text_parents, lines)
3106
# install the inventory
3107
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3108
# Cache this inventory
3109
inventory_cache[rev.revision_id] = inv
3111
basis_inv = inventory_cache[rev.parent_ids[0]]
3113
repository.add_inventory(rev.revision_id, inv, present_parents)
3115
delta = inv._make_delta(basis_inv)
3116
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3117
rev.revision_id, present_parents)
3119
repository.add_inventory(rev.revision_id, inv, present_parents)
3120
except errors.RevisionAlreadyPresent:
3122
if signature is not None:
3123
repository.add_signature_text(rev.revision_id, signature)
3124
repository.add_revision(rev.revision_id, rev, inv)
3127
def install_revision(repository, rev, revision_tree):
3128
"""Install all revision data into a repository."""
3129
install_revisions(repository, [(rev, revision_tree, None)])