1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Repository formats built around versioned files."""
19
from __future__ import absolute_import
22
from ..lazy_import import lazy_import
23
lazy_import(globals(), """
28
config as _mod_config,
36
revision as _mod_revision,
37
serializer as _mod_serializer,
42
from breezy.bzr import (
48
from breezy.recordcounter import RecordCounter
49
from breezy.revisiontree import InventoryRevisionTree
50
from breezy.testament import Testament
51
from breezy.i18n import gettext
57
from ..decorators import (
62
from .inventory import (
69
from ..repository import (
75
from .repository import (
77
RepositoryFormatMetaDir,
80
from ..sixish import (
91
class VersionedFileRepositoryFormat(RepositoryFormat):
92
"""Base class for all repository formats that are VersionedFiles-based."""
94
supports_full_versioned_files = True
95
supports_versioned_directories = True
96
supports_unreferenced_revisions = True
98
# Should commit add an inventory, or an inventory delta to the repository.
99
_commit_inv_deltas = True
100
# What order should fetch operations request streams in?
101
# The default is unordered as that is the cheapest for an origin to
103
_fetch_order = 'unordered'
104
# Does this repository format use deltas that can be fetched as-deltas ?
105
# (E.g. knits, where the knit deltas can be transplanted intact.
106
# We default to False, which will ensure that enough data to get
107
# a full text out of any fetch stream will be grabbed.
108
_fetch_uses_deltas = False
111
class VersionedFileCommitBuilder(CommitBuilder):
112
"""Commit builder implementation for versioned files based repositories.
115
# this commit builder supports the record_entry_contents interface
116
supports_record_entry_contents = True
118
# the default CommitBuilder does not manage trees whose root is versioned.
119
_versioned_root = False
121
def __init__(self, repository, parents, config_stack, timestamp=None,
122
timezone=None, committer=None, revprops=None,
123
revision_id=None, lossy=False):
124
super(VersionedFileCommitBuilder, self).__init__(repository,
125
parents, config_stack, timestamp, timezone, committer, revprops,
128
basis_id = self.parents[0]
130
basis_id = _mod_revision.NULL_REVISION
131
self.basis_delta_revision = basis_id
132
self.new_inventory = Inventory(None)
133
self._basis_delta = []
134
self.__heads = graph.HeadsCache(repository.get_graph()).heads
135
# memo'd check for no-op commits.
136
self._any_changes = False
137
# API compatibility, older code that used CommitBuilder did not call
138
# .record_delete(), which means the delta that is computed would not be
139
# valid. Callers that will call record_delete() should call
140
# .will_record_deletes() to indicate that.
141
self._recording_deletes = False
143
def will_record_deletes(self):
144
"""Tell the commit builder that deletes are being notified.
146
This enables the accumulation of an inventory delta; for the resulting
147
commit to be valid, deletes against the basis MUST be recorded via
148
builder.record_delete().
150
self._recording_deletes = True
152
def any_changes(self):
153
"""Return True if any entries were changed.
155
This includes merge-only changes. It is the core for the --unchanged
158
:return: True if any changes have occured.
160
return self._any_changes
162
def _ensure_fallback_inventories(self):
163
"""Ensure that appropriate inventories are available.
165
This only applies to repositories that are stacked, and is about
166
enusring the stacking invariants. Namely, that for any revision that is
167
present, we either have all of the file content, or we have the parent
168
inventory and the delta file content.
170
if not self.repository._fallback_repositories:
172
if not self.repository._format.supports_chks:
173
raise errors.BzrError("Cannot commit directly to a stacked branch"
174
" in pre-2a formats. See "
175
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
176
# This is a stacked repo, we need to make sure we have the parent
177
# inventories for the parents.
178
parent_keys = [(p,) for p in self.parents]
179
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
180
missing_parent_keys = {pk for pk in parent_keys
181
if pk not in parent_map}
182
fallback_repos = list(reversed(self.repository._fallback_repositories))
183
missing_keys = [('inventories', pk[0])
184
for pk in missing_parent_keys]
186
while missing_keys and fallback_repos:
187
fallback_repo = fallback_repos.pop()
188
source = fallback_repo._get_source(self.repository._format)
189
sink = self.repository._get_sink()
190
stream = source.get_stream_for_missing_keys(missing_keys)
191
missing_keys = sink.insert_stream_without_locking(stream,
192
self.repository._format)
194
raise errors.BzrError('Unable to fill in parent inventories for a'
197
def commit(self, message):
198
"""Make the actual commit.
200
:return: The revision id of the recorded revision.
202
self._validate_unicode_text(message, 'commit message')
203
rev = _mod_revision.Revision(
204
timestamp=self._timestamp,
205
timezone=self._timezone,
206
committer=self._committer,
208
inventory_sha1=self.inv_sha1,
209
revision_id=self._new_revision_id,
210
properties=self._revprops)
211
rev.parent_ids = self.parents
212
if self._config_stack.get('create_signatures') == _mod_config.SIGN_ALWAYS:
213
testament = Testament(rev, self.revision_tree())
214
plaintext = testament.as_short_text()
215
self.repository.store_revision_signature(
216
gpg.GPGStrategy(self._config_stack), plaintext,
217
self._new_revision_id)
218
self.repository._add_revision(rev)
219
self._ensure_fallback_inventories()
220
self.repository.commit_write_group()
221
return self._new_revision_id
224
"""Abort the commit that is being built.
226
self.repository.abort_write_group()
228
def revision_tree(self):
229
"""Return the tree that was just committed.
231
After calling commit() this can be called to get a
232
RevisionTree representing the newly committed tree. This is
233
preferred to calling Repository.revision_tree() because that may
234
require deserializing the inventory, while we already have a copy in
237
if self.new_inventory is None:
238
self.new_inventory = self.repository.get_inventory(
239
self._new_revision_id)
240
return InventoryRevisionTree(self.repository, self.new_inventory,
241
self._new_revision_id)
243
def finish_inventory(self):
244
"""Tell the builder that the inventory is finished.
246
:return: The inventory id in the repository, which can be used with
247
repository.get_inventory.
249
if self.new_inventory is None:
250
# an inventory delta was accumulated without creating a new
252
basis_id = self.basis_delta_revision
253
# We ignore the 'inventory' returned by add_inventory_by_delta
254
# because self.new_inventory is used to hint to the rest of the
255
# system what code path was taken
256
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
257
basis_id, self._basis_delta, self._new_revision_id,
260
if self.new_inventory.root is None:
261
raise AssertionError('Root entry should be supplied to'
262
' record_entry_contents, as of bzr 0.10.')
263
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
264
self.new_inventory.revision_id = self._new_revision_id
265
self.inv_sha1 = self.repository.add_inventory(
266
self._new_revision_id,
270
return self._new_revision_id
272
def _check_root(self, ie, parent_invs, tree):
273
"""Helper for record_entry_contents.
275
:param ie: An entry being added.
276
:param parent_invs: The inventories of the parent revisions of the
278
:param tree: The tree that is being committed.
280
# In this revision format, root entries have no knit or weave When
281
# serializing out to disk and back in root.revision is always
283
ie.revision = self._new_revision_id
285
def _require_root_change(self, tree):
286
"""Enforce an appropriate root object change.
288
This is called once when record_iter_changes is called, if and only if
289
the root was not in the delta calculated by record_iter_changes.
291
:param tree: The tree which is being committed.
293
if len(self.parents) == 0:
294
raise errors.RootMissing()
295
entry = entry_factory['directory'](tree.path2id(''), '',
297
entry.revision = self._new_revision_id
298
self._basis_delta.append(('', '', entry.file_id, entry))
300
def _get_delta(self, ie, basis_inv, path):
301
"""Get a delta against the basis inventory for ie."""
302
if not basis_inv.has_id(ie.file_id):
304
result = (None, path, ie.file_id, ie)
305
self._basis_delta.append(result)
307
elif ie != basis_inv[ie.file_id]:
309
# TODO: avoid tis id2path call.
310
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
311
self._basis_delta.append(result)
317
def _heads(self, file_id, revision_ids):
318
"""Calculate the graph heads for revision_ids in the graph of file_id.
320
This can use either a per-file graph or a global revision graph as we
321
have an identity relationship between the two graphs.
323
return self.__heads(revision_ids)
325
def get_basis_delta(self):
326
"""Return the complete inventory delta versus the basis inventory.
328
This has been built up with the calls to record_delete and
329
record_entry_contents. The client must have already called
330
will_record_deletes() to indicate that they will be generating a
333
:return: An inventory delta, suitable for use with apply_delta, or
334
Repository.add_inventory_by_delta, etc.
336
if not self._recording_deletes:
337
raise AssertionError("recording deletes not activated.")
338
return self._basis_delta
340
def record_delete(self, path, file_id):
341
"""Record that a delete occured against a basis tree.
343
This is an optional API - when used it adds items to the basis_delta
344
being accumulated by the commit builder. It cannot be called unless the
345
method will_record_deletes() has been called to inform the builder that
346
a delta is being supplied.
348
:param path: The path of the thing deleted.
349
:param file_id: The file id that was deleted.
351
if not self._recording_deletes:
352
raise AssertionError("recording deletes not activated.")
353
delta = (path, None, file_id, None)
354
self._basis_delta.append(delta)
355
self._any_changes = True
358
def record_entry_contents(self, ie, parent_invs, path, tree,
360
"""Record the content of ie from tree into the commit if needed.
362
Side effect: sets ie.revision when unchanged
364
:param ie: An inventory entry present in the commit.
365
:param parent_invs: The inventories of the parent revisions of the
367
:param path: The path the entry is at in the tree.
368
:param tree: The tree which contains this entry and should be used to
370
:param content_summary: Summary data from the tree about the paths
371
content - stat, length, exec, sha/link target. This is only
372
accessed when the entry has a revision of None - that is when it is
373
a candidate to commit.
374
:return: A tuple (change_delta, version_recorded, fs_hash).
375
change_delta is an inventory_delta change for this entry against
376
the basis tree of the commit, or None if no change occured against
378
version_recorded is True if a new version of the entry has been
379
recorded. For instance, committing a merge where a file was only
380
changed on the other side will return (delta, False).
381
fs_hash is either None, or the hash details for the path (currently
382
a tuple of the contents sha1 and the statvalue returned by
383
tree.get_file_with_stat()).
385
if self.new_inventory.root is None:
386
if ie.parent_id is not None:
387
raise errors.RootMissing()
388
self._check_root(ie, parent_invs, tree)
389
if ie.revision is None:
390
kind = content_summary[0]
392
# ie is carried over from a prior commit
394
# XXX: repository specific check for nested tree support goes here - if
395
# the repo doesn't want nested trees we skip it ?
396
if (kind == 'tree-reference' and
397
not self.repository._format.supports_tree_reference):
398
# mismatch between commit builder logic and repository:
399
# this needs the entry creation pushed down into the builder.
400
raise NotImplementedError('Missing repository subtree support.')
401
self.new_inventory.add(ie)
403
# TODO: slow, take it out of the inner loop.
405
basis_inv = parent_invs[0]
407
basis_inv = Inventory(root_id=None)
409
# ie.revision is always None if the InventoryEntry is considered
410
# for committing. We may record the previous parents revision if the
411
# content is actually unchanged against a sole head.
412
if ie.revision is not None:
413
if not self._versioned_root and path == '':
414
# repositories that do not version the root set the root's
415
# revision to the new commit even when no change occurs (more
416
# specifically, they do not record a revision on the root; and
417
# the rev id is assigned to the root during deserialisation -
418
# this masks when a change may have occurred against the basis.
419
# To match this we always issue a delta, because the revision
420
# of the root will always be changing.
421
if basis_inv.has_id(ie.file_id):
422
delta = (basis_inv.id2path(ie.file_id), path,
426
delta = (None, path, ie.file_id, ie)
427
self._basis_delta.append(delta)
428
return delta, False, None
430
# we don't need to commit this, because the caller already
431
# determined that an existing revision of this file is
432
# appropriate. If it's not being considered for committing then
433
# it and all its parents to the root must be unaltered so
434
# no-change against the basis.
435
if ie.revision == self._new_revision_id:
436
raise AssertionError("Impossible situation, a skipped "
437
"inventory entry (%r) claims to be modified in this "
438
"commit (%r).", (ie, self._new_revision_id))
439
return None, False, None
440
# XXX: Friction: parent_candidates should return a list not a dict
441
# so that we don't have to walk the inventories again.
442
parent_candidate_entries = ie.parent_candidates(parent_invs)
443
head_set = self._heads(ie.file_id, parent_candidate_entries)
445
for inv in parent_invs:
446
if inv.has_id(ie.file_id):
447
old_rev = inv[ie.file_id].revision
448
if old_rev in head_set:
449
heads.append(inv[ie.file_id].revision)
450
head_set.remove(inv[ie.file_id].revision)
453
# now we check to see if we need to write a new record to the
455
# We write a new entry unless there is one head to the ancestors, and
456
# the kind-derived content is unchanged.
458
# Cheapest check first: no ancestors, or more the one head in the
459
# ancestors, we write a new node.
463
# There is a single head, look it up for comparison
464
parent_entry = parent_candidate_entries[heads[0]]
465
# if the non-content specific data has changed, we'll be writing a
467
if (parent_entry.parent_id != ie.parent_id or
468
parent_entry.name != ie.name):
470
# now we need to do content specific checks:
472
# if the kind changed the content obviously has
473
if kind != parent_entry.kind:
475
# Stat cache fingerprint feedback for the caller - None as we usually
476
# don't generate one.
479
if content_summary[2] is None:
480
raise ValueError("Files must not have executable = None")
482
# We can't trust a check of the file length because of content
484
if (# if the exec bit has changed we have to store:
485
parent_entry.executable != content_summary[2]):
487
elif parent_entry.text_sha1 == content_summary[3]:
488
# all meta and content is unchanged (using a hash cache
489
# hit to check the sha)
490
ie.revision = parent_entry.revision
491
ie.text_size = parent_entry.text_size
492
ie.text_sha1 = parent_entry.text_sha1
493
ie.executable = parent_entry.executable
494
return self._get_delta(ie, basis_inv, path), False, None
496
# Either there is only a hash change(no hash cache entry,
497
# or same size content change), or there is no change on
499
# Provide the parent's hash to the store layer, so that the
500
# content is unchanged we will not store a new node.
501
nostore_sha = parent_entry.text_sha1
503
# We want to record a new node regardless of the presence or
504
# absence of a content change in the file.
506
ie.executable = content_summary[2]
507
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
509
text = file_obj.read()
513
ie.text_sha1, ie.text_size = self._add_text_to_weave(
514
ie.file_id, text, heads, nostore_sha)
515
# Let the caller know we generated a stat fingerprint.
516
fingerprint = (ie.text_sha1, stat_value)
517
except errors.ExistingContent:
518
# Turns out that the file content was unchanged, and we were
519
# only going to store a new node if it was changed. Carry over
521
ie.revision = parent_entry.revision
522
ie.text_size = parent_entry.text_size
523
ie.text_sha1 = parent_entry.text_sha1
524
ie.executable = parent_entry.executable
525
return self._get_delta(ie, basis_inv, path), False, None
526
elif kind == 'directory':
528
# all data is meta here, nothing specific to directory, so
530
ie.revision = parent_entry.revision
531
return self._get_delta(ie, basis_inv, path), False, None
532
self._add_text_to_weave(ie.file_id, '', heads, None)
533
elif kind == 'symlink':
534
current_link_target = content_summary[3]
536
# symlink target is not generic metadata, check if it has
538
if current_link_target != parent_entry.symlink_target:
541
# unchanged, carry over.
542
ie.revision = parent_entry.revision
543
ie.symlink_target = parent_entry.symlink_target
544
return self._get_delta(ie, basis_inv, path), False, None
545
ie.symlink_target = current_link_target
546
self._add_text_to_weave(ie.file_id, '', heads, None)
547
elif kind == 'tree-reference':
549
if content_summary[3] != parent_entry.reference_revision:
552
# unchanged, carry over.
553
ie.reference_revision = parent_entry.reference_revision
554
ie.revision = parent_entry.revision
555
return self._get_delta(ie, basis_inv, path), False, None
556
ie.reference_revision = content_summary[3]
557
if ie.reference_revision is None:
558
raise AssertionError("invalid content_summary for nested tree: %r"
559
% (content_summary,))
560
self._add_text_to_weave(ie.file_id, '', heads, None)
562
raise NotImplementedError('unknown kind')
563
ie.revision = self._new_revision_id
564
# The initial commit adds a root directory, but this in itself is not
565
# a worthwhile commit.
566
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
568
self._any_changes = True
569
return self._get_delta(ie, basis_inv, path), True, fingerprint
571
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
572
_entry_factory=entry_factory):
573
"""Record a new tree via iter_changes.
575
:param tree: The tree to obtain text contents from for changed objects.
576
:param basis_revision_id: The revision id of the tree the iter_changes
577
has been generated against. Currently assumed to be the same
578
as self.parents[0] - if it is not, errors may occur.
579
:param iter_changes: An iter_changes iterator with the changes to apply
580
to basis_revision_id. The iterator must not include any items with
581
a current kind of None - missing items must be either filtered out
582
or errored-on before record_iter_changes sees the item.
583
:param _entry_factory: Private method to bind entry_factory locally for
585
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
588
# Create an inventory delta based on deltas between all the parents and
589
# deltas between all the parent inventories. We use inventory delta's
590
# between the inventory objects because iter_changes masks
591
# last-changed-field only changes.
593
# file_id -> change map, change is fileid, paths, changed, versioneds,
594
# parents, names, kinds, executables
596
# {file_id -> revision_id -> inventory entry, for entries in parent
597
# trees that are not parents[0]
601
revtrees = list(self.repository.revision_trees(self.parents))
602
except errors.NoSuchRevision:
603
# one or more ghosts, slow path.
605
for revision_id in self.parents:
607
revtrees.append(self.repository.revision_tree(revision_id))
608
except errors.NoSuchRevision:
610
basis_revision_id = _mod_revision.NULL_REVISION
612
revtrees.append(self.repository.revision_tree(
613
_mod_revision.NULL_REVISION))
614
# The basis inventory from a repository
616
basis_tree = revtrees[0]
618
basis_tree = self.repository.revision_tree(
619
_mod_revision.NULL_REVISION)
620
basis_inv = basis_tree.root_inventory
621
if len(self.parents) > 0:
622
if basis_revision_id != self.parents[0] and not ghost_basis:
624
"arbitrary basis parents not yet supported with merges")
625
for revtree in revtrees[1:]:
626
for change in revtree.root_inventory._make_delta(basis_inv):
627
if change[1] is None:
628
# Not present in this parent.
630
if change[2] not in merged_ids:
631
if change[0] is not None:
632
basis_entry = basis_inv[change[2]]
633
merged_ids[change[2]] = [
635
basis_entry.revision,
638
parent_entries[change[2]] = {
640
basis_entry.revision:basis_entry,
642
change[3].revision:change[3],
645
merged_ids[change[2]] = [change[3].revision]
646
parent_entries[change[2]] = {change[3].revision:change[3]}
648
merged_ids[change[2]].append(change[3].revision)
649
parent_entries[change[2]][change[3].revision] = change[3]
652
# Setup the changes from the tree:
653
# changes maps file_id -> (change, [parent revision_ids])
655
for change in iter_changes:
656
# This probably looks up in basis_inv way to much.
657
if change[1][0] is not None:
658
head_candidate = [basis_inv[change[0]].revision]
661
changes[change[0]] = change, merged_ids.get(change[0],
663
unchanged_merged = set(merged_ids) - set(changes)
664
# Extend the changes dict with synthetic changes to record merges of
666
for file_id in unchanged_merged:
667
# Record a merged version of these items that did not change vs the
668
# basis. This can be either identical parallel changes, or a revert
669
# of a specific file after a merge. The recorded content will be
670
# that of the current tree (which is the same as the basis), but
671
# the per-file graph will reflect a merge.
672
# NB:XXX: We are reconstructing path information we had, this
673
# should be preserved instead.
674
# inv delta change: (file_id, (path_in_source, path_in_target),
675
# changed_content, versioned, parent, name, kind,
678
basis_entry = basis_inv[file_id]
679
except errors.NoSuchId:
680
# a change from basis->some_parents but file_id isn't in basis
681
# so was new in the merge, which means it must have changed
682
# from basis -> current, and as it hasn't the add was reverted
683
# by the user. So we discard this change.
687
(basis_inv.id2path(file_id), tree.id2path(file_id)),
689
(basis_entry.parent_id, basis_entry.parent_id),
690
(basis_entry.name, basis_entry.name),
691
(basis_entry.kind, basis_entry.kind),
692
(basis_entry.executable, basis_entry.executable))
693
changes[file_id] = (change, merged_ids[file_id])
694
# changes contains tuples with the change and a set of inventory
695
# candidates for the file.
697
# old_path, new_path, file_id, new_inventory_entry
698
seen_root = False # Is the root in the basis delta?
699
inv_delta = self._basis_delta
700
modified_rev = self._new_revision_id
701
for change, head_candidates in viewvalues(changes):
702
if change[3][1]: # versioned in target.
703
# Several things may be happening here:
704
# We may have a fork in the per-file graph
705
# - record a change with the content from tree
706
# We may have a change against < all trees
707
# - carry over the tree that hasn't changed
708
# We may have a change against all trees
709
# - record the change with the content from tree
712
entry = _entry_factory[kind](file_id, change[5][1],
714
head_set = self._heads(change[0], set(head_candidates))
717
for head_candidate in head_candidates:
718
if head_candidate in head_set:
719
heads.append(head_candidate)
720
head_set.remove(head_candidate)
723
# Could be a carry-over situation:
724
parent_entry_revs = parent_entries.get(file_id, None)
725
if parent_entry_revs:
726
parent_entry = parent_entry_revs.get(heads[0], None)
729
if parent_entry is None:
730
# The parent iter_changes was called against is the one
731
# that is the per-file head, so any change is relevant
732
# iter_changes is valid.
733
carry_over_possible = False
735
# could be a carry over situation
736
# A change against the basis may just indicate a merge,
737
# we need to check the content against the source of the
738
# merge to determine if it was changed after the merge
740
if (parent_entry.kind != entry.kind or
741
parent_entry.parent_id != entry.parent_id or
742
parent_entry.name != entry.name):
743
# Metadata common to all entries has changed
744
# against per-file parent
745
carry_over_possible = False
747
carry_over_possible = True
748
# per-type checks for changes against the parent_entry
751
# Cannot be a carry-over situation
752
carry_over_possible = False
753
# Populate the entry in the delta
755
# XXX: There is still a small race here: If someone reverts the content of a file
756
# after iter_changes examines and decides it has changed,
757
# we will unconditionally record a new version even if some
758
# other process reverts it while commit is running (with
759
# the revert happening after iter_changes did its
762
entry.executable = True
764
entry.executable = False
765
if (carry_over_possible and
766
parent_entry.executable == entry.executable):
767
# Check the file length, content hash after reading
769
nostore_sha = parent_entry.text_sha1
772
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
774
text = file_obj.read()
778
entry.text_sha1, entry.text_size = self._add_text_to_weave(
779
file_id, text, heads, nostore_sha)
780
yield file_id, change[1][1], (entry.text_sha1, stat_value)
781
except errors.ExistingContent:
782
# No content change against a carry_over parent
783
# Perhaps this should also yield a fs hash update?
785
entry.text_size = parent_entry.text_size
786
entry.text_sha1 = parent_entry.text_sha1
787
elif kind == 'symlink':
789
entry.symlink_target = tree.get_symlink_target(file_id)
790
if (carry_over_possible and
791
parent_entry.symlink_target == entry.symlink_target):
794
self._add_text_to_weave(change[0], '', heads, None)
795
elif kind == 'directory':
796
if carry_over_possible:
799
# Nothing to set on the entry.
800
# XXX: split into the Root and nonRoot versions.
801
if change[1][1] != '' or self.repository.supports_rich_root():
802
self._add_text_to_weave(change[0], '', heads, None)
803
elif kind == 'tree-reference':
804
if not self.repository._format.supports_tree_reference:
805
# This isn't quite sane as an error, but we shouldn't
806
# ever see this code path in practice: tree's don't
807
# permit references when the repo doesn't support tree
809
raise errors.UnsupportedOperation(tree.add_reference,
811
reference_revision = tree.get_reference_revision(change[0])
812
entry.reference_revision = reference_revision
813
if (carry_over_possible and
814
parent_entry.reference_revision == reference_revision):
817
self._add_text_to_weave(change[0], '', heads, None)
819
raise AssertionError('unknown kind %r' % kind)
821
entry.revision = modified_rev
823
entry.revision = parent_entry.revision
826
new_path = change[1][1]
827
inv_delta.append((change[1][0], new_path, change[0], entry))
830
self.new_inventory = None
831
# The initial commit adds a root directory, but this in itself is not
832
# a worthwhile commit.
833
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
834
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
835
# This should perhaps be guarded by a check that the basis we
836
# commit against is the basis for the commit and if not do a delta
838
self._any_changes = True
840
# housekeeping root entry changes do not affect no-change commits.
841
self._require_root_change(tree)
842
self.basis_delta_revision = basis_revision_id
844
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
845
parent_keys = tuple([(file_id, parent) for parent in parents])
846
return self.repository.texts._add_text(
847
(file_id, self._new_revision_id), parent_keys, new_text,
848
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
851
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
852
"""This commitbuilder actually records the root id"""
854
# the root entry gets versioned properly by this builder.
855
_versioned_root = True
857
def _check_root(self, ie, parent_invs, tree):
858
"""Helper for record_entry_contents.
860
:param ie: An entry being added.
861
:param parent_invs: The inventories of the parent revisions of the
863
:param tree: The tree that is being committed.
866
def _require_root_change(self, tree):
867
"""Enforce an appropriate root object change.
869
This is called once when record_iter_changes is called, if and only if
870
the root was not in the delta calculated by record_iter_changes.
872
:param tree: The tree which is being committed.
874
# versioned roots do not change unless the tree found a change.
877
class VersionedFileRepository(Repository):
878
"""Repository holding history for one or more branches.
880
The repository holds and retrieves historical information including
881
revisions and file history. It's normally accessed only by the Branch,
882
which views a particular line of development through that history.
884
The Repository builds on top of some byte storage facilies (the revisions,
885
signatures, inventories, texts and chk_bytes attributes) and a Transport,
886
which respectively provide byte storage and a means to access the (possibly
889
The byte storage facilities are addressed via tuples, which we refer to
890
as 'keys' throughout the code base. Revision_keys, inventory_keys and
891
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
892
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
893
byte string made up of a hash identifier and a hash value.
894
We use this interface because it allows low friction with the underlying
895
code that implements disk indices, network encoding and other parts of
898
:ivar revisions: A breezy.versionedfile.VersionedFiles instance containing
899
the serialised revisions for the repository. This can be used to obtain
900
revision graph information or to access raw serialised revisions.
901
The result of trying to insert data into the repository via this store
902
is undefined: it should be considered read-only except for implementors
904
:ivar signatures: A breezy.versionedfile.VersionedFiles instance containing
905
the serialised signatures for the repository. This can be used to
906
obtain access to raw serialised signatures. The result of trying to
907
insert data into the repository via this store is undefined: it should
908
be considered read-only except for implementors of repositories.
909
:ivar inventories: A breezy.versionedfile.VersionedFiles instance containing
910
the serialised inventories for the repository. This can be used to
911
obtain unserialised inventories. The result of trying to insert data
912
into the repository via this store is undefined: it should be
913
considered read-only except for implementors of repositories.
914
:ivar texts: A breezy.versionedfile.VersionedFiles instance containing the
915
texts of files and directories for the repository. This can be used to
916
obtain file texts or file graphs. Note that Repository.iter_file_bytes
917
is usually a better interface for accessing file texts.
918
The result of trying to insert data into the repository via this store
919
is undefined: it should be considered read-only except for implementors
921
:ivar chk_bytes: A breezy.versionedfile.VersionedFiles instance containing
922
any data the repository chooses to store or have indexed by its hash.
923
The result of trying to insert data into the repository via this store
924
is undefined: it should be considered read-only except for implementors
926
:ivar _transport: Transport for file access to repository, typically
927
pointing to .bzr/repository.
930
# What class to use for a CommitBuilder. Often it's simpler to change this
931
# in a Repository class subclass rather than to override
932
# get_commit_builder.
933
_commit_builder_class = VersionedFileCommitBuilder
935
def add_fallback_repository(self, repository):
936
"""Add a repository to use for looking up data not held locally.
938
:param repository: A repository.
940
if not self._format.supports_external_lookups:
941
raise errors.UnstackableRepositoryFormat(self._format, self.base)
942
# This can raise an exception, so should be done before we lock the
943
# fallback repository.
944
self._check_fallback_repository(repository)
946
# This repository will call fallback.unlock() when we transition to
947
# the unlocked state, so we make sure to increment the lock count
948
repository.lock_read()
949
self._fallback_repositories.append(repository)
950
self.texts.add_fallback_versioned_files(repository.texts)
951
self.inventories.add_fallback_versioned_files(repository.inventories)
952
self.revisions.add_fallback_versioned_files(repository.revisions)
953
self.signatures.add_fallback_versioned_files(repository.signatures)
954
if self.chk_bytes is not None:
955
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
957
@only_raises(errors.LockNotHeld, errors.LockBroken)
959
super(VersionedFileRepository, self).unlock()
960
if self.control_files._lock_count == 0:
961
self._inventory_entry_cache.clear()
963
def add_inventory(self, revision_id, inv, parents):
964
"""Add the inventory inv to the repository as revision_id.
966
:param parents: The revision ids of the parents that revision_id
967
is known to have and are in the repository already.
969
:returns: The validator(which is a sha1 digest, though what is sha'd is
970
repository format specific) of the serialized inventory.
972
if not self.is_in_write_group():
973
raise AssertionError("%r not in write group" % (self,))
974
_mod_revision.check_not_reserved_id(revision_id)
975
if not (inv.revision_id is None or inv.revision_id == revision_id):
976
raise AssertionError(
977
"Mismatch between inventory revision"
978
" id and insertion revid (%r, %r)"
979
% (inv.revision_id, revision_id))
981
raise errors.RootMissing()
982
return self._add_inventory_checked(revision_id, inv, parents)
984
def _add_inventory_checked(self, revision_id, inv, parents):
985
"""Add inv to the repository after checking the inputs.
987
This function can be overridden to allow different inventory styles.
989
:seealso: add_inventory, for the contract.
991
inv_lines = self._serializer.write_inventory_to_lines(inv)
992
return self._inventory_add_lines(revision_id, parents,
993
inv_lines, check_content=False)
995
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
996
parents, basis_inv=None, propagate_caches=False):
997
"""Add a new inventory expressed as a delta against another revision.
999
See the inventory developers documentation for the theory behind
1002
:param basis_revision_id: The inventory id the delta was created
1003
against. (This does not have to be a direct parent.)
1004
:param delta: The inventory delta (see Inventory.apply_delta for
1006
:param new_revision_id: The revision id that the inventory is being
1008
:param parents: The revision ids of the parents that revision_id is
1009
known to have and are in the repository already. These are supplied
1010
for repositories that depend on the inventory graph for revision
1011
graph access, as well as for those that pun ancestry with delta
1013
:param basis_inv: The basis inventory if it is already known,
1015
:param propagate_caches: If True, the caches for this inventory are
1016
copied to and updated for the result if possible.
1018
:returns: (validator, new_inv)
1019
The validator(which is a sha1 digest, though what is sha'd is
1020
repository format specific) of the serialized inventory, and the
1021
resulting inventory.
1023
if not self.is_in_write_group():
1024
raise AssertionError("%r not in write group" % (self,))
1025
_mod_revision.check_not_reserved_id(new_revision_id)
1026
basis_tree = self.revision_tree(basis_revision_id)
1027
basis_tree.lock_read()
1029
# Note that this mutates the inventory of basis_tree, which not all
1030
# inventory implementations may support: A better idiom would be to
1031
# return a new inventory, but as there is no revision tree cache in
1032
# repository this is safe for now - RBC 20081013
1033
if basis_inv is None:
1034
basis_inv = basis_tree.root_inventory
1035
basis_inv.apply_delta(delta)
1036
basis_inv.revision_id = new_revision_id
1037
return (self.add_inventory(new_revision_id, basis_inv, parents),
1042
def _inventory_add_lines(self, revision_id, parents, lines,
1043
check_content=True):
1044
"""Store lines in inv_vf and return the sha1 of the inventory."""
1045
parents = [(parent,) for parent in parents]
1046
result = self.inventories.add_lines((revision_id,), parents, lines,
1047
check_content=check_content)[0]
1048
self.inventories._access.flush()
1051
def add_revision(self, revision_id, rev, inv=None):
1052
"""Add rev to the revision store as revision_id.
1054
:param revision_id: the revision id to use.
1055
:param rev: The revision object.
1056
:param inv: The inventory for the revision. if None, it will be looked
1057
up in the inventory storer
1059
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1061
_mod_revision.check_not_reserved_id(revision_id)
1062
# check inventory present
1063
if not self.inventories.get_parent_map([(revision_id,)]):
1065
raise errors.WeaveRevisionNotPresent(revision_id,
1068
# yes, this is not suitable for adding with ghosts.
1069
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1072
key = (revision_id,)
1073
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1074
self._add_revision(rev)
1076
def _add_revision(self, revision):
1077
text = self._serializer.write_revision_to_string(revision)
1078
key = (revision.revision_id,)
1079
parents = tuple((parent,) for parent in revision.parent_ids)
1080
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1082
def _check_inventories(self, checker):
1083
"""Check the inventories found from the revision scan.
1085
This is responsible for verifying the sha1 of inventories and
1086
creating a pending_keys set that covers data referenced by inventories.
1088
bar = ui.ui_factory.nested_progress_bar()
1090
self._do_check_inventories(checker, bar)
1094
def _do_check_inventories(self, checker, bar):
1095
"""Helper for _check_inventories."""
1097
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1098
kinds = ['chk_bytes', 'texts']
1099
count = len(checker.pending_keys)
1100
bar.update(gettext("inventories"), 0, 2)
1101
current_keys = checker.pending_keys
1102
checker.pending_keys = {}
1103
# Accumulate current checks.
1104
for key in current_keys:
1105
if key[0] != 'inventories' and key[0] not in kinds:
1106
checker._report_items.append('unknown key type %r' % (key,))
1107
keys[key[0]].add(key[1:])
1108
if keys['inventories']:
1109
# NB: output order *should* be roughly sorted - topo or
1110
# inverse topo depending on repository - either way decent
1111
# to just delta against. However, pre-CHK formats didn't
1112
# try to optimise inventory layout on disk. As such the
1113
# pre-CHK code path does not use inventory deltas.
1115
for record in self.inventories.check(keys=keys['inventories']):
1116
if record.storage_kind == 'absent':
1117
checker._report_items.append(
1118
'Missing inventory {%s}' % (record.key,))
1120
last_object = self._check_record('inventories', record,
1121
checker, last_object,
1122
current_keys[('inventories',) + record.key])
1123
del keys['inventories']
1126
bar.update(gettext("texts"), 1)
1127
while (checker.pending_keys or keys['chk_bytes']
1129
# Something to check.
1130
current_keys = checker.pending_keys
1131
checker.pending_keys = {}
1132
# Accumulate current checks.
1133
for key in current_keys:
1134
if key[0] not in kinds:
1135
checker._report_items.append('unknown key type %r' % (key,))
1136
keys[key[0]].add(key[1:])
1137
# Check the outermost kind only - inventories || chk_bytes || texts
1141
for record in getattr(self, kind).check(keys=keys[kind]):
1142
if record.storage_kind == 'absent':
1143
checker._report_items.append(
1144
'Missing %s {%s}' % (kind, record.key,))
1146
last_object = self._check_record(kind, record,
1147
checker, last_object, current_keys[(kind,) + record.key])
1151
def _check_record(self, kind, record, checker, last_object, item_data):
1152
"""Check a single text from this repository."""
1153
if kind == 'inventories':
1154
rev_id = record.key[0]
1155
inv = self._deserialise_inventory(rev_id,
1156
record.get_bytes_as('fulltext'))
1157
if last_object is not None:
1158
delta = inv._make_delta(last_object)
1159
for old_path, path, file_id, ie in delta:
1162
ie.check(checker, rev_id, inv)
1164
for path, ie in inv.iter_entries():
1165
ie.check(checker, rev_id, inv)
1166
if self._format.fast_deltas:
1168
elif kind == 'chk_bytes':
1169
# No code written to check chk_bytes for this repo format.
1170
checker._report_items.append(
1171
'unsupported key type chk_bytes for %s' % (record.key,))
1172
elif kind == 'texts':
1173
self._check_text(record, checker, item_data)
1175
checker._report_items.append(
1176
'unknown key type %s for %s' % (kind, record.key))
1178
def _check_text(self, record, checker, item_data):
1179
"""Check a single text."""
1180
# Check it is extractable.
1181
# TODO: check length.
1182
if record.storage_kind == 'chunked':
1183
chunks = record.get_bytes_as(record.storage_kind)
1184
sha1 = osutils.sha_strings(chunks)
1185
length = sum(map(len, chunks))
1187
content = record.get_bytes_as('fulltext')
1188
sha1 = osutils.sha_string(content)
1189
length = len(content)
1190
if item_data and sha1 != item_data[1]:
1191
checker._report_items.append(
1192
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1193
(record.key, sha1, item_data[1], item_data[2]))
1196
def _eliminate_revisions_not_present(self, revision_ids):
1197
"""Check every revision id in revision_ids to see if we have it.
1199
Returns a set of the present revisions.
1202
graph = self.get_graph()
1203
parent_map = graph.get_parent_map(revision_ids)
1204
# The old API returned a list, should this actually be a set?
1205
return list(parent_map)
1207
def __init__(self, _format, a_controldir, control_files):
1208
"""Instantiate a VersionedFileRepository.
1210
:param _format: The format of the repository on disk.
1211
:param controldir: The ControlDir of the repository.
1212
:param control_files: Control files to use for locking, etc.
1214
# In the future we will have a single api for all stores for
1215
# getting file texts, inventories and revisions, then
1216
# this construct will accept instances of those things.
1217
super(VersionedFileRepository, self).__init__(_format, a_controldir,
1219
self._transport = control_files._transport
1220
self.base = self._transport.base
1222
self._reconcile_does_inventory_gc = True
1223
self._reconcile_fixes_text_parents = False
1224
self._reconcile_backsup_inventory = True
1225
# An InventoryEntry cache, used during deserialization
1226
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1227
# Is it safe to return inventory entries directly from the entry cache,
1228
# rather copying them?
1229
self._safe_to_return_from_cache = False
1231
def fetch(self, source, revision_id=None, find_ghosts=False,
1233
"""Fetch the content required to construct revision_id from source.
1235
If revision_id is None and fetch_spec is None, then all content is
1238
fetch() may not be used when the repository is in a write group -
1239
either finish the current write group before using fetch, or use
1240
fetch before starting the write group.
1242
:param find_ghosts: Find and copy revisions in the source that are
1243
ghosts in the target (and not reachable directly by walking out to
1244
the first-present revision in target from revision_id).
1245
:param revision_id: If specified, all the content needed for this
1246
revision ID will be copied to the target. Fetch will determine for
1247
itself which content needs to be copied.
1248
:param fetch_spec: If specified, a SearchResult or
1249
PendingAncestryResult that describes which revisions to copy. This
1250
allows copying multiple heads at once. Mutually exclusive with
1253
if fetch_spec is not None and revision_id is not None:
1254
raise AssertionError(
1255
"fetch_spec and revision_id are mutually exclusive.")
1256
if self.is_in_write_group():
1257
raise errors.InternalBzrError(
1258
"May not fetch while in a write group.")
1259
# fast path same-url fetch operations
1260
# TODO: lift out to somewhere common with RemoteRepository
1261
# <https://bugs.launchpad.net/bzr/+bug/401646>
1262
if (self.has_same_location(source)
1263
and fetch_spec is None
1264
and self._has_same_fallbacks(source)):
1265
# check that last_revision is in 'from' and then return a
1267
if (revision_id is not None and
1268
not _mod_revision.is_null(revision_id)):
1269
self.get_revision(revision_id)
1271
inter = InterRepository.get(source, self)
1272
if (fetch_spec is not None and
1273
not getattr(inter, "supports_fetch_spec", False)):
1274
raise errors.UnsupportedOperation(
1275
"fetch_spec not supported for %r" % inter)
1276
return inter.fetch(revision_id=revision_id,
1277
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1280
def gather_stats(self, revid=None, committers=None):
1281
"""See Repository.gather_stats()."""
1282
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1283
# now gather global repository information
1284
# XXX: This is available for many repos regardless of listability.
1285
if self.user_transport.listable():
1286
# XXX: do we want to __define len__() ?
1287
# Maybe the versionedfiles object should provide a different
1288
# method to get the number of keys.
1289
result['revisions'] = len(self.revisions.keys())
1290
# result['size'] = t
1293
def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
1294
timezone=None, committer=None, revprops=None,
1295
revision_id=None, lossy=False):
1296
"""Obtain a CommitBuilder for this repository.
1298
:param branch: Branch to commit to.
1299
:param parents: Revision ids of the parents of the new revision.
1300
:param config_stack: Configuration stack to use.
1301
:param timestamp: Optional timestamp recorded for commit.
1302
:param timezone: Optional timezone for timestamp.
1303
:param committer: Optional committer to set for commit.
1304
:param revprops: Optional dictionary of revision properties.
1305
:param revision_id: Optional revision id.
1306
:param lossy: Whether to discard data that can not be natively
1307
represented, when pushing to a foreign VCS
1309
if self._fallback_repositories and not self._format.supports_chks:
1310
raise errors.BzrError("Cannot commit directly to a stacked branch"
1311
" in pre-2a formats. See "
1312
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1313
result = self._commit_builder_class(self, parents, config_stack,
1314
timestamp, timezone, committer, revprops, revision_id,
1316
self.start_write_group()
1319
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1320
"""Return the keys of missing inventory parents for revisions added in
1323
A revision is not complete if the inventory delta for that revision
1324
cannot be calculated. Therefore if the parent inventories of a
1325
revision are not present, the revision is incomplete, and e.g. cannot
1326
be streamed by a smart server. This method finds missing inventory
1327
parents for revisions added in this write group.
1329
if not self._format.supports_external_lookups:
1330
# This is only an issue for stacked repositories
1332
if not self.is_in_write_group():
1333
raise AssertionError('not in a write group')
1335
# XXX: We assume that every added revision already has its
1336
# corresponding inventory, so we only check for parent inventories that
1337
# might be missing, rather than all inventories.
1338
parents = set(self.revisions._index.get_missing_parents())
1339
parents.discard(_mod_revision.NULL_REVISION)
1340
unstacked_inventories = self.inventories._index
1341
present_inventories = unstacked_inventories.get_parent_map(
1342
key[-1:] for key in parents)
1343
parents.difference_update(present_inventories)
1344
if len(parents) == 0:
1345
# No missing parent inventories.
1347
if not check_for_missing_texts:
1348
return set(('inventories', rev_id) for (rev_id,) in parents)
1349
# Ok, now we have a list of missing inventories. But these only matter
1350
# if the inventories that reference them are missing some texts they
1351
# appear to introduce.
1352
# XXX: Texts referenced by all added inventories need to be present,
1353
# but at the moment we're only checking for texts referenced by
1354
# inventories at the graph's edge.
1355
key_deps = self.revisions._index._key_dependencies
1356
key_deps.satisfy_refs_for_keys(present_inventories)
1357
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1358
file_ids = self.fileids_altered_by_revision_ids(referrers)
1359
missing_texts = set()
1360
for file_id, version_ids in viewitems(file_ids):
1361
missing_texts.update(
1362
(file_id, version_id) for version_id in version_ids)
1363
present_texts = self.texts.get_parent_map(missing_texts)
1364
missing_texts.difference_update(present_texts)
1365
if not missing_texts:
1366
# No texts are missing, so all revisions and their deltas are
1369
# Alternatively the text versions could be returned as the missing
1370
# keys, but this is likely to be less data.
1371
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1375
def has_revisions(self, revision_ids):
1376
"""Probe to find out the presence of multiple revisions.
1378
:param revision_ids: An iterable of revision_ids.
1379
:return: A set of the revision_ids that were present.
1381
parent_map = self.revisions.get_parent_map(
1382
[(rev_id,) for rev_id in revision_ids])
1384
if _mod_revision.NULL_REVISION in revision_ids:
1385
result.add(_mod_revision.NULL_REVISION)
1386
result.update([key[0] for key in parent_map])
1390
def get_revision_reconcile(self, revision_id):
1391
"""'reconcile' helper routine that allows access to a revision always.
1393
This variant of get_revision does not cross check the weave graph
1394
against the revision one as get_revision does: but it should only
1395
be used by reconcile, or reconcile-alike commands that are correcting
1396
or testing the revision graph.
1398
return self._get_revisions([revision_id])[0]
1401
def get_revisions(self, revision_ids):
1402
"""Get many revisions at once.
1404
Repositories that need to check data on every revision read should
1405
subclass this method.
1407
return self._get_revisions(revision_ids)
1410
def _get_revisions(self, revision_ids):
1411
"""Core work logic to get many revisions without sanity checks."""
1413
for revid, rev in self._iter_revisions(revision_ids):
1415
raise errors.NoSuchRevision(self, revid)
1417
return [revs[revid] for revid in revision_ids]
1419
def _iter_revisions(self, revision_ids):
1420
"""Iterate over revision objects.
1422
:param revision_ids: An iterable of revisions to examine. None may be
1423
passed to request all revisions known to the repository. Note that
1424
not all repositories can find unreferenced revisions; for those
1425
repositories only referenced ones will be returned.
1426
:return: An iterator of (revid, revision) tuples. Absent revisions (
1427
those asked for but not available) are returned as (revid, None).
1429
if revision_ids is None:
1430
revision_ids = self.all_revision_ids()
1432
for rev_id in revision_ids:
1433
if not rev_id or not isinstance(rev_id, basestring):
1434
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1435
keys = [(key,) for key in revision_ids]
1436
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1437
for record in stream:
1438
revid = record.key[0]
1439
if record.storage_kind == 'absent':
1442
text = record.get_bytes_as('fulltext')
1443
rev = self._serializer.read_revision_from_string(text)
1447
def add_signature_text(self, revision_id, signature):
1448
"""Store a signature text for a revision.
1450
:param revision_id: Revision id of the revision
1451
:param signature: Signature text.
1453
self.signatures.add_lines((revision_id,), (),
1454
osutils.split_lines(signature))
1456
def find_text_key_references(self):
1457
"""Find the text key references within the repository.
1459
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1460
to whether they were referred to by the inventory of the
1461
revision_id that they contain. The inventory texts from all present
1462
revision ids are assessed to generate this report.
1464
revision_keys = self.revisions.keys()
1465
w = self.inventories
1466
pb = ui.ui_factory.nested_progress_bar()
1468
return self._serializer._find_text_key_references(
1469
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1473
def _inventory_xml_lines_for_keys(self, keys):
1474
"""Get a line iterator of the sort needed for findind references.
1476
Not relevant for non-xml inventory repositories.
1478
Ghosts in revision_keys are ignored.
1480
:param revision_keys: The revision keys for the inventories to inspect.
1481
:return: An iterator over (inventory line, revid) for the fulltexts of
1482
all of the xml inventories specified by revision_keys.
1484
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1485
for record in stream:
1486
if record.storage_kind != 'absent':
1487
chunks = record.get_bytes_as('chunked')
1488
revid = record.key[-1]
1489
lines = osutils.chunks_to_lines(chunks)
1493
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1495
"""Helper routine for fileids_altered_by_revision_ids.
1497
This performs the translation of xml lines to revision ids.
1499
:param line_iterator: An iterator of lines, origin_version_id
1500
:param revision_keys: The revision ids to filter for. This should be a
1501
set or other type which supports efficient __contains__ lookups, as
1502
the revision key from each parsed line will be looked up in the
1503
revision_keys filter.
1504
:return: a dictionary mapping altered file-ids to an iterable of
1505
revision_ids. Each altered file-ids has the exact revision_ids that
1506
altered it listed explicitly.
1508
seen = set(self._serializer._find_text_key_references(line_iterator))
1509
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1510
parent_seen = set(self._serializer._find_text_key_references(
1511
self._inventory_xml_lines_for_keys(parent_keys)))
1512
new_keys = seen - parent_seen
1514
setdefault = result.setdefault
1515
for key in new_keys:
1516
setdefault(key[0], set()).add(key[-1])
1519
def _find_parent_keys_of_revisions(self, revision_keys):
1520
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1522
:param revision_keys: An iterable of revision_keys.
1523
:return: The parents of all revision_keys that are not already in
1526
parent_map = self.revisions.get_parent_map(revision_keys)
1527
parent_keys = set(itertools.chain.from_iterable(
1528
viewvalues(parent_map)))
1529
parent_keys.difference_update(revision_keys)
1530
parent_keys.discard(_mod_revision.NULL_REVISION)
1533
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1534
"""Find the file ids and versions affected by revisions.
1536
:param revisions: an iterable containing revision ids.
1537
:param _inv_weave: The inventory weave from this repository or None.
1538
If None, the inventory weave will be opened automatically.
1539
:return: a dictionary mapping altered file-ids to an iterable of
1540
revision_ids. Each altered file-ids has the exact revision_ids that
1541
altered it listed explicitly.
1543
selected_keys = set((revid,) for revid in revision_ids)
1544
w = _inv_weave or self.inventories
1545
return self._find_file_ids_from_xml_inventory_lines(
1546
w.iter_lines_added_or_present_in_keys(
1547
selected_keys, pb=None),
1550
def iter_files_bytes(self, desired_files):
1551
"""Iterate through file versions.
1553
Files will not necessarily be returned in the order they occur in
1554
desired_files. No specific order is guaranteed.
1556
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1557
value supplied by the caller as part of desired_files. It should
1558
uniquely identify the file version in the caller's context. (Examples:
1559
an index number or a TreeTransform trans_id.)
1561
bytes_iterator is an iterable of bytestrings for the file. The
1562
kind of iterable and length of the bytestrings are unspecified, but for
1563
this implementation, it is a list of bytes produced by
1564
VersionedFile.get_record_stream().
1566
:param desired_files: a list of (file_id, revision_id, identifier)
1570
for file_id, revision_id, callable_data in desired_files:
1571
text_keys[(file_id, revision_id)] = callable_data
1572
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1573
if record.storage_kind == 'absent':
1574
raise errors.RevisionNotPresent(record.key[1], record.key[0])
1575
yield text_keys[record.key], record.get_bytes_as('chunked')
1577
def _generate_text_key_index(self, text_key_references=None,
1579
"""Generate a new text key index for the repository.
1581
This is an expensive function that will take considerable time to run.
1583
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1584
list of parents, also text keys. When a given key has no parents,
1585
the parents list will be [NULL_REVISION].
1587
# All revisions, to find inventory parents.
1588
if ancestors is None:
1589
graph = self.get_graph()
1590
ancestors = graph.get_parent_map(self.all_revision_ids())
1591
if text_key_references is None:
1592
text_key_references = self.find_text_key_references()
1593
pb = ui.ui_factory.nested_progress_bar()
1595
return self._do_generate_text_key_index(ancestors,
1596
text_key_references, pb)
1600
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1601
"""Helper for _generate_text_key_index to avoid deep nesting."""
1602
revision_order = tsort.topo_sort(ancestors)
1603
invalid_keys = set()
1605
for revision_id in revision_order:
1606
revision_keys[revision_id] = set()
1607
text_count = len(text_key_references)
1608
# a cache of the text keys to allow reuse; costs a dict of all the
1609
# keys, but saves a 2-tuple for every child of a given key.
1611
for text_key, valid in viewitems(text_key_references):
1613
invalid_keys.add(text_key)
1615
revision_keys[text_key[1]].add(text_key)
1616
text_key_cache[text_key] = text_key
1617
del text_key_references
1619
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1620
NULL_REVISION = _mod_revision.NULL_REVISION
1621
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1622
# too small for large or very branchy trees. However, for 55K path
1623
# trees, it would be easy to use too much memory trivially. Ideally we
1624
# could gauge this by looking at available real memory etc, but this is
1625
# always a tricky proposition.
1626
inventory_cache = lru_cache.LRUCache(10)
1627
batch_size = 10 # should be ~150MB on a 55K path tree
1628
batch_count = len(revision_order) / batch_size + 1
1630
pb.update(gettext("Calculating text parents"), processed_texts, text_count)
1631
for offset in range(batch_count):
1632
to_query = revision_order[offset * batch_size:(offset + 1) *
1636
for revision_id in to_query:
1637
parent_ids = ancestors[revision_id]
1638
for text_key in revision_keys[revision_id]:
1639
pb.update(gettext("Calculating text parents"), processed_texts)
1640
processed_texts += 1
1641
candidate_parents = []
1642
for parent_id in parent_ids:
1643
parent_text_key = (text_key[0], parent_id)
1645
check_parent = parent_text_key not in \
1646
revision_keys[parent_id]
1648
# the parent parent_id is a ghost:
1649
check_parent = False
1650
# truncate the derived graph against this ghost.
1651
parent_text_key = None
1653
# look at the parent commit details inventories to
1654
# determine possible candidates in the per file graph.
1657
inv = inventory_cache[parent_id]
1659
inv = self.revision_tree(parent_id).root_inventory
1660
inventory_cache[parent_id] = inv
1662
parent_entry = inv[text_key[0]]
1663
except (KeyError, errors.NoSuchId):
1665
if parent_entry is not None:
1667
text_key[0], parent_entry.revision)
1669
parent_text_key = None
1670
if parent_text_key is not None:
1671
candidate_parents.append(
1672
text_key_cache[parent_text_key])
1673
parent_heads = text_graph.heads(candidate_parents)
1674
new_parents = list(parent_heads)
1675
new_parents.sort(key=lambda x:candidate_parents.index(x))
1676
if new_parents == []:
1677
new_parents = [NULL_REVISION]
1678
text_index[text_key] = new_parents
1680
for text_key in invalid_keys:
1681
text_index[text_key] = [NULL_REVISION]
1684
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1685
"""Get an iterable listing the keys of all the data introduced by a set
1688
The keys will be ordered so that the corresponding items can be safely
1689
fetched and inserted in that order.
1691
:returns: An iterable producing tuples of (knit-kind, file-id,
1692
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1693
'revisions'. file-id is None unless knit-kind is 'file'.
1695
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1698
for result in self._find_non_file_keys_to_fetch(revision_ids):
1701
def _find_file_keys_to_fetch(self, revision_ids, pb):
1702
# XXX: it's a bit weird to control the inventory weave caching in this
1703
# generator. Ideally the caching would be done in fetch.py I think. Or
1704
# maybe this generator should explicitly have the contract that it
1705
# should not be iterated until the previously yielded item has been
1707
inv_w = self.inventories
1709
# file ids that changed
1710
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1712
num_file_ids = len(file_ids)
1713
for file_id, altered_versions in viewitems(file_ids):
1715
pb.update(gettext("Fetch texts"), count, num_file_ids)
1717
yield ("file", file_id, altered_versions)
1719
def _find_non_file_keys_to_fetch(self, revision_ids):
1721
yield ("inventory", None, revision_ids)
1724
# XXX: Note ATM no callers actually pay attention to this return
1725
# instead they just use the list of revision ids and ignore
1726
# missing sigs. Consider removing this work entirely
1727
revisions_with_signatures = set(self.signatures.get_parent_map(
1728
[(r,) for r in revision_ids]))
1729
revisions_with_signatures = {r for (r,) in revisions_with_signatures}
1730
revisions_with_signatures.intersection_update(revision_ids)
1731
yield ("signatures", None, revisions_with_signatures)
1734
yield ("revisions", None, revision_ids)
1737
def get_inventory(self, revision_id):
1738
"""Get Inventory object by revision id."""
1739
return next(self.iter_inventories([revision_id]))
1741
def iter_inventories(self, revision_ids, ordering=None):
1742
"""Get many inventories by revision_ids.
1744
This will buffer some or all of the texts used in constructing the
1745
inventories in memory, but will only parse a single inventory at a
1748
:param revision_ids: The expected revision ids of the inventories.
1749
:param ordering: optional ordering, e.g. 'topological'. If not
1750
specified, the order of revision_ids will be preserved (by
1751
buffering if necessary).
1752
:return: An iterator of inventories.
1754
if ((None in revision_ids)
1755
or (_mod_revision.NULL_REVISION in revision_ids)):
1756
raise ValueError('cannot get null revision inventory')
1757
for inv, revid in self._iter_inventories(revision_ids, ordering):
1759
raise errors.NoSuchRevision(self, revid)
1762
def _iter_inventories(self, revision_ids, ordering):
1763
"""single-document based inventory iteration."""
1764
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1765
for text, revision_id in inv_xmls:
1767
yield None, revision_id
1769
yield self._deserialise_inventory(revision_id, text), revision_id
1771
def _iter_inventory_xmls(self, revision_ids, ordering):
1772
if ordering is None:
1773
order_as_requested = True
1774
ordering = 'unordered'
1776
order_as_requested = False
1777
keys = [(revision_id,) for revision_id in revision_ids]
1780
if order_as_requested:
1781
key_iter = iter(keys)
1782
next_key = next(key_iter)
1783
stream = self.inventories.get_record_stream(keys, ordering, True)
1785
for record in stream:
1786
if record.storage_kind != 'absent':
1787
chunks = record.get_bytes_as('chunked')
1788
if order_as_requested:
1789
text_chunks[record.key] = chunks
1791
yield ''.join(chunks), record.key[-1]
1793
yield None, record.key[-1]
1794
if order_as_requested:
1795
# Yield as many results as we can while preserving order.
1796
while next_key in text_chunks:
1797
chunks = text_chunks.pop(next_key)
1798
yield ''.join(chunks), next_key[-1]
1800
next_key = next(key_iter)
1801
except StopIteration:
1802
# We still want to fully consume the get_record_stream,
1803
# just in case it is not actually finished at this point
1807
def _deserialise_inventory(self, revision_id, xml):
1808
"""Transform the xml into an inventory object.
1810
:param revision_id: The expected revision id of the inventory.
1811
:param xml: A serialised inventory.
1813
result = self._serializer.read_inventory_from_string(xml, revision_id,
1814
entry_cache=self._inventory_entry_cache,
1815
return_from_cache=self._safe_to_return_from_cache)
1816
if result.revision_id != revision_id:
1817
raise AssertionError('revision id mismatch %s != %s' % (
1818
result.revision_id, revision_id))
1821
def get_serializer_format(self):
1822
return self._serializer.format_num
1825
def _get_inventory_xml(self, revision_id):
1826
"""Get serialized inventory as a string."""
1827
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1828
text, revision_id = next(texts)
1830
raise errors.NoSuchRevision(self, revision_id)
1834
def revision_tree(self, revision_id):
1835
"""Return Tree for a revision on this branch.
1837
`revision_id` may be NULL_REVISION for the empty tree revision.
1839
revision_id = _mod_revision.ensure_null(revision_id)
1840
# TODO: refactor this to use an existing revision object
1841
# so we don't need to read it in twice.
1842
if revision_id == _mod_revision.NULL_REVISION:
1843
return InventoryRevisionTree(self,
1844
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1846
inv = self.get_inventory(revision_id)
1847
return InventoryRevisionTree(self, inv, revision_id)
1849
def revision_trees(self, revision_ids):
1850
"""Return Trees for revisions in this repository.
1852
:param revision_ids: a sequence of revision-ids;
1853
a revision-id may not be None or 'null:'
1855
inventories = self.iter_inventories(revision_ids)
1856
for inv in inventories:
1857
yield InventoryRevisionTree(self, inv, inv.revision_id)
1859
def _filtered_revision_trees(self, revision_ids, file_ids):
1860
"""Return Tree for a revision on this branch with only some files.
1862
:param revision_ids: a sequence of revision-ids;
1863
a revision-id may not be None or 'null:'
1864
:param file_ids: if not None, the result is filtered
1865
so that only those file-ids, their parents and their
1866
children are included.
1868
inventories = self.iter_inventories(revision_ids)
1869
for inv in inventories:
1870
# Should we introduce a FilteredRevisionTree class rather
1871
# than pre-filter the inventory here?
1872
filtered_inv = inv.filter(file_ids)
1873
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1875
def get_parent_map(self, revision_ids):
1876
"""See graph.StackedParentsProvider.get_parent_map"""
1877
# revisions index works in keys; this just works in revisions
1878
# therefore wrap and unwrap
1881
for revision_id in revision_ids:
1882
if revision_id == _mod_revision.NULL_REVISION:
1883
result[revision_id] = ()
1884
elif revision_id is None:
1885
raise ValueError('get_parent_map(None) is not valid')
1887
query_keys.append((revision_id ,))
1888
for (revision_id,), parent_keys in viewitems(
1889
self.revisions.get_parent_map(query_keys)):
1891
result[revision_id] = tuple([parent_revid
1892
for (parent_revid,) in parent_keys])
1894
result[revision_id] = (_mod_revision.NULL_REVISION,)
1898
def get_known_graph_ancestry(self, revision_ids):
1899
"""Return the known graph for a set of revision ids and their ancestors.
1901
st = static_tuple.StaticTuple
1902
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1903
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1904
return graph.GraphThunkIdsToKeys(known_graph)
1907
def get_file_graph(self):
1908
"""Return the graph walker for text revisions."""
1909
return graph.Graph(self.texts)
1911
def revision_ids_to_search_result(self, result_set):
1912
"""Convert a set of revision ids to a graph SearchResult."""
1913
result_parents = set(itertools.chain.from_iterable(viewvalues(
1914
self.get_graph().get_parent_map(result_set))))
1915
included_keys = result_set.intersection(result_parents)
1916
start_keys = result_set.difference(included_keys)
1917
exclude_keys = result_parents.difference(result_set)
1918
result = vf_search.SearchResult(start_keys, exclude_keys,
1919
len(result_set), result_set)
1922
def _get_versioned_file_checker(self, text_key_references=None,
1924
"""Return an object suitable for checking versioned files.
1926
:param text_key_references: if non-None, an already built
1927
dictionary mapping text keys ((fileid, revision_id) tuples)
1928
to whether they were referred to by the inventory of the
1929
revision_id that they contain. If None, this will be
1931
:param ancestors: Optional result from
1932
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1935
return _VersionedFileChecker(self,
1936
text_key_references=text_key_references, ancestors=ancestors)
1939
def has_signature_for_revision_id(self, revision_id):
1940
"""Query for a revision signature for revision_id in the repository."""
1941
if not self.has_revision(revision_id):
1942
raise errors.NoSuchRevision(self, revision_id)
1943
sig_present = (1 == len(
1944
self.signatures.get_parent_map([(revision_id,)])))
1948
def get_signature_text(self, revision_id):
1949
"""Return the text for a signature."""
1950
stream = self.signatures.get_record_stream([(revision_id,)],
1952
record = next(stream)
1953
if record.storage_kind == 'absent':
1954
raise errors.NoSuchRevision(self, revision_id)
1955
return record.get_bytes_as('fulltext')
1958
def _check(self, revision_ids, callback_refs, check_repo):
1959
result = check.VersionedFileCheck(self, check_repo=check_repo)
1960
result.check(callback_refs)
1963
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1964
"""Find revisions with different parent lists in the revision object
1965
and in the index graph.
1967
:param revisions_iterator: None, or an iterator of (revid,
1968
Revision-or-None). This iterator controls the revisions checked.
1969
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1970
parents-in-revision).
1972
if not self.is_locked():
1973
raise AssertionError()
1975
if revisions_iterator is None:
1976
revisions_iterator = self._iter_revisions(None)
1977
for revid, revision in revisions_iterator:
1978
if revision is None:
1980
parent_map = vf.get_parent_map([(revid,)])
1981
parents_according_to_index = tuple(parent[-1] for parent in
1982
parent_map[(revid,)])
1983
parents_according_to_revision = tuple(revision.parent_ids)
1984
if parents_according_to_index != parents_according_to_revision:
1985
yield (revid, parents_according_to_index,
1986
parents_according_to_revision)
1988
def _check_for_inconsistent_revision_parents(self):
1989
inconsistencies = list(self._find_inconsistent_revision_parents())
1991
raise errors.BzrCheckError(
1992
"Revision knit has inconsistent parents.")
1994
def _get_sink(self):
1995
"""Return a sink for streaming into this repository."""
1996
return StreamSink(self)
1998
def _get_source(self, to_format):
1999
"""Return a source for streaming from this repository."""
2000
return StreamSource(self, to_format)
2003
class MetaDirVersionedFileRepository(MetaDirRepository,
2004
VersionedFileRepository):
2005
"""Repositories in a meta-dir, that work via versioned file objects."""
2007
def __init__(self, _format, a_controldir, control_files):
2008
super(MetaDirVersionedFileRepository, self).__init__(_format, a_controldir,
2012
class MetaDirVersionedFileRepositoryFormat(RepositoryFormatMetaDir,
2013
VersionedFileRepositoryFormat):
2014
"""Base class for repository formats using versioned files in metadirs."""
2017
class StreamSink(object):
2018
"""An object that can insert a stream into a repository.
2020
This interface handles the complexity of reserialising inventories and
2021
revisions from different formats, and allows unidirectional insertion into
2022
stacked repositories without looking for the missing basis parents
2026
def __init__(self, target_repo):
2027
self.target_repo = target_repo
2029
def insert_stream(self, stream, src_format, resume_tokens):
2030
"""Insert a stream's content into the target repository.
2032
:param src_format: a bzr repository format.
2034
:return: a list of resume tokens and an iterable of keys additional
2035
items required before the insertion can be completed.
2037
self.target_repo.lock_write()
2040
self.target_repo.resume_write_group(resume_tokens)
2043
self.target_repo.start_write_group()
2046
# locked_insert_stream performs a commit|suspend.
2047
missing_keys = self.insert_stream_without_locking(stream,
2048
src_format, is_resume)
2050
# suspend the write group and tell the caller what we is
2051
# missing. We know we can suspend or else we would not have
2052
# entered this code path. (All repositories that can handle
2053
# missing keys can handle suspending a write group).
2054
write_group_tokens = self.target_repo.suspend_write_group()
2055
return write_group_tokens, missing_keys
2056
hint = self.target_repo.commit_write_group()
2057
to_serializer = self.target_repo._format._serializer
2058
src_serializer = src_format._serializer
2059
if (to_serializer != src_serializer and
2060
self.target_repo._format.pack_compresses):
2061
self.target_repo.pack(hint=hint)
2064
self.target_repo.abort_write_group(suppress_errors=True)
2067
self.target_repo.unlock()
2069
def insert_stream_without_locking(self, stream, src_format,
2071
"""Insert a stream's content into the target repository.
2073
This assumes that you already have a locked repository and an active
2076
:param src_format: a bzr repository format.
2077
:param is_resume: Passed down to get_missing_parent_inventories to
2078
indicate if we should be checking for missing texts at the same
2081
:return: A set of keys that are missing.
2083
if not self.target_repo.is_write_locked():
2084
raise errors.ObjectNotLocked(self)
2085
if not self.target_repo.is_in_write_group():
2086
raise errors.BzrError('you must already be in a write group')
2087
to_serializer = self.target_repo._format._serializer
2088
src_serializer = src_format._serializer
2090
if to_serializer == src_serializer:
2091
# If serializers match and the target is a pack repository, set the
2092
# write cache size on the new pack. This avoids poor performance
2093
# on transports where append is unbuffered (such as
2094
# RemoteTransport). This is safe to do because nothing should read
2095
# back from the target repository while a stream with matching
2096
# serialization is being inserted.
2097
# The exception is that a delta record from the source that should
2098
# be a fulltext may need to be expanded by the target (see
2099
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2100
# explicitly flush any buffered writes first in that rare case.
2102
new_pack = self.target_repo._pack_collection._new_pack
2103
except AttributeError:
2104
# Not a pack repository
2107
new_pack.set_write_cache_size(1024*1024)
2108
for substream_type, substream in stream:
2109
if 'stream' in debug.debug_flags:
2110
mutter('inserting substream: %s', substream_type)
2111
if substream_type == 'texts':
2112
self.target_repo.texts.insert_record_stream(substream)
2113
elif substream_type == 'inventories':
2114
if src_serializer == to_serializer:
2115
self.target_repo.inventories.insert_record_stream(
2118
self._extract_and_insert_inventories(
2119
substream, src_serializer)
2120
elif substream_type == 'inventory-deltas':
2121
self._extract_and_insert_inventory_deltas(
2122
substream, src_serializer)
2123
elif substream_type == 'chk_bytes':
2124
# XXX: This doesn't support conversions, as it assumes the
2125
# conversion was done in the fetch code.
2126
self.target_repo.chk_bytes.insert_record_stream(substream)
2127
elif substream_type == 'revisions':
2128
# This may fallback to extract-and-insert more often than
2129
# required if the serializers are different only in terms of
2131
if src_serializer == to_serializer:
2132
self.target_repo.revisions.insert_record_stream(substream)
2134
self._extract_and_insert_revisions(substream,
2136
elif substream_type == 'signatures':
2137
self.target_repo.signatures.insert_record_stream(substream)
2139
raise AssertionError('kaboom! %s' % (substream_type,))
2140
# Done inserting data, and the missing_keys calculations will try to
2141
# read back from the inserted data, so flush the writes to the new pack
2142
# (if this is pack format).
2143
if new_pack is not None:
2144
new_pack._write_data('', flush=True)
2145
# Find all the new revisions (including ones from resume_tokens)
2146
missing_keys = self.target_repo.get_missing_parent_inventories(
2147
check_for_missing_texts=is_resume)
2149
for prefix, versioned_file in (
2150
('texts', self.target_repo.texts),
2151
('inventories', self.target_repo.inventories),
2152
('revisions', self.target_repo.revisions),
2153
('signatures', self.target_repo.signatures),
2154
('chk_bytes', self.target_repo.chk_bytes),
2156
if versioned_file is None:
2158
# TODO: key is often going to be a StaticTuple object
2159
# I don't believe we can define a method by which
2160
# (prefix,) + StaticTuple will work, though we could
2161
# define a StaticTuple.sq_concat that would allow you to
2162
# pass in either a tuple or a StaticTuple as the second
2163
# object, so instead we could have:
2164
# StaticTuple(prefix) + key here...
2165
missing_keys.update((prefix,) + key for key in
2166
versioned_file.get_missing_compression_parent_keys())
2167
except NotImplementedError:
2168
# cannot even attempt suspending, and missing would have failed
2169
# during stream insertion.
2170
missing_keys = set()
2173
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2174
target_rich_root = self.target_repo._format.rich_root_data
2175
target_tree_refs = self.target_repo._format.supports_tree_reference
2176
for record in substream:
2177
# Insert the delta directly
2178
inventory_delta_bytes = record.get_bytes_as('fulltext')
2179
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2181
parse_result = deserialiser.parse_text_bytes(
2182
inventory_delta_bytes)
2183
except inventory_delta.IncompatibleInventoryDelta as err:
2184
mutter("Incompatible delta: %s", err.msg)
2185
raise errors.IncompatibleRevision(self.target_repo._format)
2186
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2187
revision_id = new_id
2188
parents = [key[0] for key in record.parents]
2189
self.target_repo.add_inventory_by_delta(
2190
basis_id, inv_delta, revision_id, parents)
2192
def _extract_and_insert_inventories(self, substream, serializer,
2194
"""Generate a new inventory versionedfile in target, converting data.
2196
The inventory is retrieved from the source, (deserializing it), and
2197
stored in the target (reserializing it in a different format).
2199
target_rich_root = self.target_repo._format.rich_root_data
2200
target_tree_refs = self.target_repo._format.supports_tree_reference
2201
for record in substream:
2202
# It's not a delta, so it must be a fulltext in the source
2203
# serializer's format.
2204
bytes = record.get_bytes_as('fulltext')
2205
revision_id = record.key[0]
2206
inv = serializer.read_inventory_from_string(bytes, revision_id)
2207
parents = [key[0] for key in record.parents]
2208
self.target_repo.add_inventory(revision_id, inv, parents)
2209
# No need to keep holding this full inv in memory when the rest of
2210
# the substream is likely to be all deltas.
2213
def _extract_and_insert_revisions(self, substream, serializer):
2214
for record in substream:
2215
bytes = record.get_bytes_as('fulltext')
2216
revision_id = record.key[0]
2217
rev = serializer.read_revision_from_string(bytes)
2218
if rev.revision_id != revision_id:
2219
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2220
self.target_repo.add_revision(revision_id, rev)
2223
if self.target_repo._format._fetch_reconcile:
2224
self.target_repo.reconcile()
2227
class StreamSource(object):
2228
"""A source of a stream for fetching between repositories."""
2230
def __init__(self, from_repository, to_format):
2231
"""Create a StreamSource streaming from from_repository."""
2232
self.from_repository = from_repository
2233
self.to_format = to_format
2234
self._record_counter = RecordCounter()
2236
def delta_on_metadata(self):
2237
"""Return True if delta's are permitted on metadata streams.
2239
That is on revisions and signatures.
2241
src_serializer = self.from_repository._format._serializer
2242
target_serializer = self.to_format._serializer
2243
return (self.to_format._fetch_uses_deltas and
2244
src_serializer == target_serializer)
2246
def _fetch_revision_texts(self, revs):
2247
# fetch signatures first and then the revision texts
2248
# may need to be a InterRevisionStore call here.
2249
from_sf = self.from_repository.signatures
2250
# A missing signature is just skipped.
2251
keys = [(rev_id,) for rev_id in revs]
2252
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2254
self.to_format._fetch_order,
2255
not self.to_format._fetch_uses_deltas))
2256
# If a revision has a delta, this is actually expanded inside the
2257
# insert_record_stream code now, which is an alternate fix for
2259
from_rf = self.from_repository.revisions
2260
revisions = from_rf.get_record_stream(
2262
self.to_format._fetch_order,
2263
not self.delta_on_metadata())
2264
return [('signatures', signatures), ('revisions', revisions)]
2266
def _generate_root_texts(self, revs):
2267
"""This will be called by get_stream between fetching weave texts and
2268
fetching the inventory weave.
2270
if self._rich_root_upgrade():
2271
return _mod_fetch.Inter1and2Helper(
2272
self.from_repository).generate_root_texts(revs)
2276
def get_stream(self, search):
2278
revs = search.get_keys()
2279
graph = self.from_repository.get_graph()
2280
revs = tsort.topo_sort(graph.get_parent_map(revs))
2281
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2283
for knit_kind, file_id, revisions in data_to_fetch:
2284
if knit_kind != phase:
2286
# Make a new progress bar for this phase
2287
if knit_kind == "file":
2288
# Accumulate file texts
2289
text_keys.extend([(file_id, revision) for revision in
2291
elif knit_kind == "inventory":
2292
# Now copy the file texts.
2293
from_texts = self.from_repository.texts
2294
yield ('texts', from_texts.get_record_stream(
2295
text_keys, self.to_format._fetch_order,
2296
not self.to_format._fetch_uses_deltas))
2297
# Cause an error if a text occurs after we have done the
2300
# Before we process the inventory we generate the root
2301
# texts (if necessary) so that the inventories references
2303
for _ in self._generate_root_texts(revs):
2305
# we fetch only the referenced inventories because we do not
2306
# know for unselected inventories whether all their required
2307
# texts are present in the other repository - it could be
2309
for info in self._get_inventory_stream(revs):
2311
elif knit_kind == "signatures":
2312
# Nothing to do here; this will be taken care of when
2313
# _fetch_revision_texts happens.
2315
elif knit_kind == "revisions":
2316
for record in self._fetch_revision_texts(revs):
2319
raise AssertionError("Unknown knit kind %r" % knit_kind)
2321
def get_stream_for_missing_keys(self, missing_keys):
2322
# missing keys can only occur when we are byte copying and not
2323
# translating (because translation means we don't send
2324
# unreconstructable deltas ever).
2326
keys['texts'] = set()
2327
keys['revisions'] = set()
2328
keys['inventories'] = set()
2329
keys['chk_bytes'] = set()
2330
keys['signatures'] = set()
2331
for key in missing_keys:
2332
keys[key[0]].add(key[1:])
2333
if len(keys['revisions']):
2334
# If we allowed copying revisions at this point, we could end up
2335
# copying a revision without copying its required texts: a
2336
# violation of the requirements for repository integrity.
2337
raise AssertionError(
2338
'cannot copy revisions to fill in missing deltas %s' % (
2339
keys['revisions'],))
2340
for substream_kind, keys in viewitems(keys):
2341
vf = getattr(self.from_repository, substream_kind)
2342
if vf is None and keys:
2343
raise AssertionError(
2344
"cannot fill in keys for a versioned file we don't"
2345
" have: %s needs %s" % (substream_kind, keys))
2347
# No need to stream something we don't have
2349
if substream_kind == 'inventories':
2350
# Some missing keys are genuinely ghosts, filter those out.
2351
present = self.from_repository.inventories.get_parent_map(keys)
2352
revs = [key[0] for key in present]
2353
# Get the inventory stream more-or-less as we do for the
2354
# original stream; there's no reason to assume that records
2355
# direct from the source will be suitable for the sink. (Think
2356
# e.g. 2a -> 1.9-rich-root).
2357
for info in self._get_inventory_stream(revs, missing=True):
2361
# Ask for full texts always so that we don't need more round trips
2362
# after this stream.
2363
# Some of the missing keys are genuinely ghosts, so filter absent
2364
# records. The Sink is responsible for doing another check to
2365
# ensure that ghosts don't introduce missing data for future
2367
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2368
self.to_format._fetch_order, True))
2369
yield substream_kind, stream
2371
def inventory_fetch_order(self):
2372
if self._rich_root_upgrade():
2373
return 'topological'
2375
return self.to_format._fetch_order
2377
def _rich_root_upgrade(self):
2378
return (not self.from_repository._format.rich_root_data and
2379
self.to_format.rich_root_data)
2381
def _get_inventory_stream(self, revision_ids, missing=False):
2382
from_format = self.from_repository._format
2383
if (from_format.supports_chks and self.to_format.supports_chks and
2384
from_format.network_name() == self.to_format.network_name()):
2385
raise AssertionError(
2386
"this case should be handled by GroupCHKStreamSource")
2387
elif 'forceinvdeltas' in debug.debug_flags:
2388
return self._get_convertable_inventory_stream(revision_ids,
2389
delta_versus_null=missing)
2390
elif from_format.network_name() == self.to_format.network_name():
2392
return self._get_simple_inventory_stream(revision_ids,
2394
elif (not from_format.supports_chks and not self.to_format.supports_chks
2395
and from_format._serializer == self.to_format._serializer):
2396
# Essentially the same format.
2397
return self._get_simple_inventory_stream(revision_ids,
2400
# Any time we switch serializations, we want to use an
2401
# inventory-delta based approach.
2402
return self._get_convertable_inventory_stream(revision_ids,
2403
delta_versus_null=missing)
2405
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2406
# NB: This currently reopens the inventory weave in source;
2407
# using a single stream interface instead would avoid this.
2408
from_weave = self.from_repository.inventories
2410
delta_closure = True
2412
delta_closure = not self.delta_on_metadata()
2413
yield ('inventories', from_weave.get_record_stream(
2414
[(rev_id,) for rev_id in revision_ids],
2415
self.inventory_fetch_order(), delta_closure))
2417
def _get_convertable_inventory_stream(self, revision_ids,
2418
delta_versus_null=False):
2419
# The two formats are sufficiently different that there is no fast
2420
# path, so we need to send just inventorydeltas, which any
2421
# sufficiently modern client can insert into any repository.
2422
# The StreamSink code expects to be able to
2423
# convert on the target, so we need to put bytes-on-the-wire that can
2424
# be converted. That means inventory deltas (if the remote is <1.19,
2425
# RemoteStreamSink will fallback to VFS to insert the deltas).
2426
yield ('inventory-deltas',
2427
self._stream_invs_as_deltas(revision_ids,
2428
delta_versus_null=delta_versus_null))
2430
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2431
"""Return a stream of inventory-deltas for the given rev ids.
2433
:param revision_ids: The list of inventories to transmit
2434
:param delta_versus_null: Don't try to find a minimal delta for this
2435
entry, instead compute the delta versus the NULL_REVISION. This
2436
effectively streams a complete inventory. Used for stuff like
2437
filling in missing parents, etc.
2439
from_repo = self.from_repository
2440
revision_keys = [(rev_id,) for rev_id in revision_ids]
2441
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2442
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2444
inventories = self.from_repository.iter_inventories(
2445
revision_ids, 'topological')
2446
format = from_repo._format
2447
invs_sent_so_far = {_mod_revision.NULL_REVISION}
2448
inventory_cache = lru_cache.LRUCache(50)
2449
null_inventory = from_repo.revision_tree(
2450
_mod_revision.NULL_REVISION).root_inventory
2451
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2452
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2453
# repo back into a non-rich-root repo ought to be allowed)
2454
serializer = inventory_delta.InventoryDeltaSerializer(
2455
versioned_root=format.rich_root_data,
2456
tree_references=format.supports_tree_reference)
2457
for inv in inventories:
2458
key = (inv.revision_id,)
2459
parent_keys = parent_map.get(key, ())
2461
if not delta_versus_null and parent_keys:
2462
# The caller did not ask for complete inventories and we have
2463
# some parents that we can delta against. Make a delta against
2464
# each parent so that we can find the smallest.
2465
parent_ids = [parent_key[0] for parent_key in parent_keys]
2466
for parent_id in parent_ids:
2467
if parent_id not in invs_sent_so_far:
2468
# We don't know that the remote side has this basis, so
2471
if parent_id == _mod_revision.NULL_REVISION:
2472
parent_inv = null_inventory
2474
parent_inv = inventory_cache.get(parent_id, None)
2475
if parent_inv is None:
2476
parent_inv = from_repo.get_inventory(parent_id)
2477
candidate_delta = inv._make_delta(parent_inv)
2478
if (delta is None or
2479
len(delta) > len(candidate_delta)):
2480
delta = candidate_delta
2481
basis_id = parent_id
2483
# Either none of the parents ended up being suitable, or we
2484
# were asked to delta against NULL
2485
basis_id = _mod_revision.NULL_REVISION
2486
delta = inv._make_delta(null_inventory)
2487
invs_sent_so_far.add(inv.revision_id)
2488
inventory_cache[inv.revision_id] = inv
2489
delta_serialized = ''.join(
2490
serializer.delta_to_lines(basis_id, key[-1], delta))
2491
yield versionedfile.FulltextContentFactory(
2492
key, parent_keys, None, delta_serialized)
2495
class _VersionedFileChecker(object):
2497
def __init__(self, repository, text_key_references=None, ancestors=None):
2498
self.repository = repository
2499
self.text_index = self.repository._generate_text_key_index(
2500
text_key_references=text_key_references, ancestors=ancestors)
2502
def calculate_file_version_parents(self, text_key):
2503
"""Calculate the correct parents for a file version according to
2506
parent_keys = self.text_index[text_key]
2507
if parent_keys == [_mod_revision.NULL_REVISION]:
2509
return tuple(parent_keys)
2511
def check_file_version_parents(self, texts, progress_bar=None):
2512
"""Check the parents stored in a versioned file are correct.
2514
It also detects file versions that are not referenced by their
2515
corresponding revision's inventory.
2517
:returns: A tuple of (wrong_parents, dangling_file_versions).
2518
wrong_parents is a dict mapping {revision_id: (stored_parents,
2519
correct_parents)} for each revision_id where the stored parents
2520
are not correct. dangling_file_versions is a set of (file_id,
2521
revision_id) tuples for versions that are present in this versioned
2522
file, but not used by the corresponding inventory.
2524
local_progress = None
2525
if progress_bar is None:
2526
local_progress = ui.ui_factory.nested_progress_bar()
2527
progress_bar = local_progress
2529
return self._check_file_version_parents(texts, progress_bar)
2532
local_progress.finished()
2534
def _check_file_version_parents(self, texts, progress_bar):
2535
"""See check_file_version_parents."""
2537
self.file_ids = {file_id for file_id, _ in self.text_index}
2538
# text keys is now grouped by file_id
2539
n_versions = len(self.text_index)
2540
progress_bar.update(gettext('loading text store'), 0, n_versions)
2541
parent_map = self.repository.texts.get_parent_map(self.text_index)
2542
# On unlistable transports this could well be empty/error...
2543
text_keys = self.repository.texts.keys()
2544
unused_keys = frozenset(text_keys) - set(self.text_index)
2545
for num, key in enumerate(self.text_index):
2546
progress_bar.update(gettext('checking text graph'), num, n_versions)
2547
correct_parents = self.calculate_file_version_parents(key)
2549
knit_parents = parent_map[key]
2550
except errors.RevisionNotPresent:
2553
if correct_parents != knit_parents:
2554
wrong_parents[key] = (knit_parents, correct_parents)
2555
return wrong_parents, unused_keys
2558
class InterVersionedFileRepository(InterRepository):
2560
_walk_to_common_revisions_batch_size = 50
2562
supports_fetch_spec = True
2565
def fetch(self, revision_id=None, find_ghosts=False,
2567
"""Fetch the content required to construct revision_id.
2569
The content is copied from self.source to self.target.
2571
:param revision_id: if None all content is copied, if NULL_REVISION no
2575
if self.target._format.experimental:
2576
ui.ui_factory.show_user_warning('experimental_format_fetch',
2577
from_format=self.source._format,
2578
to_format=self.target._format)
2579
from breezy.fetch import RepoFetcher
2580
# See <https://launchpad.net/bugs/456077> asking for a warning here
2581
if self.source._format.network_name() != self.target._format.network_name():
2582
ui.ui_factory.show_user_warning('cross_format_fetch',
2583
from_format=self.source._format,
2584
to_format=self.target._format)
2585
f = RepoFetcher(to_repository=self.target,
2586
from_repository=self.source,
2587
last_revision=revision_id,
2588
fetch_spec=fetch_spec,
2589
find_ghosts=find_ghosts)
2591
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2592
"""Walk out from revision_ids in source to revisions target has.
2594
:param revision_ids: The start point for the search.
2595
:return: A set of revision ids.
2597
target_graph = self.target.get_graph()
2598
revision_ids = frozenset(revision_ids)
2600
all_wanted_revs = revision_ids.union(if_present_ids)
2602
all_wanted_revs = revision_ids
2603
missing_revs = set()
2604
source_graph = self.source.get_graph()
2605
# ensure we don't pay silly lookup costs.
2606
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2607
null_set = frozenset([_mod_revision.NULL_REVISION])
2608
searcher_exhausted = False
2612
# Iterate the searcher until we have enough next_revs
2613
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2615
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2616
next_revs.update(next_revs_part)
2617
ghosts.update(ghosts_part)
2618
except StopIteration:
2619
searcher_exhausted = True
2621
# If there are ghosts in the source graph, and the caller asked for
2622
# them, make sure that they are present in the target.
2623
# We don't care about other ghosts as we can't fetch them and
2624
# haven't been asked to.
2625
ghosts_to_check = set(revision_ids.intersection(ghosts))
2626
revs_to_get = set(next_revs).union(ghosts_to_check)
2628
have_revs = set(target_graph.get_parent_map(revs_to_get))
2629
# we always have NULL_REVISION present.
2630
have_revs = have_revs.union(null_set)
2631
# Check if the target is missing any ghosts we need.
2632
ghosts_to_check.difference_update(have_revs)
2634
# One of the caller's revision_ids is a ghost in both the
2635
# source and the target.
2636
raise errors.NoSuchRevision(
2637
self.source, ghosts_to_check.pop())
2638
missing_revs.update(next_revs - have_revs)
2639
# Because we may have walked past the original stop point, make
2640
# sure everything is stopped
2641
stop_revs = searcher.find_seen_ancestors(have_revs)
2642
searcher.stop_searching_any(stop_revs)
2643
if searcher_exhausted:
2645
(started_keys, excludes, included_keys) = searcher.get_state()
2646
return vf_search.SearchResult(started_keys, excludes,
2647
len(included_keys), included_keys)
2650
def search_missing_revision_ids(self,
2651
find_ghosts=True, revision_ids=None, if_present_ids=None,
2653
"""Return the revision ids that source has that target does not.
2655
:param revision_ids: return revision ids included by these
2656
revision_ids. NoSuchRevision will be raised if any of these
2657
revisions are not present.
2658
:param if_present_ids: like revision_ids, but will not cause
2659
NoSuchRevision if any of these are absent, instead they will simply
2660
not be in the result. This is useful for e.g. finding revisions
2661
to fetch for tags, which may reference absent revisions.
2662
:param find_ghosts: If True find missing revisions in deep history
2663
rather than just finding the surface difference.
2664
:return: A breezy.graph.SearchResult.
2666
# stop searching at found target revisions.
2667
if not find_ghosts and (revision_ids is not None or if_present_ids is
2669
result = self._walk_to_common_revisions(revision_ids,
2670
if_present_ids=if_present_ids)
2673
result_set = result.get_keys()
2675
# generic, possibly worst case, slow code path.
2676
target_ids = set(self.target.all_revision_ids())
2677
source_ids = self._present_source_revisions_for(
2678
revision_ids, if_present_ids)
2679
result_set = set(source_ids).difference(target_ids)
2680
if limit is not None:
2681
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2682
result_set = set(itertools.islice(topo_ordered, limit))
2683
return self.source.revision_ids_to_search_result(result_set)
2685
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2686
"""Returns set of all revisions in ancestry of revision_ids present in
2689
:param revision_ids: if None, all revisions in source are returned.
2690
:param if_present_ids: like revision_ids, but if any/all of these are
2691
absent no error is raised.
2693
if revision_ids is not None or if_present_ids is not None:
2694
# First, ensure all specified revisions exist. Callers expect
2695
# NoSuchRevision when they pass absent revision_ids here.
2696
if revision_ids is None:
2697
revision_ids = set()
2698
if if_present_ids is None:
2699
if_present_ids = set()
2700
revision_ids = set(revision_ids)
2701
if_present_ids = set(if_present_ids)
2702
all_wanted_ids = revision_ids.union(if_present_ids)
2703
graph = self.source.get_graph()
2704
present_revs = set(graph.get_parent_map(all_wanted_ids))
2705
missing = revision_ids.difference(present_revs)
2707
raise errors.NoSuchRevision(self.source, missing.pop())
2708
found_ids = all_wanted_ids.intersection(present_revs)
2709
source_ids = [rev_id for (rev_id, parents) in
2710
graph.iter_ancestry(found_ids)
2711
if rev_id != _mod_revision.NULL_REVISION
2712
and parents is not None]
2714
source_ids = self.source.all_revision_ids()
2715
return set(source_ids)
2718
def _get_repo_format_to_test(self):
2722
def is_compatible(cls, source, target):
2723
# The default implementation is compatible with everything
2724
return (source._format.supports_full_versioned_files and
2725
target._format.supports_full_versioned_files)
2728
class InterDifferingSerializer(InterVersionedFileRepository):
2731
def _get_repo_format_to_test(self):
2735
def is_compatible(source, target):
2736
if not source._format.supports_full_versioned_files:
2738
if not target._format.supports_full_versioned_files:
2740
# This is redundant with format.check_conversion_target(), however that
2741
# raises an exception, and we just want to say "False" as in we won't
2742
# support converting between these formats.
2743
if 'IDS_never' in debug.debug_flags:
2745
if source.supports_rich_root() and not target.supports_rich_root():
2747
if (source._format.supports_tree_reference
2748
and not target._format.supports_tree_reference):
2750
if target._fallback_repositories and target._format.supports_chks:
2751
# IDS doesn't know how to copy CHKs for the parent inventories it
2752
# adds to stacked repos.
2754
if 'IDS_always' in debug.debug_flags:
2756
# Only use this code path for local source and target. IDS does far
2757
# too much IO (both bandwidth and roundtrips) over a network.
2758
if not source.controldir.transport.base.startswith('file:///'):
2760
if not target.controldir.transport.base.startswith('file:///'):
2764
def _get_trees(self, revision_ids, cache):
2766
for rev_id in revision_ids:
2768
possible_trees.append((rev_id, cache[rev_id]))
2770
# Not cached, but inventory might be present anyway.
2772
tree = self.source.revision_tree(rev_id)
2773
except errors.NoSuchRevision:
2774
# Nope, parent is ghost.
2777
cache[rev_id] = tree
2778
possible_trees.append((rev_id, tree))
2779
return possible_trees
2781
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2782
"""Get the best delta and base for this revision.
2784
:return: (basis_id, delta)
2787
# Generate deltas against each tree, to find the shortest.
2788
# FIXME: Support nested trees
2789
texts_possibly_new_in_tree = set()
2790
for basis_id, basis_tree in possible_trees:
2791
delta = tree.root_inventory._make_delta(basis_tree.root_inventory)
2792
for old_path, new_path, file_id, new_entry in delta:
2793
if new_path is None:
2794
# This file_id isn't present in the new rev, so we don't
2798
# Rich roots are handled elsewhere...
2800
kind = new_entry.kind
2801
if kind != 'directory' and kind != 'file':
2802
# No text record associated with this inventory entry.
2804
# This is a directory or file that has changed somehow.
2805
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2806
deltas.append((len(delta), basis_id, delta))
2808
return deltas[0][1:]
2810
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2811
"""Find all parent revisions that are absent, but for which the
2812
inventory is present, and copy those inventories.
2814
This is necessary to preserve correctness when the source is stacked
2815
without fallbacks configured. (Note that in cases like upgrade the
2816
source may be not have _fallback_repositories even though it is
2819
parent_revs = set(itertools.chain.from_iterable(viewvalues(
2821
present_parents = self.source.get_parent_map(parent_revs)
2822
absent_parents = parent_revs.difference(present_parents)
2823
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2824
(rev_id,) for rev_id in absent_parents)
2825
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2826
for parent_tree in self.source.revision_trees(parent_inv_ids):
2827
current_revision_id = parent_tree.get_revision_id()
2828
parents_parents_keys = parent_invs_keys_for_stacking[
2829
(current_revision_id,)]
2830
parents_parents = [key[-1] for key in parents_parents_keys]
2831
basis_id = _mod_revision.NULL_REVISION
2832
basis_tree = self.source.revision_tree(basis_id)
2833
delta = parent_tree.root_inventory._make_delta(
2834
basis_tree.root_inventory)
2835
self.target.add_inventory_by_delta(
2836
basis_id, delta, current_revision_id, parents_parents)
2837
cache[current_revision_id] = parent_tree
2839
def _fetch_batch(self, revision_ids, basis_id, cache):
2840
"""Fetch across a few revisions.
2842
:param revision_ids: The revisions to copy
2843
:param basis_id: The revision_id of a tree that must be in cache, used
2844
as a basis for delta when no other base is available
2845
:param cache: A cache of RevisionTrees that we can use.
2846
:return: The revision_id of the last converted tree. The RevisionTree
2847
for it will be in cache
2849
# Walk though all revisions; get inventory deltas, copy referenced
2850
# texts that delta references, insert the delta, revision and
2852
root_keys_to_create = set()
2855
pending_revisions = []
2856
parent_map = self.source.get_parent_map(revision_ids)
2857
self._fetch_parent_invs_for_stacking(parent_map, cache)
2858
self.source._safe_to_return_from_cache = True
2859
for tree in self.source.revision_trees(revision_ids):
2860
# Find a inventory delta for this revision.
2861
# Find text entries that need to be copied, too.
2862
current_revision_id = tree.get_revision_id()
2863
parent_ids = parent_map.get(current_revision_id, ())
2864
parent_trees = self._get_trees(parent_ids, cache)
2865
possible_trees = list(parent_trees)
2866
if len(possible_trees) == 0:
2867
# There either aren't any parents, or the parents are ghosts,
2868
# so just use the last converted tree.
2869
possible_trees.append((basis_id, cache[basis_id]))
2870
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2872
revision = self.source.get_revision(current_revision_id)
2873
pending_deltas.append((basis_id, delta,
2874
current_revision_id, revision.parent_ids))
2875
if self._converting_to_rich_root:
2876
self._revision_id_to_root_id[current_revision_id] = \
2878
# Determine which texts are in present in this revision but not in
2879
# any of the available parents.
2880
texts_possibly_new_in_tree = set()
2881
for old_path, new_path, file_id, entry in delta:
2882
if new_path is None:
2883
# This file_id isn't present in the new rev
2887
if not self.target.supports_rich_root():
2888
# The target doesn't support rich root, so we don't
2891
if self._converting_to_rich_root:
2892
# This can't be copied normally, we have to insert
2894
root_keys_to_create.add((file_id, entry.revision))
2897
texts_possibly_new_in_tree.add((file_id, entry.revision))
2898
for basis_id, basis_tree in possible_trees:
2899
basis_inv = basis_tree.root_inventory
2900
for file_key in list(texts_possibly_new_in_tree):
2901
file_id, file_revision = file_key
2903
entry = basis_inv[file_id]
2904
except errors.NoSuchId:
2906
if entry.revision == file_revision:
2907
texts_possibly_new_in_tree.remove(file_key)
2908
text_keys.update(texts_possibly_new_in_tree)
2909
pending_revisions.append(revision)
2910
cache[current_revision_id] = tree
2911
basis_id = current_revision_id
2912
self.source._safe_to_return_from_cache = False
2914
from_texts = self.source.texts
2915
to_texts = self.target.texts
2916
if root_keys_to_create:
2917
root_stream = _mod_fetch._new_root_data_stream(
2918
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2920
to_texts.insert_record_stream(root_stream)
2921
to_texts.insert_record_stream(from_texts.get_record_stream(
2922
text_keys, self.target._format._fetch_order,
2923
not self.target._format._fetch_uses_deltas))
2924
# insert inventory deltas
2925
for delta in pending_deltas:
2926
self.target.add_inventory_by_delta(*delta)
2927
if self.target._fallback_repositories:
2928
# Make sure this stacked repository has all the parent inventories
2929
# for the new revisions that we are about to insert. We do this
2930
# before adding the revisions so that no revision is added until
2931
# all the inventories it may depend on are added.
2932
# Note that this is overzealous, as we may have fetched these in an
2935
revision_ids = set()
2936
for revision in pending_revisions:
2937
revision_ids.add(revision.revision_id)
2938
parent_ids.update(revision.parent_ids)
2939
parent_ids.difference_update(revision_ids)
2940
parent_ids.discard(_mod_revision.NULL_REVISION)
2941
parent_map = self.source.get_parent_map(parent_ids)
2942
# we iterate over parent_map and not parent_ids because we don't
2943
# want to try copying any revision which is a ghost
2944
for parent_tree in self.source.revision_trees(parent_map):
2945
current_revision_id = parent_tree.get_revision_id()
2946
parents_parents = parent_map[current_revision_id]
2947
possible_trees = self._get_trees(parents_parents, cache)
2948
if len(possible_trees) == 0:
2949
# There either aren't any parents, or the parents are
2950
# ghosts, so just use the last converted tree.
2951
possible_trees.append((basis_id, cache[basis_id]))
2952
basis_id, delta = self._get_delta_for_revision(parent_tree,
2953
parents_parents, possible_trees)
2954
self.target.add_inventory_by_delta(
2955
basis_id, delta, current_revision_id, parents_parents)
2956
# insert signatures and revisions
2957
for revision in pending_revisions:
2959
signature = self.source.get_signature_text(
2960
revision.revision_id)
2961
self.target.add_signature_text(revision.revision_id,
2963
except errors.NoSuchRevision:
2965
self.target.add_revision(revision.revision_id, revision)
2968
def _fetch_all_revisions(self, revision_ids, pb):
2969
"""Fetch everything for the list of revisions.
2971
:param revision_ids: The list of revisions to fetch. Must be in
2973
:param pb: A ProgressTask
2976
basis_id, basis_tree = self._get_basis(revision_ids[0])
2978
cache = lru_cache.LRUCache(100)
2979
cache[basis_id] = basis_tree
2980
del basis_tree # We don't want to hang on to it here
2984
for offset in range(0, len(revision_ids), batch_size):
2985
self.target.start_write_group()
2987
pb.update(gettext('Transferring revisions'), offset,
2989
batch = revision_ids[offset:offset+batch_size]
2990
basis_id = self._fetch_batch(batch, basis_id, cache)
2992
self.source._safe_to_return_from_cache = False
2993
self.target.abort_write_group()
2996
hint = self.target.commit_write_group()
2999
if hints and self.target._format.pack_compresses:
3000
self.target.pack(hint=hints)
3001
pb.update(gettext('Transferring revisions'), len(revision_ids),
3005
def fetch(self, revision_id=None, find_ghosts=False,
3007
"""See InterRepository.fetch()."""
3008
if fetch_spec is not None:
3009
revision_ids = fetch_spec.get_keys()
3012
if self.source._format.experimental:
3013
ui.ui_factory.show_user_warning('experimental_format_fetch',
3014
from_format=self.source._format,
3015
to_format=self.target._format)
3016
if (not self.source.supports_rich_root()
3017
and self.target.supports_rich_root()):
3018
self._converting_to_rich_root = True
3019
self._revision_id_to_root_id = {}
3021
self._converting_to_rich_root = False
3022
# See <https://launchpad.net/bugs/456077> asking for a warning here
3023
if self.source._format.network_name() != self.target._format.network_name():
3024
ui.ui_factory.show_user_warning('cross_format_fetch',
3025
from_format=self.source._format,
3026
to_format=self.target._format)
3027
if revision_ids is None:
3029
search_revision_ids = [revision_id]
3031
search_revision_ids = None
3032
revision_ids = self.target.search_missing_revision_ids(self.source,
3033
revision_ids=search_revision_ids,
3034
find_ghosts=find_ghosts).get_keys()
3035
if not revision_ids:
3037
revision_ids = tsort.topo_sort(
3038
self.source.get_graph().get_parent_map(revision_ids))
3039
if not revision_ids:
3041
# Walk though all revisions; get inventory deltas, copy referenced
3042
# texts that delta references, insert the delta, revision and
3044
pb = ui.ui_factory.nested_progress_bar()
3046
self._fetch_all_revisions(revision_ids, pb)
3049
return len(revision_ids), 0
3051
def _get_basis(self, first_revision_id):
3052
"""Get a revision and tree which exists in the target.
3054
This assumes that first_revision_id is selected for transmission
3055
because all other ancestors are already present. If we can't find an
3056
ancestor we fall back to NULL_REVISION since we know that is safe.
3058
:return: (basis_id, basis_tree)
3060
first_rev = self.source.get_revision(first_revision_id)
3062
basis_id = first_rev.parent_ids[0]
3063
# only valid as a basis if the target has it
3064
self.target.get_revision(basis_id)
3065
# Try to get a basis tree - if it's a ghost it will hit the
3066
# NoSuchRevision case.
3067
basis_tree = self.source.revision_tree(basis_id)
3068
except (IndexError, errors.NoSuchRevision):
3069
basis_id = _mod_revision.NULL_REVISION
3070
basis_tree = self.source.revision_tree(basis_id)
3071
return basis_id, basis_tree
3074
class InterSameDataRepository(InterVersionedFileRepository):
3075
"""Code for converting between repositories that represent the same data.
3077
Data format and model must match for this to work.
3081
def _get_repo_format_to_test(self):
3082
"""Repository format for testing with.
3084
InterSameData can pull from subtree to subtree and from non-subtree to
3085
non-subtree, so we test this with the richest repository format.
3087
from breezy.bzr import knitrepo
3088
return knitrepo.RepositoryFormatKnit3()
3091
def is_compatible(source, target):
3093
InterRepository._same_model(source, target) and
3094
source._format.supports_full_versioned_files and
3095
target._format.supports_full_versioned_files)
3098
InterRepository.register_optimiser(InterVersionedFileRepository)
3099
InterRepository.register_optimiser(InterDifferingSerializer)
3100
InterRepository.register_optimiser(InterSameDataRepository)
3103
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3104
"""Install all revision data into a repository.
3106
Accepts an iterable of revision, tree, signature tuples. The signature
3109
repository.start_write_group()
3111
inventory_cache = lru_cache.LRUCache(10)
3112
for n, (revision, revision_tree, signature) in enumerate(iterable):
3113
_install_revision(repository, revision, revision_tree, signature,
3116
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3118
repository.abort_write_group()
3121
repository.commit_write_group()
3124
def _install_revision(repository, rev, revision_tree, signature,
3126
"""Install all revision data into a repository."""
3127
present_parents = []
3129
for p_id in rev.parent_ids:
3130
if repository.has_revision(p_id):
3131
present_parents.append(p_id)
3132
parent_trees[p_id] = repository.revision_tree(p_id)
3134
parent_trees[p_id] = repository.revision_tree(
3135
_mod_revision.NULL_REVISION)
3137
# FIXME: Support nested trees
3138
inv = revision_tree.root_inventory
3139
entries = inv.iter_entries()
3140
# backwards compatibility hack: skip the root id.
3141
if not repository.supports_rich_root():
3142
path, root = next(entries)
3143
if root.revision != rev.revision_id:
3144
raise errors.IncompatibleRevision(repr(repository))
3146
for path, ie in entries:
3147
text_keys[(ie.file_id, ie.revision)] = ie
3148
text_parent_map = repository.texts.get_parent_map(text_keys)
3149
missing_texts = set(text_keys) - set(text_parent_map)
3150
# Add the texts that are not already present
3151
for text_key in missing_texts:
3152
ie = text_keys[text_key]
3154
# FIXME: TODO: The following loop overlaps/duplicates that done by
3155
# commit to determine parents. There is a latent/real bug here where
3156
# the parents inserted are not those commit would do - in particular
3157
# they are not filtered by heads(). RBC, AB
3158
for revision, tree in viewitems(parent_trees):
3159
if not tree.has_id(ie.file_id):
3161
parent_id = tree.get_file_revision(ie.file_id)
3162
if parent_id in text_parents:
3164
text_parents.append((ie.file_id, parent_id))
3165
lines = revision_tree.get_file(ie.file_id).readlines()
3166
repository.texts.add_lines(text_key, text_parents, lines)
3168
# install the inventory
3169
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3170
# Cache this inventory
3171
inventory_cache[rev.revision_id] = inv
3173
basis_inv = inventory_cache[rev.parent_ids[0]]
3175
repository.add_inventory(rev.revision_id, inv, present_parents)
3177
delta = inv._make_delta(basis_inv)
3178
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3179
rev.revision_id, present_parents)
3181
repository.add_inventory(rev.revision_id, inv, present_parents)
3182
except errors.RevisionAlreadyPresent:
3184
if signature is not None:
3185
repository.add_signature_text(rev.revision_id, signature)
3186
repository.add_revision(rev.revision_id, rev, inv)
3189
def install_revision(repository, rev, revision_tree):
3190
"""Install all revision data into a repository."""
3191
install_revisions(repository, [(rev, revision_tree, None)])